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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Roll a replaced digital file back when the update is invalid
Damian Legawieca3e3ab7b0e83
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.rbindex 068d7ad4f5..fd9859c424 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@@ -13,10 +13,19 @@ module Spreedef updatereturn render_private_storage_error unless uploaded_blob_private?- @resource.variant = requested_variant if params[:variant_id].present?- attach_uploaded_file(@resource)-- super+ # The asset already exists, so attaching a replacement blob writes+ # to the database immediately, while the update below renders a 422+ # without raising when it fails. Wrap both so a failed update rolls+ # the new attachment back rather than leaving the file swapped but+ # the record unchanged.+ model_class.transaction do+ @resource.variant = requested_variant if params[:variant_id].present?+ attach_uploaded_file(@resource)++ super++ raise ActiveRecord::Rollback if @resource.errors.any?+ endend# POST /api/v3/admin/products/:product_id/digital_assetsdiff --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.rbindex 7af7b2edfb..8dcba3e12f 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@@ -149,6 +149,23 @@ RSpec.describe Spree::Api::V3::Admin::Products::DigitalAssetsController, type: :expect(response).to have_http_status(:ok)expect(json_response['authorized_clicks']).to be_nilend++ # Attaching the replacement writes immediately, so a validation failure in+ # the same request must roll it back — otherwise the file would be swapped+ # while the update reports 422.+ it 'rolls the replaced file back when the update is invalid' do+ original_filename = digital_asset.attachment.filename.to_s++ patch :update, params: {+ product_id: product.prefixed_id,+ id: digital_asset.prefixed_id,+ signed_id: blob.signed_id,+ authorized_clicks: 0+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(digital_asset.reload.attachment.filename.to_s).to eq(original_filename)+ endenddescribe 'DELETE #destroy' do