From 6580c1727386ab33dc2cf0a1d13306050bd2fadf Mon Sep 17 00:00:00 2001 From: Methapon Metanipat Date: Mon, 25 Nov 2024 15:03:49 +0700 Subject: [PATCH] refactor: prevent recreation of work --- src/controllers/04-service-controller.ts | 42 +++++++++++++++++------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/controllers/04-service-controller.ts b/src/controllers/04-service-controller.ts index 1cf16fe..a31d744 100644 --- a/src/controllers/04-service-controller.ts +++ b/src/controllers/04-service-controller.ts @@ -91,6 +91,7 @@ type ServiceUpdate = { status?: "ACTIVE" | "INACTIVE"; workflowId?: string; work?: { + id?: string; name: string; product: { id: string; @@ -401,17 +402,36 @@ export class ServiceController extends Controller { ...payload, statusOrder: +(payload.status === "INACTIVE"), work: { - deleteMany: {}, - create: (work || []).map((w, wIdx) => ({ - name: w.name, - order: wIdx + 1, - attributes: w.attributes, - productOnWork: { - create: w.product.map((p, pIdx) => ({ - productId: p.id, - installmentNo: p.installmentNo, - order: pIdx + 1, - })), + deleteMany: { + id: work?.some((v) => !!v.id) + ? { notIn: work.flatMap((v) => (!!v.id ? v.id : [])) } + : undefined, + }, + upsert: (work || []).map((w, wIdx) => ({ + where: { id: w.id }, + create: { + name: w.name, + order: wIdx + 1, + attributes: w.attributes, + productOnWork: { + create: w.product.map((p, pIdx) => ({ + productId: p.id, + installmentNo: p.installmentNo, + order: pIdx + 1, + })), + }, + }, + update: { + name: w.name, + order: wIdx + 1, + attributes: w.attributes, + productOnWork: { + create: w.product.map((p, pIdx) => ({ + productId: p.id, + installmentNo: p.installmentNo, + order: pIdx + 1, + })), + }, }, })), },