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.

Add Admin API for digital assets and download grants

Damian Legawiec3512d7779470
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 40d9db1258..4fa10de2dd 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -137,6 +137,8 @@ import type {
DeliveryOriginGroupParams,
DeliveryProfileParams,
DeliveryZoneParams,
+ DigitalAssetCreateParams,
+ DigitalAssetUpdateParams,
DirectUploadCreateParams,
ExchangeCreateParams,
ExchangeFulfillParams,
@@ -278,6 +280,8 @@ import type {
DeliveryProfile,
DeliveryRateProviderOption,
DeliveryZone,
+ DigitalAsset,
+ DigitalLink,
Discount,
Exchange,
Export,
@@ -900,6 +904,46 @@ export class AdminClient {
this.request<void>('DELETE', `/products/${productId}/media/${id}`, options),
},
+ digitalAssets: {
+ list: (
+ productId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<DigitalAsset>> =>
+ this.request<PaginatedResponse<DigitalAsset>>(
+ 'GET',
+ `/products/${productId}/digital_assets`,
+ {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ },
+ ),
+
+ create: (
+ productId: string,
+ params: DigitalAssetCreateParams,
+ options?: RequestOptions,
+ ): Promise<DigitalAsset> =>
+ this.request<DigitalAsset>('POST', `/products/${productId}/digital_assets`, {
+ ...options,
+ body: params,
+ }),
+
+ update: (
+ productId: string,
+ id: string,
+ params: DigitalAssetUpdateParams,
+ options?: RequestOptions,
+ ): Promise<DigitalAsset> =>
+ this.request<DigitalAsset>('PATCH', `/products/${productId}/digital_assets/${id}`, {
+ ...options,
+ body: params,
+ }),
+
+ delete: (productId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/products/${productId}/digital_assets/${id}`, options),
+ },
+
variants: {
list: (
productId: string,
@@ -1004,6 +1048,31 @@ export class AdminClient {
translations: this.parentScopedTranslations('/products'),
}
+ // ============================================
+ // Digital links
+ // ============================================
+
+ /**
+ * Download grants issued to customers when an order is placed. They are never
+ * created by hand — `reset` gives a customer their allowance back.
+ */
+ readonly digitalLinks = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<DigitalLink>> =>
+ this.request<PaginatedResponse<DigitalLink>>('GET', '/digital_links', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ retrieve: (id: string, options?: RequestOptions): Promise<DigitalLink> =>
+ this.request<DigitalLink>('GET', `/digital_links/${id}`, options),
+
+ reset: (id: string, options?: RequestOptions): Promise<DigitalLink> =>
+ this.request<DigitalLink>('PATCH', `/digital_links/${id}/reset`, options),
+ }
+
// ============================================
// Orders
// ============================================
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index e90578c508..68e1de0094 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -654,6 +654,24 @@ export interface ProductMediaInput {
variant_ids?: Array<string>
}
+export interface DigitalAssetCreateParams {
+ /** Signed blob id from a `private: true` direct upload. */
+ signed_id: string
+ /** Defaults to the product's default variant when omitted. */
+ variant_id?: string
+ /** Null (or omitted) means the store's download settings apply. */
+ authorized_clicks?: number | null
+ authorized_days?: number | null
+}
+
+export interface DigitalAssetUpdateParams {
+ /** Replaces the file for everyone who already bought it. */
+ signed_id?: string
+ variant_id?: string
+ authorized_clicks?: number | null
+ authorized_days?: number | null
+}
+
export interface MediaUpdateParams {
alt?: string
position?: number
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
new file mode 100644
index 0000000000..76f21f785d
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/digital_links_controller.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class DigitalLinksController < ResourceController
+ scoped_resource :orders
+
+ before_action :set_resource, only: [:reset]
+
+ # PATCH /api/v3/admin/digital_links/:id/reset
+ #
+ # Gives the customer their download allowance back and restarts the
+ # expiry clock — the remedy when a download failed or a file was
+ # replaced after they had used up their attempts.
+ def reset
+ @resource.reset!
+
+ render json: serialize_resource(@resource)
+ end
+
+ protected
+
+ def model_class
+ Spree::DigitalLink
+ end
+
+ def serializer_class
+ Spree.api.admin_digital_link_serializer
+ end
+
+ def scope
+ current_store.digital_links
+ end
+
+ 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
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
index 91fc8171e3..bd8b24b754 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
@@ -16,6 +16,37 @@ module Spree
scoped_resource :products
skip_before_action :authenticate_user
+
+ # POST /api/v3/admin/direct_uploads
+ #
+ # Overrides the shared concern's create to select the storage service:
+ # digital assets must land on private storage up front, since attaching
+ # a signed id never moves a blob between services.
+ def create
+ blob = ActiveStorage::Blob.create_before_direct_upload!(service_name: storage_service_name, **blob_params)
+
+ render json: {
+ direct_upload: {
+ url: blob.service_url_for_direct_upload,
+ headers: blob.service_headers_for_direct_upload
+ },
+ signed_id: blob.signed_id
+ }, status: :created
+ end
+
+ private
+
+ # Attaching a signed id never moves the blob between services, so a
+ # file destined for a private attachment has to be uploaded to the
+ # private service up front. `private: true` asks for that; everything
+ # else keeps landing on the public service as before.
+ def storage_service_name
+ if params[:private].to_b
+ Spree.private_storage_service_name
+ else
+ Spree.public_storage_service_name
+ end
+ 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
new file mode 100644
index 0000000000..03d6997ecb
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
@@ -0,0 +1,69 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Products
+ class DigitalAssetsController < ResourceController
+ scoped_resource :products
+
+ # PATCH /api/v3/admin/products/:product_id/digital_assets/:id
+ #
+ # Replacing the file keeps every already-issued link working, since
+ # links resolve through the asset rather than the blob.
+ def update
+ attach_uploaded_file(@resource)
+
+ super
+ end
+
+ protected
+
+ def model_class
+ Spree::DigitalAsset
+ end
+
+ def serializer_class
+ Spree.api.admin_digital_asset_serializer
+ end
+
+ def set_parent
+ @parent = current_store.products.find_by_prefix_id!(params[:product_id])
+ authorize!(:show, @parent)
+ end
+
+ def parent_association
+ :digital_assets
+ end
+
+ def scope_includes
+ [:variant, { attachment_attachment: :blob }]
+ end
+
+ # signed_id names an already-uploaded blob rather than a column, so
+ # it is attached separately instead of being assigned.
+ def permitted_params
+ params.permit(:variant_id, :authorized_clicks, :authorized_days)
+ end
+
+ private
+
+ # A product without explicit variants keeps its file on the default
+ # variant, mirroring how the rest of the admin treats such products.
+ def build_resource
+ digital_asset = super
+ digital_asset.variant ||= @parent.default_variant
+ attach_uploaded_file(digital_asset)
+ digital_asset
+ end
+
+ def attach_uploaded_file(digital_asset)
+ return if params[:signed_id].blank?
+
+ digital_asset.attachment.attach(params[:signed_id])
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index dd9bff0571..f9b9b2b298 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -316,6 +316,16 @@ Spree::Core::Engine.add_routes do
resources :media, controller: 'media', only: [:index, :create, :update, :destroy]
end
resources :media, controller: 'media', only: [:index, :create, :update, :destroy]
+ resources :digital_assets, controller: 'products/digital_assets',
+ only: [:index, :create, :show, :update, :destroy]
+ end
+
+ # Digital download grants — read and reset only; they are created by
+ # order completion, never by hand.
+ resources :digital_links, only: [:index, :show] do
+ member do
+ patch :reset
+ end
end
# Media library — every file in the store, placed or not. Files are put
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
new file mode 100644
index 0000000000..88f1541b59
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/digital_links_controller_spec.rb
@@ -0,0 +1,68 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::DigitalLinksController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let(:product) { create(:product, store: store) }
+ let(:order) { create(:order_with_line_items, store: store) }
+ let(:line_item) { order.line_items.first }
+ let(:digital_asset) { create(:digital_asset, variant: line_item.variant) }
+ let!(:digital_link) { create(:digital_link, digital_asset: digital_asset, line_item: line_item) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'lists the links for the store' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |l| l['id'] }).to include(digital_link.prefixed_id)
+ end
+
+ it 'excludes links from another store' do
+ other_order = create(:order_with_line_items, store: create(:store))
+ other_item = other_order.line_items.first
+ other_link = create(:digital_link, digital_asset: create(:digital_asset, variant: other_item.variant),
+ line_item: other_item)
+
+ get :index
+
+ expect(json_response['data'].map { |l| l['id'] }).not_to include(other_link.prefixed_id)
+ end
+ end
+
+ describe 'PATCH #reset' do
+ before { digital_link.update_column(:access_counter, 5) }
+
+ it 'gives the download allowance back' do
+ patch :reset, params: { id: digital_link.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['access_counter']).to eq(0)
+ expect(digital_link.reload.access_counter).to eq(0)
+ end
+
+ it 'restarts the expiry clock' do
+ store.update!(preferred_limit_digital_download_days: true, preferred_digital_asset_authorized_days: 1)
+ digital_link.update_column(:created_at, 5.days.ago)
+ expect(digital_link.reload).to be_expired
+
+ patch :reset, params: { id: digital_link.prefixed_id }
+
+ expect(digital_link.reload).not_to be_expired
+ end
+
+ it 'does not reset a link from another store' do
+ other_order = create(:order_with_line_items, store: create(:store))
+ other_item = other_order.line_items.first
+ other_link = create(:digital_link, digital_asset: create(:digital_asset, variant: other_item.variant),
+ line_item: other_item)
+
+ patch :reset, params: { id: other_link.prefixed_id }
+
+ expect(response).to have_http_status(:not_found)
+ 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
new file mode 100644
index 0000000000..4997004d0c
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/digital_assets_controller_spec.rb
@@ -0,0 +1,134 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:product) { create(:product, store: store) }
+ let(:variant) { product.default_variant }
+
+ let(:blob) do
+ ActiveStorage::Blob.create_and_upload!(
+ io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
+ filename: 'manual.pdf',
+ content_type: 'application/pdf',
+ service_name: Spree.private_storage_service_name
+ )
+ end
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ let!(:digital_asset) { create(:digital_asset, variant: variant) }
+
+ it 'lists the assets for the product' do
+ get :index, params: { product_id: product.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |a| a['id'] }).to include(digital_asset.prefixed_id)
+ end
+
+ it 'does not list assets belonging to another product' do
+ other = create(:digital_asset)
+
+ get :index, params: { product_id: product.prefixed_id }
+
+ expect(json_response['data'].map { |a| a['id'] }).not_to include(other.prefixed_id)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'attaches an uploaded file to the default variant' do
+ post :create, params: {
+ product_id: product.prefixed_id,
+ signed_id: blob.signed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['filename']).to eq('manual.pdf')
+ expect(json_response['variant_id']).to eq(variant.prefixed_id)
+ end
+
+ it 'accepts per-asset download limits' do
+ post :create, params: {
+ product_id: product.prefixed_id,
+ signed_id: blob.signed_id,
+ authorized_clicks: 99,
+ authorized_days: 365
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['authorized_clicks']).to eq(99)
+ expect(json_response['effective_authorized_clicks']).to eq(99)
+ end
+
+ it 'rejects a file with no attachment' do
+ post :create, params: { product_id: product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+
+ it 'rejects a non-positive limit' do
+ post :create, params: {
+ product_id: product.prefixed_id,
+ signed_id: blob.signed_id,
+ authorized_clicks: 0
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+ end
+
+ describe 'PATCH #update' do
+ let!(:digital_asset) { create(:digital_asset, variant: variant) }
+
+ it 'replaces the file, keeping existing links working' do
+ digital_link = create(:digital_link, digital_asset: digital_asset)
+
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: digital_asset.prefixed_id,
+ signed_id: blob.signed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['filename']).to eq('manual.pdf')
+ expect(digital_link.reload).to be_authorizable
+ end
+
+ it 'clears a limit override back to the store default' do
+ digital_asset.update!(authorized_clicks: 50)
+
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: digital_asset.prefixed_id,
+ authorized_clicks: nil
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['authorized_clicks']).to be_nil
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ let!(:digital_asset) { create(:digital_asset, variant: variant) }
+
+ it 'removes the asset' do
+ delete :destroy, params: { product_id: product.prefixed_id, id: digital_asset.prefixed_id }
+
+ expect(response).to have_http_status(:no_content)
+ expect(Spree::DigitalAsset.where(id: digital_asset.id)).to be_empty
+ end
+ end
+
+ context 'with a product from another store' do
+ let(:other_product) { create(:product, store: create(:store)) }
+
+ it 'returns not found' do
+ get :index, params: { product_id: other_product.prefixed_id }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index c9fed1109f..3beb38de2d 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -294,7 +294,7 @@ module Spree
register_resource(:orders, group: :orders, audiences: %i[seller], subjects: -> {
[Spree::Order, Spree::OrderGroup, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,
Spree::Return, Spree::Exchange, Spree::Claim, Spree::TaxIdentifier,
- Spree::CustomField]
+ Spree::CustomField, Spree::DigitalLink]
})
register_resource(:payments, group: :orders, subjects: -> { [Spree::Payment, Spree::PaymentSplit] })
register_resource(:fulfillments, group: :orders, audiences: %i[seller], subjects: -> { [Spree::Fulfillment] })
@@ -318,7 +318,7 @@ module Spree
[Spree::Product, Spree::Variant, Spree::OptionType,
Spree::OptionValue, Spree::Price, Spree::PriceList, Spree::PriceRule,
Spree::Catalog, Spree::CatalogProduct,
- Spree::CatalogAssignment, Spree::CustomField,
+ Spree::CatalogAssignment, Spree::CustomField, Spree::DigitalAsset,
Spree::Import, Spree::ImportRow]
})
# Its own resource so a seller can be granted the read without the