Update : All method API for management-aspect

This commit is contained in:
percyfikri 2024-09-13 10:52:48 +07:00
parent 964e9f4eb7
commit 831759278c

View File

@ -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 { Hono } from "hono";
import { questions } from "../../drizzle/schema/questions";
import { z } from "zod"; import { z } from "zod";
import db from "../../drizzle"; import db from "../../drizzle";
import { aspects } from "../../drizzle/schema/aspects"; import { aspects } from "../../drizzle/schema/aspects";
@ -33,14 +33,16 @@ export const aspectFormSchema = z.object({
.optional(), .optional(),
}); });
export const aspectUpdateSchema = aspectFormSchema.extend({
subAspects: z.string().optional().or(z.literal("")),
});
// Schema for creating and updating subAspects // Schema for creating and updating subAspects
export const subAspectFormSchema = z.object({ export const subAspectFormSchema = z.object({
id: z.string(),
name: z.string().min(1).max(50), 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({}); export const subAspectUpdateSchema = subAspectFormSchema.extend({});
@ -71,17 +73,17 @@ const managementAspectRoute = new Hono<HonoEnv>()
.optional() .optional()
.transform((v) => v?.toLowerCase() === "true"), .transform((v) => v?.toLowerCase() === "true"),
page: z.coerce.number().int().min(0).default(0), 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(""), q: z.string().default(""),
}) })
), ),
async (c) => { async (c) => {
const { includeTrashed, page, limit, q } = c.req.valid("query"); const { includeTrashed, page, limit, q } = c.req.valid("query");
const totalCountQuery = includeTrashed const totalCountQuery = includeTrashed
? sql<number>`(SELECT count(*) FROM ${aspects})` ? sql<number>`(SELECT count(*) FROM ${aspects})`
: sql<number>`(SELECT count(*) FROM ${aspects} WHERE ${aspects.deletedAt} IS NULL)`; : sql<number>`(SELECT count(*) FROM ${aspects} WHERE ${aspects.deletedAt} IS NULL)`;
const result = await db const result = await db
.select({ .select({
id: aspects.id, id: aspects.id,
@ -89,8 +91,8 @@ const managementAspectRoute = new Hono<HonoEnv>()
createdAt: aspects.createdAt, createdAt: aspects.createdAt,
updatedAt: aspects.updatedAt, updatedAt: aspects.updatedAt,
...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}), ...(includeTrashed ? { deletedAt: aspects.deletedAt } : {}),
subAspectId : subAspects.id, subAspectId: subAspects.id,
subAspectName : subAspects.name, subAspectName: subAspects.name,
fullCount: totalCountQuery, fullCount: totalCountQuery,
}) })
.from(aspects) .from(aspects)
@ -103,9 +105,38 @@ const managementAspectRoute = new Hono<HonoEnv>()
) )
.offset(page * limit) .offset(page * limit)
.limit(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<string, {
id: string;
name: string;
createdAt: string | null;
updatedAt: string | null;
subAspects: { id: string; name: string }[];
}>);
const groupedArray = Object.values(groupedResult);
return c.json({ return c.json({
data: result.map((d) => ({ ...d, fullCount: undefined })), data: groupedArray,
_metadata: { _metadata: {
currentPage: page, currentPage: page,
totalPages: Math.ceil((Number(result[0]?.fullCount) ?? 0) / limit), totalPages: Math.ceil((Number(result[0]?.fullCount) ?? 0) / limit),
@ -114,7 +145,7 @@ const managementAspectRoute = new Hono<HonoEnv>()
}, },
}); });
} }
) )
// Get aspect by id // Get aspect by id
.get( .get(
@ -128,14 +159,14 @@ const managementAspectRoute = new Hono<HonoEnv>()
), ),
async (c) => { async (c) => {
const aspectId = c.req.param("id"); const aspectId = c.req.param("id");
if (!aspectId) if (!aspectId)
throw notFound({ throw notFound({
message: "Missing id", message: "Missing id",
}); });
const includeTrashed = c.req.query("includeTrashed")?.toLowerCase() === "true"; const includeTrashed = c.req.query("includeTrashed")?.toLowerCase() === "true";
const queryResult = await db const queryResult = await db
.select({ .select({
id: aspects.id, id: aspects.id,
@ -146,29 +177,35 @@ const managementAspectRoute = new Hono<HonoEnv>()
subAspect: { subAspect: {
name: subAspects.name, name: subAspects.name,
id: subAspects.id, id: subAspects.id,
questionCount: sql`COUNT(${questions.id})`.as("questionCount"),
}, },
}) })
.from(aspects) .from(aspects)
.leftJoin(subAspects, eq(aspects.id, subAspects.aspectId)) .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) if (!queryResult.length)
throw forbidden({ throw forbidden({
message: "The aspect does not exist", message: "The aspect does not exist",
}); });
const subAspectsList = queryResult.reduce((prev, curr) => { const subAspectsList = queryResult.reduce((prev, curr) => {
if (!curr.subAspect) return prev; 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; return prev;
}, new Map<string, string>()); // Map<id, name> }, new Map<string, { name: string; questionCount: number }>());
const aspectData = { const aspectData = {
...queryResult[0], ...queryResult[0],
subAspect: undefined, subAspect: undefined,
subAspects: Array.from(subAspectsList, ([id, name]) => ({ id, name })), subAspects: Array.from(subAspectsList, ([id, { name, questionCount }]) => ({ id, name, questionCount })),
}; };
return c.json(aspectData); return c.json(aspectData);
} }
) )
@ -179,96 +216,160 @@ const managementAspectRoute = new Hono<HonoEnv>()
requestValidator("json", aspectFormSchema), requestValidator("json", aspectFormSchema),
async (c) => { async (c) => {
const aspectData = c.req.valid("json"); const aspectData = c.req.valid("json");
// Validation to check if the aspect name already exists // Cek jika nama aspek sudah ada
const existingAspect = await db const existingAspect = await db
.select() .select()
.from(aspects) .from(aspects)
.where(eq(aspects.name, aspectData.name)); .where(eq(aspects.name, aspectData.name));
if (existingAspect.length > 0) { let aspectId;
throw forbidden({ if (existingAspect.length > 0) {
message: "Aspect name already exists", // Jika aspek sudah ada, ambil ID-nya
}); aspectId = existingAspect[0].id;
} } else {
// Jika tidak ada, buat aspek baru
const aspect = await db const aspect = await db
.insert(aspects) .insert(aspects)
.values({ .values({
name: aspectData.name, name: aspectData.name,
}) })
.returning(); .returning();
aspectId = aspect[0].id;
// 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,
}))
);
} }
}
// 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( return c.json(
{ {
message: "Aspect created successfully", message: "Aspect and sub-aspects created successfully",
}, },
201 201
); );
} }
) )
// Update aspect // Update aspect
.patch( .patch(
"/:id", "/:id",
checkPermission("managementAspect.update"), checkPermission("managementAspect.update"),
requestValidator("json", aspectUpdateSchema), requestValidator("json", aspectUpdateSchema),
async (c) => { async (c) => {
const aspectId = c.req.param("id"); const aspectId = c.req.param("id");
const aspectData = c.req.valid("json"); const aspectData = c.req.valid("json");
// Validation to check if the new aspect name already exists // Cek jika nama aspek baru sudah ada
const existingAspect = await db const existingAspect = await db
.select() .select()
.from(aspects) .from(aspects)
.where( .where(
and( and(
eq(aspects.name, aspectData.name), eq(aspects.name, aspectData.name),
isNull(aspects.deletedAt), isNull(aspects.deletedAt),
sql`${aspects.id} <> ${aspectId}` sql`${aspects.id} <> ${aspectId}`
) )
); );
if (existingAspect.length > 0) { if (existingAspect.length > 0) {
throw forbidden({ throw forbidden({
message: "Aspect name already exists", message: "Aspect name already exists",
}); });
} }
const aspect = await db // Cek jika aspek yang dimaksud ada
.select() const aspect = await db
.from(aspects) .select()
.where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt))); .from(aspects)
.where(and(eq(aspects.id, aspectId), isNull(aspects.deletedAt)));
if (!aspect[0]) throw notFound();
if (!aspect[0]) throw notFound();
await db
.update(aspects) // Update nama aspek
.set({ await db
...aspectData, .update(aspects)
updatedAt: new Date(), .set({
}) name: aspectData.name,
.where(eq(aspects.id, aspectId)); 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({ return c.json({
message: "Aspect updated successfully", message: "Aspect and sub-aspects updated successfully",
}); });
} }
) )
// Delete aspect // Delete aspect
.delete( .delete(
@ -333,159 +434,4 @@ const managementAspectRoute = new Hono<HonoEnv>()
} }
) )
// Get sub aspects by aspect ID export default managementAspectRoute;
.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;