diff --git a/.changeset/shy-gorillas-allow.md b/.changeset/shy-gorillas-allow.md new file mode 100644 index 0000000000000..1c94c4a148d0d --- /dev/null +++ b/.changeset/shy-gorillas-allow.md @@ -0,0 +1,6 @@ +--- +"@medusajs/dashboard": patch +"@medusajs/product": patch +--- + +fix(product,dashboard): Avoid duplicating images diff --git a/packages/admin/dashboard/src/routes/products/product-media/components/edit-product-media-form/edit-product-media-form.tsx b/packages/admin/dashboard/src/routes/products/product-media/components/edit-product-media-form/edit-product-media-form.tsx index 11ab0f748746a..e8b1c4df6fb08 100644 --- a/packages/admin/dashboard/src/routes/products/product-media/components/edit-product-media-form/edit-product-media-form.tsx +++ b/packages/admin/dashboard/src/routes/products/product-media/components/edit-product-media-form/edit-product-media-form.tsx @@ -132,8 +132,8 @@ export const EditProductMediaForm = ({ product }: ProductMediaViewProps) => { await mutateAsync( { - images: withUpdatedUrls.map((file) => ({ url: file.url })), - thumbnail: thumbnail, + images: withUpdatedUrls.map((file) => ({ url: file.url, id: file.id })), + thumbnail: thumbnail || null, }, { onSuccess: () => { diff --git a/packages/modules/product/src/migrations/Migration20241122120331.ts b/packages/modules/product/src/migrations/Migration20241122120331.ts index d8585ef7295e8..ff324f3e1ec7d 100644 --- a/packages/modules/product/src/migrations/Migration20241122120331.ts +++ b/packages/modules/product/src/migrations/Migration20241122120331.ts @@ -19,6 +19,12 @@ export class Migration20241122120331 extends Migration { where pi.image_id = i.id; `); + // Delete orphaned images + this.addSql(` + delete from "image" + where product_id is null; + `); + this.addSql('alter table if exists "image" alter column "product_id" set not null;'); this.addSql('alter table if exists "image" add constraint "image_product_id_foreign" foreign key ("product_id") references "product" ("id") on update cascade on delete cascade;'); this.addSql('drop table if exists "product_images" cascade;'); diff --git a/packages/modules/product/src/services/product-module-service.ts b/packages/modules/product/src/services/product-module-service.ts index 777fb9fc091ef..623eb8b8700f5 100644 --- a/packages/modules/product/src/services/product-module-service.ts +++ b/packages/modules/product/src/services/product-module-service.ts @@ -1690,6 +1690,16 @@ export default class ProductModuleService sharedContext ) upsertedProduct.images = productImages + + await this.productImageService_.delete( + { + product_id: upsertedProduct.id, + id: { + $nin: productImages.map(({ id }) => id), + }, + }, + sharedContext + ) } else { await this.productImageService_.delete( { product_id: upsertedProduct.id },