summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/service.ts
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-04-28 02:13:30 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-04-28 02:13:30 +0000
commitef4c533ebacc2cdc97e518f30e9a9350004fcdfb (patch)
tree345251a3ed0f4429716fa5edaa31024d8f4cb560 /lib/vendor-investigation/service.ts
parent9ceed79cf32c896f8a998399bf1b296506b2cd4a (diff)
~20250428 작업사항
Diffstat (limited to 'lib/vendor-investigation/service.ts')
-rw-r--r--lib/vendor-investigation/service.ts85
1 files changed, 61 insertions, 24 deletions
diff --git a/lib/vendor-investigation/service.ts b/lib/vendor-investigation/service.ts
index b731a95c..e3d03cd4 100644
--- a/lib/vendor-investigation/service.ts
+++ b/lib/vendor-investigation/service.ts
@@ -12,6 +12,7 @@ import { sendEmail } from "../mail/sendEmail";
import fs from "fs"
import path from "path"
import { v4 as uuid } from "uuid"
+import { vendorsLogs } from "@/db/schema";
export async function getVendorsInvestigation(input: GetVendorsInvestigationSchema) {
return unstable_cache(
@@ -44,7 +45,7 @@ export async function getVendorsInvestigation(input: GetVendorsInvestigationSche
const finalWhere = and(
advancedWhere,
globalWhere,
- eq(vendorInvestigationsView.vendorStatus, "PQ_SUBMITTED")
+ // eq(vendorInvestigationsView.vendorStatus, "PQ_APPROVED")
)
@@ -82,6 +83,8 @@ export async function getVendorsInvestigation(input: GetVendorsInvestigationSche
// 7) Calculate pageCount
const pageCount = Math.ceil(total / input.perPage)
+ console.log(data,"data")
+
// Now 'data' already contains JSON arrays of contacts & items
// thanks to the subqueries in the view definition!
return { data, pageCount }
@@ -100,50 +103,84 @@ export async function getVendorsInvestigation(input: GetVendorsInvestigationSche
}
+/**
+ * Get existing investigations for a list of vendor IDs
+ *
+ * @param vendorIds Array of vendor IDs to check for existing investigations
+ * @returns Array of investigation data
+ */
+export async function getExistingInvestigationsForVendors(vendorIds: number[]) {
+ if (!vendorIds.length) return []
+
+ try {
+ // Query the vendorInvestigationsView using the vendorIds
+ const investigations = await db.query.vendorInvestigations.findMany({
+ where: inArray(vendorInvestigationsView.vendorId, vendorIds),
+ orderBy: [desc(vendorInvestigationsView.investigationCreatedAt)],
+ })
+
+ return investigations
+ } catch (error) {
+ console.error("Error fetching existing investigations:", error)
+ return []
+ }
+}
+
interface RequestInvestigateVendorsInput {
ids: number[]
}
export async function requestInvestigateVendors({
- ids,
-}: RequestInvestigateVendorsInput) {
+ ids, userId // userId를 추가
+}: RequestInvestigateVendorsInput & { userId: number }) {
try {
if (!ids || ids.length === 0) {
return { error: "No vendor IDs provided." }
}
- // 1. Create a new investigation row for each vendor
- // You could also check if an investigation already exists for each vendor
- // before inserting. For now, we’ll assume we always insert new ones.
- const newRecords = await db
- .insert(vendorInvestigations)
- .values(
- ids.map((vendorId) => ({
- vendorId
- }))
- )
- .returning()
-
- // 2. Optionally, send an email notification
- // Adjust recipient, subject, and body as needed.
+ const result = await db.transaction(async (tx) => {
+ // 1. Create a new investigation row for each vendor
+ const newRecords = await tx
+ .insert(vendorInvestigations)
+ .values(
+ ids.map((vendorId) => ({
+ vendorId
+ }))
+ )
+ .returning();
+
+ // 2. 각 벤더에 대해 로그 기록
+ await Promise.all(
+ ids.map(async (vendorId) => {
+ await tx.insert(vendorsLogs).values({
+ vendorId: vendorId,
+ userId: userId,
+ action: "investigation_requested",
+ comment: "Investigation requested for this vendor",
+ });
+ })
+ );
+
+ return newRecords;
+ });
+
+ // 3. 이메일 발송 (트랜잭션 외부에서 실행)
await sendEmail({
to: "dujin.kim@dtsolution.io",
subject: "New Vendor Investigation(s) Requested",
- // This template name could match a Handlebars file like: `investigation-request.hbs`
template: "investigation-request",
context: {
- // For example, if you're translating in Korean:
language: "ko",
- // Add any data you want to use within the template
vendorIds: ids,
notes: "Please initiate the planned investigations soon."
},
- })
+ });
- // 3. Optionally, revalidate any pages that might show updated data
- // revalidatePath("/your-vendors-page") // or wherever you list the vendors
+ // 4. 캐시 무효화
+ revalidateTag("vendors");
+ revalidateTag("vendor-investigations");
- return { data: newRecords, error: null }
+ return { data: result, error: null }
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : String(err)
return { error: errorMessage }