Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Tighten the digital assets code after review

Damian Legawiec70fb76c59971
diff --git a/packages/dashboard-core/src/components/file-upload-field.tsx b/packages/dashboard-core/src/components/file-upload-field.tsx
index ff313973aa..01b0046801 100644
--- a/packages/dashboard-core/src/components/file-upload-field.tsx
+++ b/packages/dashboard-core/src/components/file-upload-field.tsx
@@ -43,7 +43,9 @@ export const EMPTY_FILE_UPLOAD_VALUE: FileUploadValue = {
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+ // Digital products are sold in gigabytes — sample packs, video, disk images.
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`
}
export interface FileUploadFieldProps {
diff --git a/packages/dashboard-ui/src/ui/badge.tsx b/packages/dashboard-ui/src/ui/badge.tsx
index f3bf782e44..ee7cbcbccc 100644
--- a/packages/dashboard-ui/src/ui/badge.tsx
+++ b/packages/dashboard-ui/src/ui/badge.tsx
@@ -84,6 +84,7 @@ const statusVariantMap: Record<string, VariantProps<typeof badgeVariants>['varia
revoked: 'destructive',
expired: 'destructive',
ready: 'warning',
+ available: 'success',
draft: 'outline',
pending: 'warning',
processing: 'warning',
@@ -105,6 +106,7 @@ const statusVariantMap: Record<string, VariantProps<typeof badgeVariants>['varia
void: 'destructive',
error: 'destructive',
rejected: 'destructive',
+ used_up: 'destructive',
}
/**
diff --git a/packages/dashboard/src/components/spree/order-digital-links-card.tsx b/packages/dashboard/src/components/spree/order-digital-links-card.tsx
index c88d91ad89..177702fc79 100644
--- a/packages/dashboard/src/components/spree/order-digital-links-card.tsx
+++ b/packages/dashboard/src/components/spree/order-digital-links-card.tsx
@@ -1,13 +1,13 @@
import type { DigitalLink, Order } from '@spree/admin-sdk'
import { formatStoreDateTime, useStore } from '@spree/dashboard-core'
import {
- Badge,
Button,
Card,
CardAction,
CardContent,
CardHeader,
CardTitle,
+ StatusBadge,
Table,
TableBody,
TableCell,
@@ -46,14 +46,12 @@ export function OrderDigitalLinksCard({ order }: { order: Order }) {
if (confirmed) await resetLink.mutateAsync(row.link.id)
}
- function statusBadge(link: DigitalLink) {
- if (link.expired) {
- return <Badge variant="destructive">{t('admin.digital_links.status.expired')}</Badge>
- }
- if (link.access_limit_exceeded) {
- return <Badge variant="destructive">{t('admin.digital_links.status.used_up')}</Badge>
- }
- return <Badge variant="secondary">{t('admin.digital_links.status.available')}</Badge>
+ // `authorizable` already folds both refusal reasons; the specific one is
+ // what the merchant needs to see, so it is named rather than inferred.
+ function statusFor(link: DigitalLink): 'expired' | 'used_up' | 'available' {
+ if (link.expired) return 'expired'
+ if (link.access_limit_exceeded) return 'used_up'
+ return 'available'
}
return (
@@ -97,7 +95,12 @@ export function OrderDigitalLinksCard({ order }: { order: Order }) {
? formatStoreDateTime(row.link.expires_at, timezone)
: t('admin.digital_links.never_expires')}
</TableCell>
- <TableCell>{statusBadge(row.link)}</TableCell>
+ <TableCell>
+ <StatusBadge
+ status={statusFor(row.link)}
+ label={t(`admin.digital_links.status.${statusFor(row.link)}`)}
+ />
+ </TableCell>
<TableCell className="text-right">
<Button
type="button"
diff --git a/packages/dashboard/src/components/spree/products/digital-assets-card.tsx b/packages/dashboard/src/components/spree/products/digital-assets-card.tsx
index 744848a261..ce9b301b2b 100644
--- a/packages/dashboard/src/components/spree/products/digital-assets-card.tsx
+++ b/packages/dashboard/src/components/spree/products/digital-assets-card.tsx
@@ -1,5 +1,5 @@
import type { DigitalAsset, Variant } from '@spree/admin-sdk'
-import { useDirectUpload } from '@spree/dashboard-core'
+import { formatFileSize, useDirectUpload } from '@spree/dashboard-core'
import {
Button,
Card,
@@ -7,6 +7,7 @@ import {
CardHeader,
CardTitle,
Input,
+ Pagination,
Select,
SelectContent,
SelectItem,
@@ -31,17 +32,7 @@ import {
useUpdateDigitalAsset,
} from '../../../hooks/use-digital-assets'
-function formatFileSize(bytes: number | null | undefined): string {
- if (!bytes) return '—'
- const units = ['B', 'KB', 'MB', 'GB']
- let value = bytes
- let unit = 0
- while (value >= 1024 && unit < units.length - 1) {
- value /= 1024
- unit++
- }
- return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`
-}
+type LimitField = 'authorized_clicks' | 'authorized_days'
export function DigitalAssetsCard({
productId,
@@ -55,16 +46,18 @@ export function DigitalAssetsCard({
const fileInputRef = useRef<HTMLInputElement>(null)
const [uploadingName, setUploadingName] = useState<string | null>(null)
const [selectedVariantId, setSelectedVariantId] = useState<string>('')
+ const [page, setPage] = useState(1)
// Digital files live on private storage: they are only ever served through an
// authorized, signed link, never from the public bucket.
const directUpload = useDirectUpload({ private: true })
- const { data, isLoading } = useDigitalAssets(productId ?? '', Boolean(productId))
+ const { data, isLoading } = useDigitalAssets(productId ?? '', page, Boolean(productId))
const createAsset = useCreateDigitalAsset(productId ?? '')
const updateAsset = useUpdateDigitalAsset(productId ?? '')
const deleteAsset = useDeleteDigitalAsset(productId ?? '')
const assets: DigitalAsset[] = data?.data ?? []
+ const meta = data?.meta
const hasVariants = (variants?.length ?? 0) > 1
async function handleFileSelected(event: React.ChangeEvent<HTMLInputElement>) {
@@ -79,6 +72,7 @@ export function DigitalAssetsCard({
signed_id: signedId,
...(selectedVariantId ? { variant_id: selectedVariantId } : {}),
})
+ setPage(1)
} finally {
setUploadingName(null)
}
@@ -95,14 +89,40 @@ export function DigitalAssetsCard({
if (confirmed) await deleteAsset.mutateAsync(asset.id)
}
- function handleLimitChange(asset: DigitalAsset, field: 'clicks' | 'days', raw: string) {
+ // Blank means "use the store setting", so an empty box is a real value.
+ function handleLimitChange(asset: DigitalAsset, field: LimitField, raw: string) {
const parsed = raw.trim() === '' ? null : Number(raw)
if (parsed !== null && (!Number.isFinite(parsed) || parsed < 1)) return
- updateAsset.mutate({
- id: asset.id,
- ...(field === 'clicks' ? { authorized_clicks: parsed } : { authorized_days: parsed }),
- })
+ updateAsset.mutate({ id: asset.id, [field]: parsed })
+ }
+
+ function LimitCell({
+ asset,
+ field,
+ effective,
+ }: {
+ asset: DigitalAsset
+ field: LimitField
+ effective: number
+ }) {
+ const label = t(
+ field === 'authorized_clicks'
+ ? 'admin.digital_assets.columns.downloads'
+ : 'admin.digital_assets.columns.days',
+ )
+
+ return (
+ <Input
+ type="number"
+ min={1}
+ className="w-24"
+ defaultValue={asset[field] ?? ''}
+ placeholder={String(effective)}
+ aria-label={label}
+ onBlur={(e) => handleLimitChange(asset, field, e.target.value)}
+ />
+ )
}
if (!productId) return null
@@ -149,28 +169,20 @@ export function DigitalAssetsCard({
</TableCell>
)}
<TableCell className="tabular-nums">
- {formatFileSize(asset.byte_size)}
+ {asset.byte_size ? formatFileSize(asset.byte_size) : '—'}
</TableCell>
<TableCell>
- <Input
- type="number"
- min={1}
- className="w-24"
- defaultValue={asset.authorized_clicks ?? ''}
- placeholder={String(asset.effective_authorized_clicks)}
- aria-label={t('admin.digital_assets.columns.downloads')}
- onBlur={(e) => handleLimitChange(asset, 'clicks', e.target.value)}
+ <LimitCell
+ asset={asset}
+ field="authorized_clicks"
+ effective={asset.effective_authorized_clicks}
/>
</TableCell>
<TableCell>
- <Input
- type="number"
- min={1}
- className="w-24"
- defaultValue={asset.authorized_days ?? ''}
- placeholder={String(asset.effective_authorized_days)}
- aria-label={t('admin.digital_assets.columns.days')}
- onBlur={(e) => handleLimitChange(asset, 'days', e.target.value)}
+ <LimitCell
+ asset={asset}
+ field="authorized_days"
+ effective={asset.effective_authorized_days}
/>
</TableCell>
<TableCell className="text-right">
@@ -188,6 +200,7 @@ export function DigitalAssetsCard({
))}
</TableBody>
</Table>
+ {meta && <Pagination meta={meta} onPageChange={setPage} />}
</div>
)}
diff --git a/packages/dashboard/src/hooks/use-digital-assets.ts b/packages/dashboard/src/hooks/use-digital-assets.ts
index f8fc852752..5e166cfc1d 100644
--- a/packages/dashboard/src/hooks/use-digital-assets.ts
+++ b/packages/dashboard/src/hooks/use-digital-assets.ts
@@ -4,14 +4,12 @@ import { useQuery } from '@tanstack/react-query'
type DigitalAssetCreateParams = Parameters<typeof adminClient.products.digitalAssets.create>[1]
type DigitalAssetUpdateParams = Parameters<typeof adminClient.products.digitalAssets.update>[2]
-export type { DigitalAssetCreateParams, DigitalAssetUpdateParams }
-
-export function useDigitalAssets(productId: string, enabled = true) {
+export function useDigitalAssets(productId: string, page = 1, enabled = true) {
const { storeId } = useStore()
return useQuery({
- queryKey: [storeId, 'products', productId, 'digital-assets'],
- queryFn: () => adminClient.products.digitalAssets.list(productId, { per_page: 100 }),
+ queryKey: [storeId, 'products', productId, 'digital-assets', page],
+ queryFn: () => adminClient.products.digitalAssets.list(productId, { page, per_page: 25 }),
enabled: enabled && Boolean(productId),
})
}
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index 190ca06feb..b272325b48 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -1087,9 +1087,6 @@ export class StoreClient {
params: transformListParams({ ...params }),
}),
- /**
- * Get one download by ID.
- */
/**
* Get one download by ID. Each record carries a `download_url` — point the
* browser at it; the response redirects to short-lived storage, so follow
diff --git a/spree/api/app/controllers/spree/api/v3/admin/digital_links_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/digital_links_controller.rb
index 76f21f785d..99a78bb562 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/digital_links_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/digital_links_controller.rb
@@ -35,10 +35,6 @@ module Spree
def scope_includes
[:line_item, digital_asset: { attachment_attachment: :blob }]
end
-
- def authorize_resource!(resource = @resource, action = action_name.to_sym)
- authorize!(action == :reset ? :update : action, resource)
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
index 03d6997ecb..88d16d45b4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
@@ -11,11 +11,20 @@ module Spree
# Replacing the file keeps every already-issued link working, since
# links resolve through the asset rather than the blob.
def update
+ return render_private_storage_error unless uploaded_blob_private?
+
attach_uploaded_file(@resource)
super
end
+ # POST /api/v3/admin/products/:product_id/digital_assets
+ def create
+ return render_private_storage_error unless uploaded_blob_private?
+
+ super
+ end
+
protected
def model_class
@@ -61,6 +70,20 @@ module Spree
digital_asset.attachment.attach(params[:signed_id])
end
+
+ # Attaching never moves a blob between storage services, so a file
+ # uploaded to the public bucket would stay publicly readable while
+ # looking attached. Refuse it rather than storing it wrongly.
+ def uploaded_blob_private?
+ return true if params[:signed_id].blank?
+
+ blob = ActiveStorage::Blob.find_signed(params[:signed_id])
+ blob.present? && blob.service_name.to_s == Spree.private_storage_service_name.to_s
+ end
+
+ def render_private_storage_error
+ render_validation_error(Spree.t('digital_assets.attachment_must_be_private'))
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/digital_links_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/digital_links_controller.rb
index 1c003c6d83..fe62281909 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customer/digital_links_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customer/digital_links_controller.rb
@@ -19,15 +19,23 @@ module Spree
Spree.api.digital_link_serializer
end
+ def set_parent
+ @parent = current_user
+ end
+
+ def parent_association
+ :digital_links
+ end
+
def scope
- Spree::DigitalLink.
- joins(line_item: :order).
- where(spree_orders: { id: current_user.orders.complete.where(store: current_store) }).
- order(created_at: :desc)
+ super.where(spree_orders: { store_id: current_store.id }).order(created_at: :desc)
end
+ # The serializer asks each link whether it is still authorizable,
+ # which reads its order's store and its asset's limits — without
+ # both preloads that is four queries per row.
def scope_includes
- [digital_asset: { attachment_attachment: :blob }]
+ [{ line_item: :order }, { digital_asset: { attachment_attachment: :blob } }]
end
end
end
diff --git a/spree/api/app/models/spree/api/digital_link_urls.rb b/spree/api/app/models/spree/api/digital_link_urls.rb
new file mode 100644
index 0000000000..fa2b23dfcd
--- /dev/null
+++ b/spree/api/app/models/spree/api/digital_link_urls.rb
@@ -0,0 +1,26 @@
+module Spree
+ module Api
+ # The one place that knows how a download link is addressed. Both consumers
+ # live in different gems — the store serializer emits the path, the email
+ # needs it absolute — and the route only exists here, in the gem that draws
+ # it, so neither the core model nor the emails gem can own this.
+ module DigitalLinkUrls
+ module_function
+
+ # @param digital_link [Spree::DigitalLink]
+ # @return [String] path relative to the API host
+ def download_path(digital_link)
+ Spree::Core::Engine.routes.url_helpers.api_v3_store_digital_link_download_path(
+ token: digital_link.token
+ )
+ end
+
+ # @param digital_link [Spree::DigitalLink]
+ # @param host [String] the backend's own URL
+ # @return [String] absolute URL, for emails and anything else off-request
+ def download_url(digital_link, host)
+ URI.join(host, download_path(digital_link)).to_s
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb b/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
index 107cf9e53d..b975581122 100644
--- a/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/digital_link_serializer.rb
@@ -9,7 +9,7 @@ module Spree
attributes :access_counter, :filename, :content_type
attribute :download_url do |digital_link|
- Spree::Core::Engine.routes.url_helpers.api_v3_store_digital_link_download_path(token: digital_link.token)
+ Spree::Api::DigitalLinkUrls.download_path(digital_link)
end
attribute :expires_at do |digital_link|
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/digital_links_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/digital_links_controller_spec.rb
index 88f1541b59..69a3cdfd25 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/digital_links_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/digital_links_controller_spec.rb
@@ -65,4 +65,26 @@ RSpec.describe Spree::Api::V3::Admin::DigitalLinksController, type: :controller
expect(response).to have_http_status(:not_found)
end
end
+
+ # Reset is a write: the catalog grants :manage for write_orders, so no
+ # per-action mapping is needed — but the deny path is worth pinning.
+ describe 'scope enforcement' do
+ it 'denies reset to a read-only key' do
+ read_key = create(:api_key, :secret, store: store, scopes: ['read_orders'])
+ request.headers['x-spree-api-key'] = read_key.plaintext_token
+
+ patch :reset, params: { id: digital_link.prefixed_id }
+
+ expect(response.status).to be_in([401, 403])
+ end
+
+ it 'allows reset with a write key' do
+ write_key = create(:api_key, :secret, store: store, scopes: ['write_orders', 'read_orders'])
+ request.headers['x-spree-api-key'] = write_key.plaintext_token
+
+ patch :reset, params: { id: digital_link.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
index 4997004d0c..091e640b91 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
@@ -69,6 +69,23 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :
expect(response).to have_http_status(:unprocessable_entity)
end
+ # Dev and test collapse both storage services onto one, so the distinction
+ # only exists in a deployed configuration — stub it to exercise the guard.
+ it 'refuses a file uploaded to public storage' do
+ # The blob is built first, then the expected service is changed, so the
+ # already-uploaded file looks like it landed on the wrong bucket.
+ signed_id = blob.signed_id
+ allow(Spree).to receive(:private_storage_service_name).and_return(:private_bucket)
+
+ post :create, params: {
+ product_id: product.prefixed_id,
+ signed_id: signed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(Spree::DigitalAsset.count).to eq(0)
+ end
+
it 'rejects a non-positive limit' do
post :create, params: {
product_id: product.prefixed_id,
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
index 3289c798c6..2fd9f9602b 100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -61,6 +61,10 @@ module Spree
has_many :carts, -> { incomplete }, foreign_key: :customer_id, class_name: 'Spree::Order'
has_many :completed_orders, -> { complete }, foreign_key: :customer_id, class_name: 'Spree::Order'
has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :customer_id, dependent: :destroy
+ # Everything the customer has bought and can download. Scoped to completed
+ # orders — a link on an abandoned cart was never paid for.
+ has_many :completed_order_line_items, through: :completed_orders, source: :line_items, class_name: 'Spree::LineItem'
+ has_many :digital_links, through: :completed_order_line_items, source: :digital_links, class_name: 'Spree::DigitalLink'
has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :customer_id, dependent: :destroy
has_many :wished_items, through: :wishlists, source: :wished_items
has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :customer_id
diff --git a/spree/core/app/models/concerns/spree/purchase/digital_items.rb b/spree/core/app/models/concerns/spree/purchase/digital_items.rb
index 75f5b6c83b..c88eafd567 100644
--- a/spree/core/app/models/concerns/spree/purchase/digital_items.rb
+++ b/spree/core/app/models/concerns/spree/purchase/digital_items.rb
@@ -36,9 +36,14 @@ module Spree
line_items.joins(:variant).with_digital_assets.distinct
end
- # @return [Array<Spree::DigitalLink>]
+ # One query rather than one per line item — this is read for every
+ # digital order's email. `reorder(nil)` drops the line-item default order:
+ # PostgreSQL rejects SELECT DISTINCT ordered by a column that is not in
+ # the select list, and ordering a subquery buys nothing anyway.
+ #
+ # @return [ActiveRecord::Relation<Spree::DigitalLink>]
def digital_links
- digital_line_items.map(&:digital_links).flatten
+ Spree::DigitalLink.where(line_item_id: digital_line_items.reorder(nil).select(:id))
end
# Whether the customer must choose a delivery option in checkout —
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 522120663f..ae0b20334e 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -883,6 +883,7 @@ en:
subject: Your files are ready
thanks: Thank you for your business.
digital_assets: Digital assets
+ digital_assets_attachment_must_be_private: Upload the file to private storage before attaching it
discontinue_on: Discontinue On
discontinued: Discontinued
discontinued_variants_present: Some line items in this order have products that are no longer available.
diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rb
index ca290a43f9..a07b53cb01 100644
--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb
@@ -153,6 +153,32 @@ module Spree
end
end
+ # The files-ready email subscribes to order.placed and bails when the order
+ # has no links, so link creation moving after the publish would turn into
+ # silence rather than a failure. Pin the ordering here.
+ describe 'digital links and order.placed' do
+ let(:digital_variant) { create(:variant) }
+ let!(:digital_asset) { create(:digital_asset, variant: digital_variant) }
+
+ before do
+ order.line_items.create!(variant: digital_variant, quantity: 2, price: 10)
+ order.recalculate_totals!
+ end
+
+ it 'has created the links by the time order.placed fires' do
+ links_at_publish = nil
+
+ allow_any_instance_of(Spree::Order).to receive(:publish_event).and_wrap_original do |original, *args|
+ links_at_publish ||= original.receiver.digital_links.count if args.first == 'order.placed'
+ original.call(*args)
+ end
+
+ described_class.call(order: order, payment_pending: true)
+
+ expect(links_at_publish).to eq(2)
+ end
+ end
+
context 'order is not considered risky' do
before do
allow(order).to receive_messages(is_risky?: false)
diff --git a/spree/emails/app/helpers/spree/digital_asset_helper.rb b/spree/emails/app/helpers/spree/digital_asset_helper.rb
index 364c37a4ce..5549bdde72 100644
--- a/spree/emails/app/helpers/spree/digital_asset_helper.rb
+++ b/spree/emails/app/helpers/spree/digital_asset_helper.rb
@@ -3,14 +3,14 @@ module Spree
# Emails need an absolute link — the route helper only produces a path, and
# the download endpoint lives on the backend rather than the storefront.
#
+ # The host is passed in rather than resolved per link: every link in one
+ # email belongs to the same order, so its store is already known.
+ #
# @param digital_link [Spree::DigitalLink]
+ # @param host [String] the backend's own URL
# @return [String]
- def digital_link_download_url(digital_link)
- path = Spree::Core::Engine.routes.url_helpers.api_v3_store_digital_link_download_path(
- token: digital_link.token
- )
-
- URI.join(digital_link.order.store.formatted_url, path).to_s
+ def digital_link_download_url(digital_link, host)
+ Spree::Api::DigitalLinkUrls.download_url(digital_link, host)
end
end
end
diff --git a/spree/emails/app/mailers/spree/digital_asset_mailer.rb b/spree/emails/app/mailers/spree/digital_asset_mailer.rb
index ae600e9f4f..5389429d89 100644
--- a/spree/emails/app/mailers/spree/digital_asset_mailer.rb
+++ b/spree/emails/app/mailers/spree/digital_asset_mailer.rb
@@ -8,10 +8,13 @@ module Spree
# replaces the confirmation email does not silently lose the links.
def files_ready_email(order, resend = false)
@order = order.respond_to?(:id) ? order : Spree::Order.find(order)
- @digital_links = @order.digital_links
+ # The template reads each link's filename and expiry, both of which reach
+ # through the asset — preload rather than paying per link.
+ @digital_links = @order.digital_links.includes(digital_asset: { attachment_attachment: :blob })
return if @digital_links.empty?
current_store = @order.store
+ @download_host = current_store.formatted_url
with_store_locale(current_store, @order.locale) do
subject = order_email_subject(
current_store,
diff --git a/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.html.erb b/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.html.erb
index 42c722859b..9b8f3f6fde 100644
--- a/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.html.erb
+++ b/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.html.erb
@@ -8,7 +8,7 @@
<% @digital_links.each do |digital_link| %>
<tr>
<td style="padding: 8px 0;">
- <a href="<%= digital_link_download_url(digital_link) %>"><%= digital_link.filename %></a>
+ <a href="<%= digital_link_download_url(digital_link, @download_host) %>"><%= digital_link.filename %></a>
<% if digital_link.expires_at %>
<div style="font-size: 12px; color: #666;">
<%= Spree.t('digital_asset_mailer.files_ready_email.available_until', date: l(digital_link.expires_at.to_date, format: :long)) %>
diff --git a/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.text.erb b/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.text.erb
index b8ef1c1349..9e14d43b20 100644
--- a/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.text.erb
+++ b/spree/emails/app/views/spree/digital_asset_mailer/files_ready_email.text.erb
@@ -4,7 +4,7 @@
<% @digital_links.each do |digital_link| %>
<%= digital_link.filename %>
-<%= digital_link_download_url(digital_link) %>
+<%= digital_link_download_url(digital_link, @download_host) %>
<% if digital_link.expires_at %><%= Spree.t('digital_asset_mailer.files_ready_email.available_until', date: l(digital_link.expires_at.to_date, format: :long)) %>
<% end %>
<% end %>