From 964e9f4eb745083662e6ee9afbc16e0400ea3d94 Mon Sep 17 00:00:00 2001 From: percyfikri Date: Thu, 5 Sep 2024 14:06:16 +0700 Subject: [PATCH 1/3] Update : API for management-aspect --- .../src/routes/managementAspect/route.ts | 59 +++++++++---------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/apps/backend/src/routes/managementAspect/route.ts b/apps/backend/src/routes/managementAspect/route.ts index da8a140..772aed5 100644 --- a/apps/backend/src/routes/managementAspect/route.ts +++ b/apps/backend/src/routes/managementAspect/route.ts @@ -40,7 +40,7 @@ export const aspectUpdateSchema = aspectFormSchema.extend({ // Schema for creating and updating subAspects export const subAspectFormSchema = z.object({ name: z.string().min(1).max(50), - aspectId: z.string().uuid(), + aspectId: z.string() }); export const subAspectUpdateSchema = subAspectFormSchema.extend({}); @@ -89,9 +89,12 @@ const managementAspectRoute = new Hono() createdAt: aspects.createdAt, updatedAt: aspects.updatedAt, ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), + subAspectId : subAspects.id, + subAspectName : subAspects.name, fullCount: totalCountQuery, }) .from(aspects) + .leftJoin(subAspects, eq(subAspects.aspectId, aspects.id)) .where( and( includeTrashed ? undefined : isNull(aspects.deletedAt), @@ -261,22 +264,6 @@ const managementAspectRoute = new Hono() }) .where(eq(aspects.id, aspectId)); - //Update for Sub-Aspects - // if (aspectData.subAspects) { - // const subAspectsArray = JSON.parse(aspectData.subAspects) as string[]; - - // await db.delete(subAspects).where(eq(subAspects.aspectId, aspectId)); - - // if (subAspectsArray.length) { - // await db.insert(subAspects).values( - // subAspectsArray.map((subAspect) => ({ - // aspectId: aspectId, - // name: subAspect, - // })) - // ); - // } - // } - return c.json({ message: "Aspect updated successfully", }); @@ -394,7 +381,7 @@ const managementAspectRoute = new Hono() eq(subAspects.aspectId, subAspectData.aspectId))); if (existingSubAspect.length > 0) { - throw forbidden({ message: "Nama Sub Aspek sudah tersedia!" }); + throw forbidden({ message: "Sub aspect name already exists!" }); } const [aspect] = await db @@ -423,28 +410,39 @@ const managementAspectRoute = new Hono() // Update sub aspect .patch( - "/subAspect/:id", checkPermission("managementAspect.update"), + "/subAspect/:id", + checkPermission("managementAspect.update"), requestValidator("json", subAspectUpdateSchema), async (c) => { const subAspectId = c.req.param("id"); const subAspectData = c.req.valid("json"); - - // Validation to check if the new sub aspect name already exists + + // Validate if the new sub aspect name already exists for the given aspect const existingSubAspect = await db .select() .from(subAspects) .where( - eq(subAspects.aspectId, subAspectData.aspectId)); - + and( + eq(subAspects.name, subAspectData.name), + eq(subAspects.aspectId, subAspectData.aspectId), + ) + ); + if (existingSubAspect.length > 0) { - throw forbidden({ message: "Name Sub Aspect already exists" }); + throw forbidden({ message: "Sub Aspect name already exists" }); } - - if (!existingSubAspect[0]) + + const [currentSubAspect] = await db + .select() + .from(subAspects) + .where(eq(subAspects.id, subAspectId)); + + if (!currentSubAspect) throw notFound({ message: "The sub aspect is not found", }); - + + // Update the sub aspect await db .update(subAspects) .set({ @@ -452,11 +450,12 @@ const managementAspectRoute = new Hono() updatedAt: new Date(), }) .where(eq(subAspects.id, subAspectId)); - + return c.json({ - message: "Sub aspect updated successfully", + message: "Sub Aspect updated successfully", }); - }) + } + ) // Delete sub aspect .delete( From 831759278cf128e0f6ba52b39112af32b1a1971d Mon Sep 17 00:00:00 2001 From: percyfikri Date: Fri, 13 Sep 2024 10:52:48 +0700 Subject: [PATCH 2/3] Update : All method API for management-aspect --- .../src/routes/managementAspect/route.ts | 458 ++++++++---------- 1 file changed, 202 insertions(+), 256 deletions(-) diff --git a/apps/backend/src/routes/managementAspect/route.ts b/apps/backend/src/routes/managementAspect/route.ts index 772aed5..cb65ee9 100644 --- a/apps/backend/src/routes/managementAspect/route.ts +++ b/apps/backend/src/routes/managementAspect/route.ts @@ -1,6 +1,6 @@ -import { and, eq, ilike, isNull, or, sql } from "drizzle-orm"; +import { and, eq, ilike, isNull, or, sql, inArray } from "drizzle-orm"; import { Hono } from "hono"; - +import { questions } from "../../drizzle/schema/questions"; import { z } from "zod"; import db from "../../drizzle"; import { aspects } from "../../drizzle/schema/aspects"; @@ -33,14 +33,16 @@ export const aspectFormSchema = z.object({ .optional(), }); -export const aspectUpdateSchema = aspectFormSchema.extend({ - subAspects: z.string().optional().or(z.literal("")), -}); - // Schema for creating and updating subAspects export const subAspectFormSchema = z.object({ + id: z.string(), name: z.string().min(1).max(50), - aspectId: z.string() + aspectId: z.string().optional(), +}); + +export const aspectUpdateSchema = z.object({ + name: z.string(), + subAspects: z.array(subAspectFormSchema), }); export const subAspectUpdateSchema = subAspectFormSchema.extend({}); @@ -71,17 +73,17 @@ const managementAspectRoute = new Hono() .optional() .transform((v) => v?.toLowerCase() === "true"), page: z.coerce.number().int().min(0).default(0), - limit: z.coerce.number().int().min(1).max(1000).default(10), + limit: z.coerce.number().int().min(1).max(1000).default(1000), q: z.string().default(""), }) ), async (c) => { const { includeTrashed, page, limit, q } = c.req.valid("query"); - + const totalCountQuery = includeTrashed ? sql`(SELECT count(*) FROM ${aspects})` : sql`(SELECT count(*) FROM ${aspects} WHERE ${aspects.deletedAt} IS NULL)`; - + const result = await db .select({ id: aspects.id, @@ -89,8 +91,8 @@ const managementAspectRoute = new Hono() createdAt: aspects.createdAt, updatedAt: aspects.updatedAt, ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), - subAspectId : subAspects.id, - subAspectName : subAspects.name, + subAspectId: subAspects.id, + subAspectName: subAspects.name, fullCount: totalCountQuery, }) .from(aspects) @@ -103,9 +105,38 @@ const managementAspectRoute = new Hono() ) .offset(page * limit) .limit(limit); - + + // Grouping sub-aspects by aspect ID + const groupedResult = result.reduce((acc, curr) => { + const aspectId = curr.id; + + if (!acc[aspectId]) { + acc[aspectId] = { + id: curr.id, + name: curr.name, + createdAt: curr.createdAt ? new Date(curr.createdAt).toISOString() : null, + updatedAt: curr.updatedAt ? new Date(curr.updatedAt).toISOString() : null, + subAspects: curr.subAspectName ? [{ id: curr.subAspectId!, name: curr.subAspectName }] : [], + }; + } else { + if (curr.subAspectName) { + acc[aspectId].subAspects.push({ id: curr.subAspectId!, name: curr.subAspectName }); + } + } + + return acc; + }, {} as Record); + + const groupedArray = Object.values(groupedResult); + return c.json({ - data: result.map((d) => ({ ...d, fullCount: undefined })), + data: groupedArray, _metadata: { currentPage: page, totalPages: Math.ceil((Number(result[0]?.fullCount) ?? 0) / limit), @@ -114,7 +145,7 @@ const managementAspectRoute = new Hono() }, }); } - ) + ) // Get aspect by id .get( @@ -128,14 +159,14 @@ const managementAspectRoute = new Hono() ), async (c) => { const aspectId = c.req.param("id"); - + if (!aspectId) throw notFound({ message: "Missing id", }); - + const includeTrashed = c.req.query("includeTrashed")?.toLowerCase() === "true"; - + const queryResult = await db .select({ id: aspects.id, @@ -146,29 +177,35 @@ const managementAspectRoute = new Hono() subAspect: { name: subAspects.name, id: subAspects.id, + questionCount: sql`COUNT(${questions.id})`.as("questionCount"), }, }) .from(aspects) .leftJoin(subAspects, eq(aspects.id, subAspects.aspectId)) - .where(and(eq(aspects.id, aspectId), !includeTrashed ? isNull(aspects.deletedAt) : undefined)); - + .leftJoin(questions, eq(subAspects.id, questions.subAspectId)) + .where(and(eq(aspects.id, aspectId), !includeTrashed ? isNull(aspects.deletedAt) : undefined)) + .groupBy(aspects.id, aspects.name, aspects.createdAt, aspects.updatedAt, subAspects.id, subAspects.name); + if (!queryResult.length) throw forbidden({ message: "The aspect does not exist", }); - + const subAspectsList = queryResult.reduce((prev, curr) => { if (!curr.subAspect) return prev; - prev.set(curr.subAspect.id, curr.subAspect.name); + prev.set(curr.subAspect.id, { + name: curr.subAspect.name, + questionCount: Number(curr.subAspect.questionCount), + }); return prev; - }, new Map()); // Map - + }, new Map()); + const aspectData = { ...queryResult[0], subAspect: undefined, - subAspects: Array.from(subAspectsList, ([id, name]) => ({ id, name })), + subAspects: Array.from(subAspectsList, ([id, { name, questionCount }]) => ({ id, name, questionCount })), }; - + return c.json(aspectData); } ) @@ -179,96 +216,160 @@ const managementAspectRoute = new Hono() requestValidator("json", aspectFormSchema), async (c) => { const aspectData = c.req.valid("json"); - - // Validation to check if the aspect name already exists - const existingAspect = await db - .select() - .from(aspects) - .where(eq(aspects.name, aspectData.name)); - - if (existingAspect.length > 0) { - throw forbidden({ - message: "Aspect name already exists", - }); - } - - const aspect = await db - .insert(aspects) - .values({ - name: aspectData.name, - }) - .returning(); - - // if sub-aspects are available, parse them into a string array - if (aspectData.subAspects) { - const subAspectsArray = JSON.parse(aspectData.subAspects) as string[]; - // if there are sub-aspects, insert them into the database - if (subAspectsArray.length) { - await db.insert(subAspects).values( - subAspectsArray.map((subAspect) => ({ - aspectId: aspect[0].id, - name: subAspect, - })) - ); + + // Cek jika nama aspek sudah ada + const existingAspect = await db + .select() + .from(aspects) + .where(eq(aspects.name, aspectData.name)); + + let aspectId; + if (existingAspect.length > 0) { + // Jika aspek sudah ada, ambil ID-nya + aspectId = existingAspect[0].id; + } else { + // Jika tidak ada, buat aspek baru + const aspect = await db + .insert(aspects) + .values({ + name: aspectData.name, + }) + .returning(); + aspectId = aspect[0].id; } - } - + + // Jika ada data sub-aspek, parse dan masukkan ke database + if (aspectData.subAspects) { + const subAspectsArray = JSON.parse(aspectData.subAspects) as string[]; + + // Masukkan sub-aspek baru ke database tanpa cek duplikasi sub-aspek + if (subAspectsArray.length) { + await db.insert(subAspects).values( + subAspectsArray.map((subAspect) => ({ + aspectId, + name: subAspect, + })) + ); + } + } + return c.json( { - message: "Aspect created successfully", + message: "Aspect and sub-aspects created successfully", }, 201 ); } - ) + ) // Update aspect .patch( - "/:id", - checkPermission("managementAspect.update"), - requestValidator("json", aspectUpdateSchema), + "/:id", + checkPermission("managementAspect.update"), + requestValidator("json", aspectUpdateSchema), async (c) => { const aspectId = c.req.param("id"); const aspectData = c.req.valid("json"); - - // Validation to check if the new aspect name already exists - const existingAspect = await db - .select() - .from(aspects) - .where( - and( - eq(aspects.name, aspectData.name), - isNull(aspects.deletedAt), - sql`${aspects.id} <> ${aspectId}` - ) - ); - - if (existingAspect.length > 0) { - throw forbidden({ - message: "Aspect name already exists", - }); - } - - const aspect = await db - .select() - .from(aspects) - .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); - - if (!aspect[0]) throw notFound(); - - await db - .update(aspects) - .set({ - ...aspectData, - updatedAt: new Date(), - }) - .where(eq(aspects.id, aspectId)); - + + // Cek jika nama aspek baru sudah ada + const existingAspect = await db + .select() + .from(aspects) + .where( + and( + eq(aspects.name, aspectData.name), + isNull(aspects.deletedAt), + sql`${aspects.id} <> ${aspectId}` + ) + ); + + if (existingAspect.length > 0) { + throw forbidden({ + message: "Aspect name already exists", + }); + } + + // Cek jika aspek yang dimaksud ada + const aspect = await db + .select() + .from(aspects) + .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); + + if (!aspect[0]) throw notFound(); + + // Update nama aspek + await db + .update(aspects) + .set({ + name: aspectData.name, + updatedAt: new Date(), + }) + .where(eq(aspects.id, aspectId)); + + // Ambil data sub-aspek baru dari request + const newSubAspects = aspectData.subAspects || []; + + // Ambil sub-aspek yang ada saat ini + const currentSubAspects = await db + .select({ id: subAspects.id, name: subAspects.name }) + .from(subAspects) + .where(eq(subAspects.aspectId, aspectId)); + + const currentSubAspectMap = new Map(currentSubAspects.map(sub => [sub.id, sub.name])); + + // Sub-aspek yang harus dihapus + const subAspectsToDelete = currentSubAspects + .filter(sub => !newSubAspects.some(newSub => newSub.id === sub.id)) + .map(sub => sub.id); + + // Hapus sub-aspek yang tidak ada di data baru + if (subAspectsToDelete.length) { + await db + .delete(subAspects) + .where( + and( + eq(subAspects.aspectId, aspectId), + inArray(subAspects.id, subAspectsToDelete) + ) + ); + } + + // Update atau tambahkan sub-aspek baru + for (const subAspect of newSubAspects) { + const existingSubAspect = currentSubAspectMap.has(subAspect.id); + + if (existingSubAspect) { + // Update jika sub-aspek sudah ada + await db + .update(subAspects) + .set({ + name: subAspect.name, + updatedAt: new Date(), + }) + .where( + and( + eq(subAspects.id, subAspect.id), + eq(subAspects.aspectId, aspectId) + ) + ); + } else { + // Tambah jika sub-aspek baru + await db + .insert(subAspects) + .values({ + id: subAspect.id, // Pastikan `id` diberikan + aspectId, + name: subAspect.name, + createdAt: new Date(), + }); + } + } + return c.json({ - message: "Aspect updated successfully", + message: "Aspect and sub-aspects updated successfully", }); } - ) + ) // Delete aspect .delete( @@ -333,159 +434,4 @@ const managementAspectRoute = new Hono() } ) - // Get sub aspects by aspect ID - .get( - "/subAspects/:aspectId", - checkPermission("managementAspect.readAll"), - async (c) => { - const aspectId = c.req.param("aspectId"); - - const aspect = await db - .select() - .from(aspects) - .where(and( - eq(aspects.id, aspectId), - isNull(aspects.deletedAt))); - - if (!aspect[0]) - throw notFound({ - message: "The aspect is not found", - }); - - const subAspectsData = await db - .select() - .from(subAspects) - .where(eq(subAspects.aspectId, aspectId)); - - return c.json({ - subAspects: subAspectsData, - }); - } - ) - - // Create sub aspect - .post( - "/subAspect", - checkPermission("managementAspect.create"), - requestValidator("json", subAspectFormSchema), - async (c) => { - const subAspectData = c.req.valid("json"); - - // Validation to check if the sub aspect name already exists - const existingSubAspect = await db - .select() - .from(subAspects) - .where( - and( - eq(subAspects.name, subAspectData.name), - eq(subAspects.aspectId, subAspectData.aspectId))); - - if (existingSubAspect.length > 0) { - throw forbidden({ message: "Sub aspect name already exists!" }); - } - - const [aspect] = await db - .select() - .from(aspects) - .where( - and( - eq(aspects.id, subAspectData.aspectId), - isNull(aspects.deletedAt))); - - if (!aspect) - throw forbidden({ - message: "The aspect is not found", - }); - - await db.insert(subAspects).values(subAspectData); - - return c.json( - { - message: "Sub aspect created successfully", - }, - 201 - ); - } - ) - - // Update sub aspect - .patch( - "/subAspect/:id", - checkPermission("managementAspect.update"), - requestValidator("json", subAspectUpdateSchema), - async (c) => { - const subAspectId = c.req.param("id"); - const subAspectData = c.req.valid("json"); - - // Validate if the new sub aspect name already exists for the given aspect - const existingSubAspect = await db - .select() - .from(subAspects) - .where( - and( - eq(subAspects.name, subAspectData.name), - eq(subAspects.aspectId, subAspectData.aspectId), - ) - ); - - if (existingSubAspect.length > 0) { - throw forbidden({ message: "Sub Aspect name already exists" }); - } - - const [currentSubAspect] = await db - .select() - .from(subAspects) - .where(eq(subAspects.id, subAspectId)); - - if (!currentSubAspect) - throw notFound({ - message: "The sub aspect is not found", - }); - - // Update the sub aspect - await db - .update(subAspects) - .set({ - ...subAspectData, - updatedAt: new Date(), - }) - .where(eq(subAspects.id, subAspectId)); - - return c.json({ - message: "Sub Aspect updated successfully", - }); - } - ) - - // Delete sub aspect - .delete( - "/subAspect/:id", - checkPermission("managementAspect.delete"), - async (c) => { - const subAspectId = c.req.param("id"); - - const subAspect = await db - .select() - .from(subAspects) - .where(eq(subAspects.id, subAspectId)); - - if (!subAspect[0]) - throw notFound({ - message: "The sub aspect is not found", - }); - - await db - .update(subAspects) - .set({ - deletedAt: new Date(), - }) - .where(eq(subAspects.id, subAspectId)); - // await db.delete(subAspects).where(eq(subAspects.id, subAspectId)); - - return c.json({ - message: "Sub aspect deleted successfully", - }); - } - ); - -export default managementAspectRoute; +export default managementAspectRoute; \ No newline at end of file From d4a4a9e0f8aaf0d3c3658119f31f793e5495f248 Mon Sep 17 00:00:00 2001 From: percyfikri Date: Thu, 3 Oct 2024 10:43:31 +0700 Subject: [PATCH 3/3] Update : All method API for management-aspect --- .../src/routes/managementAspect/route.ts | 731 ++++++++++-------- 1 file changed, 394 insertions(+), 337 deletions(-) diff --git a/apps/backend/src/routes/managementAspect/route.ts b/apps/backend/src/routes/managementAspect/route.ts index cb65ee9..ebf11fd 100644 --- a/apps/backend/src/routes/managementAspect/route.ts +++ b/apps/backend/src/routes/managementAspect/route.ts @@ -57,381 +57,438 @@ const managementAspectRoute = new Hono() * - withMetadata: boolean */ - // Get all aspects - .get( - "/", - checkPermission("managementAspect.readAll"), - requestValidator( - "query", - z.object({ - includeTrashed: z - .string() - .optional() - .transform((v) => v?.toLowerCase() === "true"), - withMetadata: z - .string() - .optional() - .transform((v) => v?.toLowerCase() === "true"), - page: z.coerce.number().int().min(0).default(0), - limit: z.coerce.number().int().min(1).max(1000).default(1000), - q: z.string().default(""), + // Get all aspects + .get( + "/", + checkPermission("managementAspect.readAll"), + requestValidator( + "query", + z.object({ + includeTrashed: z + .string() + .optional() + .transform((v) => v?.toLowerCase() === "true"), + withMetadata: z + .string() + .optional() + .transform((v) => v?.toLowerCase() === "true"), + page: z.coerce.number().int().min(0).default(0), + limit: z.coerce.number().int().min(1).max(1000).default(10), + q: z.string().default(""), + }) + ), + async (c) => { + const { includeTrashed, page, limit, q } = c.req.valid("query"); + + const totalCountQuery = includeTrashed + ? sql`(SELECT count(DISTINCT ${aspects.id}) FROM ${aspects})` + : sql`(SELECT count(DISTINCT ${aspects.id}) FROM ${aspects} WHERE ${aspects.deletedAt} IS NULL)`; + + const aspectIdsQuery = await db + .select({ + id: aspects.id, }) - ), - async (c) => { - const { includeTrashed, page, limit, q } = c.req.valid("query"); - - const totalCountQuery = includeTrashed - ? sql`(SELECT count(*) FROM ${aspects})` - : sql`(SELECT count(*) FROM ${aspects} WHERE ${aspects.deletedAt} IS NULL)`; - - const result = await db - .select({ - id: aspects.id, - name: aspects.name, - createdAt: aspects.createdAt, - updatedAt: aspects.updatedAt, - ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), - subAspectId: subAspects.id, - subAspectName: subAspects.name, - fullCount: totalCountQuery, - }) - .from(aspects) - .leftJoin(subAspects, eq(subAspects.aspectId, aspects.id)) - .where( - and( - includeTrashed ? undefined : isNull(aspects.deletedAt), - q ? or(ilike(aspects.name, q), eq(aspects.id, q)) : undefined - ) + .from(aspects) + .where( + and( + includeTrashed ? undefined : isNull(aspects.deletedAt), + q ? or(ilike(aspects.name, q), eq(aspects.id, q)) : undefined ) - .offset(page * limit) - .limit(limit); - - // Grouping sub-aspects by aspect ID - const groupedResult = result.reduce((acc, curr) => { - const aspectId = curr.id; - - if (!acc[aspectId]) { - acc[aspectId] = { - id: curr.id, - name: curr.name, - createdAt: curr.createdAt ? new Date(curr.createdAt).toISOString() : null, - updatedAt: curr.updatedAt ? new Date(curr.updatedAt).toISOString() : null, - subAspects: curr.subAspectName ? [{ id: curr.subAspectId!, name: curr.subAspectName }] : [], - }; - } else { - if (curr.subAspectName) { - acc[aspectId].subAspects.push({ id: curr.subAspectId!, name: curr.subAspectName }); - } - } - - return acc; - }, {} as Record); - - const groupedArray = Object.values(groupedResult); - + ) + .offset(page * limit) + .limit(limit); + + const aspectIds = aspectIdsQuery.map(a => a.id); + + if (aspectIds.length === 0) { return c.json({ - data: groupedArray, + data: [], _metadata: { currentPage: page, - totalPages: Math.ceil((Number(result[0]?.fullCount) ?? 0) / limit), - totalItems: Number(result[0]?.fullCount) ?? 0, + totalPages: 0, + totalItems: 0, perPage: limit, }, }); } - ) - - // Get aspect by id - .get( - "/:id", - checkPermission("managementAspect.readAll"), - requestValidator( - "query", - z.object({ - includeTrashed: z.string().default("false"), + + // Main query to get aspects, sub-aspects, and number of questions + const result = await db + .select({ + id: aspects.id, + name: aspects.name, + createdAt: aspects.createdAt, + updatedAt: aspects.updatedAt, + ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), + subAspectId: subAspects.id, + subAspectName: subAspects.name, + // Increase the number of questions related to sub aspects + questionCount: sql`( + SELECT count(*) + FROM ${questions} + WHERE ${questions.subAspectId} = ${subAspects.id} + )`.as('questionCount'), + fullCount: totalCountQuery, }) - ), - async (c) => { - const aspectId = c.req.param("id"); - - if (!aspectId) - throw notFound({ - message: "Missing id", - }); - - const includeTrashed = c.req.query("includeTrashed")?.toLowerCase() === "true"; - - const queryResult = await db - .select({ - id: aspects.id, - name: aspects.name, - createdAt: aspects.createdAt, - updatedAt: aspects.updatedAt, - ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), - subAspect: { - name: subAspects.name, - id: subAspects.id, - questionCount: sql`COUNT(${questions.id})`.as("questionCount"), - }, - }) - .from(aspects) - .leftJoin(subAspects, eq(aspects.id, subAspects.aspectId)) - .leftJoin(questions, eq(subAspects.id, questions.subAspectId)) - .where(and(eq(aspects.id, aspectId), !includeTrashed ? isNull(aspects.deletedAt) : undefined)) - .groupBy(aspects.id, aspects.name, aspects.createdAt, aspects.updatedAt, subAspects.id, subAspects.name); - - if (!queryResult.length) - throw forbidden({ - message: "The aspect does not exist", - }); - - const subAspectsList = queryResult.reduce((prev, curr) => { - if (!curr.subAspect) return prev; - prev.set(curr.subAspect.id, { - name: curr.subAspect.name, - questionCount: Number(curr.subAspect.questionCount), - }); - return prev; - }, new Map()); - - const aspectData = { - ...queryResult[0], - subAspect: undefined, - subAspects: Array.from(subAspectsList, ([id, { name, questionCount }]) => ({ id, name, questionCount })), - }; - - return c.json(aspectData); - } - ) - - // Create aspect - .post("/", - checkPermission("managementAspect.create"), - requestValidator("json", aspectFormSchema), - async (c) => { - const aspectData = c.req.valid("json"); - - // Cek jika nama aspek sudah ada - const existingAspect = await db - .select() - .from(aspects) - .where(eq(aspects.name, aspectData.name)); - - let aspectId; - if (existingAspect.length > 0) { - // Jika aspek sudah ada, ambil ID-nya - aspectId = existingAspect[0].id; + .from(aspects) + .leftJoin(subAspects, eq(subAspects.aspectId, aspects.id)) + .where(inArray(aspects.id, aspectIds)); + + // Grouping sub aspects by aspect ID + const groupedResult = result.reduce((acc, curr) => { + const aspectId = curr.id; + + if (!acc[aspectId]) { + acc[aspectId] = { + id: curr.id, + name: curr.name, + createdAt: curr.createdAt ? new Date(curr.createdAt).toISOString() : null, + updatedAt: curr.updatedAt ? new Date(curr.updatedAt).toISOString() : null, + subAspects: curr.subAspectName + ? [{ id: curr.subAspectId!, name: curr.subAspectName, questionCount: curr.questionCount }] + : [], + }; } else { - // Jika tidak ada, buat aspek baru - const aspect = await db - .insert(aspects) - .values({ - name: aspectData.name, - }) - .returning(); - aspectId = aspect[0].id; - } - - // Jika ada data sub-aspek, parse dan masukkan ke database - if (aspectData.subAspects) { - const subAspectsArray = JSON.parse(aspectData.subAspects) as string[]; - - // Masukkan sub-aspek baru ke database tanpa cek duplikasi sub-aspek - if (subAspectsArray.length) { - await db.insert(subAspects).values( - subAspectsArray.map((subAspect) => ({ - aspectId, - name: subAspect, - })) - ); + if (curr.subAspectName) { + const exists = acc[aspectId].subAspects.some(sub => sub.id === curr.subAspectId); + if (!exists) { + acc[aspectId].subAspects.push({ + id: curr.subAspectId!, + name: curr.subAspectName, + questionCount: curr.questionCount, + }); + } } } - - return c.json( - { - message: "Aspect and sub-aspects created successfully", + + return acc; + }, {} as Record); + + const groupedArray = Object.values(groupedResult); + + return c.json({ + data: groupedArray, + _metadata: { + currentPage: page, + totalPages: Math.ceil((Number(result[0]?.fullCount) ?? 0) / limit), + totalItems: Number(result[0]?.fullCount) ?? 0, + perPage: limit, + }, + }); + } + ) + + // Get aspect by id + .get( + "/:id", + checkPermission("managementAspect.readAll"), + requestValidator( + "query", + z.object({ + includeTrashed: z.string().default("false"), + }) + ), + async (c) => { + const aspectId = c.req.param("id"); + + if (!aspectId) + throw notFound({ + message: "Missing id", + }); + + const includeTrashed = c.req.query("includeTrashed")?.toLowerCase() === "true"; + + const queryResult = await db + .select({ + id: aspects.id, + name: aspects.name, + createdAt: aspects.createdAt, + updatedAt: aspects.updatedAt, + ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), + subAspect: { + name: subAspects.name, + id: subAspects.id, + questionCount: sql`COUNT(${questions.id})`.as("questionCount"), }, - 201 + }) + .from(aspects) + .leftJoin(subAspects, eq(aspects.id, subAspects.aspectId)) + .leftJoin(questions, eq(subAspects.id, questions.subAspectId)) + .where(and(eq(aspects.id, aspectId), !includeTrashed ? isNull(aspects.deletedAt) : undefined)) + .groupBy(aspects.id, aspects.name, aspects.createdAt, aspects.updatedAt, subAspects.id, subAspects.name); + + if (!queryResult.length) + throw notFound({ + message: "The aspect does not exist", + }); + + const subAspectsList = queryResult.reduce((prev, curr) => { + if (!curr.subAspect) return prev; + prev.set(curr.subAspect.id, { + name: curr.subAspect.name, + questionCount: Number(curr.subAspect.questionCount), + }); + return prev; + }, new Map()); + + const aspectData = { + ...queryResult[0], + subAspect: undefined, + subAspects: Array.from(subAspectsList, ([id, { name, questionCount }]) => ({ id, name, questionCount })), + }; + + return c.json(aspectData); + } + ) + + // Create aspect + .post("/", + checkPermission("managementAspect.create"), + requestValidator("json", aspectFormSchema), + async (c) => { + const aspectData = c.req.valid("json"); + + // Check if aspect name already exists and is not deleted + const existingAspect = await db + .select() + .from(aspects) + .where( + and( + eq(aspects.name, aspectData.name), + isNull(aspects.deletedAt) + ) + ); + + if (existingAspect.length > 0) { + // Return an error if the aspect name already exists + return c.json( + { message: "Aspect name already exists" }, + 400 // Bad Request ); } - ) - // Update aspect - .patch( - "/:id", - checkPermission("managementAspect.update"), - requestValidator("json", aspectUpdateSchema), - async (c) => { - const aspectId = c.req.param("id"); - const aspectData = c.req.valid("json"); - - // Cek jika nama aspek baru sudah ada - const existingAspect = await db - .select() - .from(aspects) + // If it doesn't exist, create a new aspect + const aspect = await db + .insert(aspects) + .values({ + name: aspectData.name, + }) + .returning(); + + const aspectId = aspect[0].id; + + // If there is sub aspect data, parse and insert into the database. + if (aspectData.subAspects) { + const subAspectsArray = JSON.parse(aspectData.subAspects) as string[]; + + // Insert new sub aspects into the database without checking for sub aspect duplication + if (subAspectsArray.length) { + await db.insert(subAspects).values( + subAspectsArray.map((subAspect) => ({ + aspectId, + name: subAspect, + })) + ); + } + } + + return c.json( + { + message: "Aspect and sub aspects created successfully", + }, + 201 + ); + } + ) + + // Update aspect + .patch( + "/:id", + checkPermission("managementAspect.update"), + requestValidator("json", aspectUpdateSchema), + async (c) => { + const aspectId = c.req.param("id"); + const aspectData = c.req.valid("json"); + + // Check if new aspect name already exists + const existingAspect = await db + .select() + .from(aspects) + .where( + and( + eq(aspects.name, aspectData.name), + isNull(aspects.deletedAt), + sql`${aspects.id} <> ${aspectId}` + ) + ); + + if (existingAspect.length > 0) { + throw notFound({ + message: "Aspect name already exists", + }); + } + + // Check if the aspect in question exists + const aspect = await db + .select() + .from(aspects) + .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); + + if (!aspect[0]) throw notFound(); + + // Update aspect name + await db + .update(aspects) + .set({ + name: aspectData.name, + updatedAt: new Date(), + }) + .where(eq(aspects.id, aspectId)); + + // Get new sub aspect data from request + const newSubAspects = aspectData.subAspects || []; + + // Take the existing sub aspects + const currentSubAspects = await db + .select({ id: subAspects.id, name: subAspects.name }) + .from(subAspects) + .where(eq(subAspects.aspectId, aspectId)); + + const currentSubAspectMap = new Map(currentSubAspects.map(sub => [sub.id, sub.name])); + + // Sub aspects to be removed + const subAspectsToDelete = currentSubAspects + .filter(sub => !newSubAspects.some(newSub => newSub.id === sub.id)) + .map(sub => sub.id); + + // Delete sub aspects that do not exist in the new data + if (subAspectsToDelete.length) { + await db + .delete(subAspects) .where( and( - eq(aspects.name, aspectData.name), - isNull(aspects.deletedAt), - sql`${aspects.id} <> ${aspectId}` + eq(subAspects.aspectId, aspectId), + inArray(subAspects.id, subAspectsToDelete) ) ); - - if (existingAspect.length > 0) { - throw forbidden({ - message: "Aspect name already exists", - }); - } - - // Cek jika aspek yang dimaksud ada - const aspect = await db - .select() - .from(aspects) - .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); - - if (!aspect[0]) throw notFound(); - - // Update nama aspek - await db - .update(aspects) - .set({ - name: aspectData.name, - updatedAt: new Date(), - }) - .where(eq(aspects.id, aspectId)); - - // Ambil data sub-aspek baru dari request - const newSubAspects = aspectData.subAspects || []; - - // Ambil sub-aspek yang ada saat ini - const currentSubAspects = await db - .select({ id: subAspects.id, name: subAspects.name }) - .from(subAspects) - .where(eq(subAspects.aspectId, aspectId)); - - const currentSubAspectMap = new Map(currentSubAspects.map(sub => [sub.id, sub.name])); - - // Sub-aspek yang harus dihapus - const subAspectsToDelete = currentSubAspects - .filter(sub => !newSubAspects.some(newSub => newSub.id === sub.id)) - .map(sub => sub.id); - - // Hapus sub-aspek yang tidak ada di data baru - if (subAspectsToDelete.length) { + } + + // Update or add new sub aspects + for (const subAspect of newSubAspects) { + const existingSubAspect = currentSubAspectMap.has(subAspect.id); + + if (existingSubAspect) { + // Update if sub aspect already exists await db - .delete(subAspects) + .update(subAspects) + .set({ + name: subAspect.name, + updatedAt: new Date(), + }) .where( and( - eq(subAspects.aspectId, aspectId), - inArray(subAspects.id, subAspectsToDelete) + eq(subAspects.id, subAspect.id), + eq(subAspects.aspectId, aspectId) ) ); + } else { + // Add if new sub aspect + await db + .insert(subAspects) + .values({ + id: subAspect.id, + aspectId, + name: subAspect.name, + createdAt: new Date(), + }); } - - // Update atau tambahkan sub-aspek baru - for (const subAspect of newSubAspects) { - const existingSubAspect = currentSubAspectMap.has(subAspect.id); - - if (existingSubAspect) { - // Update jika sub-aspek sudah ada - await db - .update(subAspects) - .set({ - name: subAspect.name, - updatedAt: new Date(), - }) - .where( - and( - eq(subAspects.id, subAspect.id), - eq(subAspects.aspectId, aspectId) - ) - ); - } else { - // Tambah jika sub-aspek baru - await db - .insert(subAspects) - .values({ - id: subAspect.id, // Pastikan `id` diberikan - aspectId, - name: subAspect.name, - createdAt: new Date(), - }); - } - } - - return c.json({ - message: "Aspect and sub-aspects updated successfully", - }); } - ) - // Delete aspect - .delete( - "/:id", - checkPermission("managementAspect.delete"), - requestValidator( - "form", - z.object({ - // skipTrash: z.string().default("false"), + return c.json({ + message: "Aspect and sub aspects updated successfully", + }); + } + ) + + // Delete aspect + .delete( + "/:id", + checkPermission("managementAspect.delete"), + async (c) => { + const aspectId = c.req.param("id"); + + // Check if aspect exists before deleting + const aspect = await db + .select() + .from(aspects) + .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); + + if (!aspect[0]) + throw notFound({ + message: "The aspect is not found", + }); + + // Update deletedAt column on aspect (soft delete) + await db + .update(aspects) + .set({ + deletedAt: new Date(), }) - ), - async (c) => { - const aspectId = c.req.param("id"); + .where(eq(aspects.id, aspectId)); - // const skipTrash = c.req.valid("form").skipTrash.toLowerCase() === "true"; + // Soft delete related sub aspects (update deletedAt on the sub-aspect) + await db + .update(subAspects) + .set({ + deletedAt: new Date(), + }) + .where(eq(subAspects.aspectId, aspectId)); - const aspect = await db - .select() - .from(aspects) - .where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); + return c.json({ + message: "Aspect and sub aspects soft deleted successfully", + }); + } + ) - if (!aspect[0]) - throw notFound({ - message: "The aspect is not found", - }); + // Undo delete + .patch( + "/restore/:id", + checkPermission("managementAspect.restore"), + async (c) => { + const aspectId = c.req.param("id"); - await db - .update(aspects) - .set({ - deletedAt: new Date(), - }) - .where(eq(aspects.id, aspectId)); - - return c.json({ - message: "Aspect deleted successfully", + // Check if the desired aspects are present + const aspect = (await db.select().from(aspects).where(eq(aspects.id, aspectId)))[0]; + + if (!aspect) { + throw notFound({ + message: "The aspect is not found", }); } - ) - // Undo delete - .patch( - "/restore/:id", - checkPermission("managementAspect.restore"), - async (c) => { - const aspectId = c.req.param("id"); - - const aspect = (await db.select().from(aspects).where(eq(aspects.id, aspectId)))[0]; - - if (!aspect) throw notFound(); - - if (!aspect.deletedAt) { - throw forbidden({ - message: "The aspect is not deleted", - }); - } - - await db.update(aspects).set({ deletedAt: null }).where(eq(aspects.id, aspectId)); - - return c.json({ - message: "Aspect restored successfully", + // Make sure the aspect has been deleted (there is deletedAt) + if (!aspect.deletedAt) { + throw notFound({ + message: "The aspect is not deleted", }); } - ) + + // Restore aspects (remove deletedAt mark) + await db.update(aspects).set({ deletedAt: null }).where(eq(aspects.id, aspectId)); + + // Restore all related sub aspects that have also been deleted (if any) + await db.update(subAspects).set({ deletedAt: null }).where(eq(subAspects.aspectId, aspectId)); + + return c.json({ + message: "Aspect and sub aspects restored successfully", + }); + } + ) export default managementAspectRoute; \ No newline at end of file