diff options
| author | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-09-30 10:08:53 +0000 |
|---|---|---|
| committer | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-09-30 10:08:53 +0000 |
| commit | 2c02afd48a4d9276a4f5c132e088540a578d0972 (patch) | |
| tree | e5efdd3f48fad33681c139a4c58481f4514fb38e /lib | |
| parent | 19794b32a6e3285fdeda7519ededdce451966f3d (diff) | |
(대표님) 폼리스트, spreadjs 관련 변경사항, 벤더문서 뷰 쿼리 수정, 이메일 템플릿 추가 등
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/docu-list-rule/document-class/table/document-class-option-add-dialog.tsx | 161 | ||||
| -rw-r--r-- | lib/evaluation-criteria/stat.ts | 413 | ||||
| -rw-r--r-- | lib/forms/stat.ts | 209 | ||||
| -rw-r--r-- | lib/mail/templates/pq.hbs | 3 | ||||
| -rw-r--r-- | lib/mail/templates/vendor-rejected.hbs | 195 | ||||
| -rw-r--r-- | lib/projects/service.ts | 23 | ||||
| -rw-r--r-- | lib/rfq-last/attachment/vendor-response-table.tsx | 1 | ||||
| -rw-r--r-- | lib/rfq-last/service.ts | 87 | ||||
| -rw-r--r-- | lib/rfq-last/validations.ts | 2 | ||||
| -rw-r--r-- | lib/rfq-last/vendor/rfq-vendor-table.tsx | 8 | ||||
| -rw-r--r-- | lib/sedp/get-form-tags.ts | 147 | ||||
| -rw-r--r-- | lib/tbe-last/service.ts | 2 | ||||
| -rw-r--r-- | lib/vendor-document-list/ship/send-to-shi-button.tsx | 70 | ||||
| -rw-r--r-- | lib/vendors/table/request-pq-dialog.tsx | 13 |
14 files changed, 1265 insertions, 69 deletions
diff --git a/lib/docu-list-rule/document-class/table/document-class-option-add-dialog.tsx b/lib/docu-list-rule/document-class/table/document-class-option-add-dialog.tsx index 93681c09..31337675 100644 --- a/lib/docu-list-rule/document-class/table/document-class-option-add-dialog.tsx +++ b/lib/docu-list-rule/document-class/table/document-class-option-add-dialog.tsx @@ -5,7 +5,7 @@ import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import { toast } from "sonner" import * as z from "zod" -import { Plus } from "lucide-react" +import { Plus, Check, ChevronsUpDown } from "lucide-react" import { Button } from "@/components/ui/button" import { @@ -25,12 +25,62 @@ import { FormLabel, FormMessage, } from "@/components/ui/form" -import { Input } from "@/components/ui/input" +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, +} from "@/components/ui/command" +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover" +import { cn } from "@/lib/utils" +import { useParams } from "next/navigation" import { createDocumentClassOptionItem } from "@/lib/docu-list-rule/document-class/service" +import { getProjectCode } from "@/lib/projects/service" + +// API 응답 타입 +interface ScheduleSetting { + COL_NM: string + DC_OBX_USE_YN: string + PROJ_COL_NM: string + PROJ_COL_NM_EN: string + SCD_VIEW_MGNT: string + USE_YN1: string + USE_YN2: string +} + +// 프로젝트 일정 설정을 가져오는 함수 +async function getProjectKindScheduleSetting(projectCode: string): Promise<ScheduleSetting[]> { + try { + const response = await fetch( + `http://60.100.99.217/DDP/Services/VNDRService.svc/GetProjectKindScheduleSetting?PROJ_NO=${projectCode}`, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + } + ) + + if (!response.ok) { + throw new Error('Failed to fetch schedule settings') + } + + const data = await response.json() + return data.GetProjectKindScheduleSettingResult || [] + } catch (error) { + console.error('Error fetching schedule settings:', error) + return [] + } +} const createOptionSchema = z.object({ - optionCode: z.string().min(1, "코드는 필수입니다."), + optionCode: z.string().min(1, "옵션을 선택해주세요."), }) type CreateOptionSchema = z.infer<typeof createOptionSchema> @@ -42,7 +92,12 @@ interface DocumentClassOptionAddDialogProps { export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: DocumentClassOptionAddDialogProps) { const [open, setOpen] = React.useState(false) + const [comboboxOpen, setComboboxOpen] = React.useState(false) const [isPending, startTransition] = React.useTransition() + const [scheduleSettings, setScheduleSettings] = React.useState<ScheduleSetting[]>([]) + const [isLoading, setIsLoading] = React.useState(false) + const params = useParams() + const projectId = Number(params?.projectId) const form = useForm<CreateOptionSchema>({ resolver: zodResolver(createOptionSchema), @@ -51,6 +106,35 @@ export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: Doc }, }) + // Dialog가 열릴 때 데이터 로드 + React.useEffect(() => { + if (open && projectId) { + loadScheduleSettings() + } + }, [open, projectId]) + + const loadScheduleSettings = async () => { + setIsLoading(true) + try { + // 먼저 projectId로 프로젝트 코드 가져오기 + const projectCode = await getProjectCode(projectId) + + if (!projectCode) { + toast.error("프로젝트 코드를 찾을 수 없습니다.") + return + } + + // 프로젝트 코드로 일정 설정 가져오기 + const settings = await getProjectKindScheduleSetting(projectCode) + setScheduleSettings(settings) + } catch (error) { + console.error("Error loading schedule settings:", error) + toast.error("옵션 목록을 불러오는 중 오류가 발생했습니다.") + } finally { + setIsLoading(false) + } + } + const handleSubmit = (data: CreateOptionSchema) => { startTransition(async () => { try { @@ -79,6 +163,10 @@ export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: Doc form.reset() } + const selectedOption = scheduleSettings.find( + (setting) => setting.COL_NM === form.watch("optionCode") + ) + return ( <Dialog open={open} onOpenChange={setOpen}> <DialogTrigger asChild> @@ -100,11 +188,66 @@ export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: Doc control={form.control} name="optionCode" render={({ field }) => ( - <FormItem> - <FormLabel>코드</FormLabel> - <FormControl> - <Input {...field} placeholder="옵션 코드" /> - </FormControl> + <FormItem className="flex flex-col"> + <FormLabel>옵션 선택</FormLabel> + <Popover open={comboboxOpen} onOpenChange={setComboboxOpen}> + <PopoverTrigger asChild> + <FormControl> + <Button + variant="outline" + role="combobox" + aria-expanded={comboboxOpen} + className={cn( + "w-full justify-between", + !field.value && "text-muted-foreground" + )} + disabled={isLoading} + > + {isLoading + ? "로딩 중..." + : selectedOption + ? `${selectedOption.COL_NM} - ${selectedOption.PROJ_COL_NM}` + : "옵션을 선택하세요"} + <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> + </Button> + </FormControl> + </PopoverTrigger> + <PopoverContent className="w-full p-0"> + <Command> + <CommandInput placeholder="옵션 검색..." /> + <CommandEmpty> + {isLoading ? "로딩 중..." : "검색 결과가 없습니다."} + </CommandEmpty> + <CommandGroup className="max-h-[200px] overflow-auto"> + {scheduleSettings.map((setting) => ( + <CommandItem + key={setting.COL_NM} + value={`${setting.COL_NM} ${setting.PROJ_COL_NM}`} + onSelect={() => { + form.setValue("optionCode", setting.COL_NM) + setComboboxOpen(false) + }} + > + <Check + className={cn( + "mr-2 h-4 w-4", + field.value === setting.COL_NM + ? "opacity-100" + : "opacity-0" + )} + /> + <div className="flex flex-col"> + <span className="font-medium">{setting.COL_NM}</span> + <span className="text-sm text-muted-foreground"> + {setting.PROJ_COL_NM} + </span> + </div> + </CommandItem> + ))} + </CommandGroup> + </Command> + </PopoverContent> + </Popover> <FormMessage /> </FormItem> )} @@ -122,4 +265,4 @@ export function DocumentClassOptionAddDialog({ documentClassId, onSuccess }: Doc </DialogContent> </Dialog> ) -}
\ No newline at end of file +}
\ No newline at end of file diff --git a/lib/evaluation-criteria/stat.ts b/lib/evaluation-criteria/stat.ts new file mode 100644 index 00000000..c39c8627 --- /dev/null +++ b/lib/evaluation-criteria/stat.ts @@ -0,0 +1,413 @@ +"use server" + +import db from "@/db/db" +import { vendors, contracts, contractItems, forms, formEntries, formMetas, tags, tagClasses, tagClassAttributes, projects } from "@/db/schema" +import { eq, and, inArray } from "drizzle-orm" +import { getEditableFieldsByTag } from "./services" +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" + +interface VendorFormStatus { + vendorId: number + vendorName: string + formCount: number // 벤더가 가진 form 개수 + tagCount: number // 벤더가 가진 tag 개수 + totalFields: number // 입력해야 하는 총 필드 개수 + completedFields: number // 입력 완료된 필드 개수 + completionRate: number // 완료율 (%) +} + +export interface FormStatusByVendor { + tagCount: number; + totalFields: number; + completedFields: number; + completionRate: number; + upcomingCount: number; // 7일 이내 임박한 개수 + overdueCount: number; // 지연된 개수 +} + +export async function getProjectsWithContracts() { + try { + const projectList = await db + .selectDistinct({ + id: projects.id, + projectCode: projects.code, + projectName: projects.name, + }) + .from(projects) + .innerJoin(contracts, eq(contracts.projectId, projects.id)) + .orderBy(projects.code) + + return projectList + } catch (error) { + console.error('Error getting projects with contracts:', error) + throw new Error('계약이 있는 프로젝트 조회 중 오류가 발생했습니다.') + } +} + + + +export async function getVendorFormStatus(projectId?: number): Promise<VendorFormStatus[]> { + try { + // 1. 벤더 조회 쿼리 수정 + const vendorList = projectId + ? await db + .selectDistinct({ + vendorId: vendors.id, + vendorName: vendors.vendorName, + }) + .from(vendors) + .innerJoin(contracts, eq(contracts.vendorId, vendors.id)) + .where(eq(contracts.projectId, projectId)) + : await db + .selectDistinct({ + vendorId: vendors.id, + vendorName: vendors.vendorName, + }) + .from(vendors) + .innerJoin(contracts, eq(contracts.vendorId, vendors.id)) + + + const vendorStatusList: VendorFormStatus[] = [] + + for (const vendor of vendorList) { + let vendorFormCount = 0 + let vendorTagCount = 0 + let vendorTotalFields = 0 + let vendorCompletedFields = 0 + const uniqueTags = new Set<string>() + + // 2. 계약 조회 시 projectId 필터 추가 + const vendorContracts = projectId + ? await db + .select({ + id: contracts.id, + projectId: contracts.projectId + }) + .from(contracts) + .where( + and( + eq(contracts.vendorId, vendor.vendorId), + eq(contracts.projectId, projectId) + ) + ) + : await db + .select({ + id: contracts.id, + projectId: contracts.projectId + }) + .from(contracts) + .where(eq(contracts.vendorId, vendor.vendorId)) + + + for (const contract of vendorContracts) { + // 3. 계약별 contractItems 조회 + const contractItemsList = await db + .select({ + id: contractItems.id + }) + .from(contractItems) + .where(eq(contractItems.contractId, contract.id)) + + for (const contractItem of contractItemsList) { + // 4. contractItem별 forms 조회 + const formsList = await db + .select({ + id: forms.id, + formCode: forms.formCode, + contractItemId: forms.contractItemId + }) + .from(forms) + .where(eq(forms.contractItemId, contractItem.id)) + + vendorFormCount += formsList.length + + // 5. formEntries 조회 + const entriesList = await db + .select({ + id: formEntries.id, + formCode: formEntries.formCode, + data: formEntries.data + }) + .from(formEntries) + .where(eq(formEntries.contractItemId, contractItem.id)) + + // 6. TAG별 편집 가능 필드 조회 + const editableFieldsByTag = await getEditableFieldsByTag(contractItem.id, contract.projectId) + + for (const entry of entriesList) { + // formMetas에서 해당 formCode의 columns 조회 + const metaResult = await db + .select({ + columns: formMetas.columns + }) + .from(formMetas) + .where( + and( + eq(formMetas.formCode, entry.formCode), + eq(formMetas.projectId, contract.projectId) + ) + ) + .limit(1) + + if (metaResult.length === 0) continue + + const metaColumns = metaResult[0].columns as any[] + + // shi가 'IN' 또는 'BOTH'인 필드 찾기 + const inputRequiredFields = metaColumns + .filter(col => col.shi === 'IN' || col.shi === 'BOTH') + .map(col => col.key) + + // entry.data 분석 (배열로 가정) + const dataArray = Array.isArray(entry.data) ? entry.data : [] + + for (const dataItem of dataArray) { + if (typeof dataItem !== 'object' || !dataItem) continue + + const tagNo = dataItem.TAG_NO + if (tagNo) { + uniqueTags.add(tagNo) + + // TAG별 편집 가능 필드 가져오기 + const tagEditableFields = editableFieldsByTag.get(tagNo) || [] + + // 최종 입력 필요 필드 = shi 기반 필드 + TAG 기반 편집 가능 필드 + const allRequiredFields = inputRequiredFields.filter(field => + tagEditableFields.includes(field) + ) + // 각 필드별 입력 상태 체크 + for (const fieldKey of allRequiredFields) { + vendorTotalFields++ + + const fieldValue = dataItem[fieldKey] + // 값이 있고, 빈 문자열이 아니고, null이 아니면 입력 완료 + if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { + vendorCompletedFields++ + } + } + } + } + } + } + } + + // 완료율 계산 + const completionRate = vendorTotalFields > 0 + ? Math.round((vendorCompletedFields / vendorTotalFields) * 100 * 10) / 10 + : 0 + + vendorStatusList.push({ + vendorId: vendor.vendorId, + vendorName: vendor.vendorName || '이름 없음', + formCount: vendorFormCount, + tagCount: uniqueTags.size, + totalFields: vendorTotalFields, + completedFields: vendorCompletedFields, + completionRate + }) + } + + return vendorStatusList + + } catch (error) { + console.error('Error getting vendor form status:', error) + throw new Error('벤더별 Form 입력 현황 조회 중 오류가 발생했습니다.') + } +} + + + +export async function getFormStatusByVendor(projectId: number, formCode: string): Promise<FormStatusByVendor[]> { + try { + const session = await getServerSession(authOptions) + if (!session?.user?.id) { + throw new Error("인증이 필요합니다.") + } + + const vendorStatusList: FormStatusByVendor[] = [] + const vendorId = Number(session.user.companyId) + + const vendorContracts = await db + .select({ + id: contracts.id, + projectId: contracts.projectId + }) + .from(contracts) + .where( + and( + eq(contracts.vendorId, vendorId), + eq(contracts.projectId, projectId) + ) + ) + + const contractIds = vendorContracts.map(v => v.id) + + const contractItemsList = await db + .select({ + id: contractItems.id + }) + .from(contractItems) + .where(inArray(contractItems.contractId, contractIds)) + + const contractItemIds = contractItemsList.map(v => v.id) + + let vendorFormCount = 0 + let vendorTagCount = 0 + let vendorTotalFields = 0 + let vendorCompletedFields = 0 + let vendorUpcomingCount = 0 // 7일 이내 임박한 개수 + let vendorOverdueCount = 0 // 지연된 개수 + const uniqueTags = new Set<string>() + const processedTags = new Set<string>() // 중복 처리 방지용 + + // 현재 날짜와 7일 후 날짜 계산 + const today = new Date() + today.setHours(0, 0, 0, 0) // 시간 부분 제거 + const sevenDaysLater = new Date(today) + sevenDaysLater.setDate(sevenDaysLater.getDate() + 7) + + // 4. contractItem별 forms 조회 + const formsList = await db + .select({ + id: forms.id, + formCode: forms.formCode, + contractItemId: forms.contractItemId + }) + .from(forms) + .where( + and( + inArray(forms.contractItemId, contractItemIds), + eq(forms.formCode, formCode) + ) + ) + + vendorFormCount += formsList.length + + // 5. formEntries 조회 + const entriesList = await db + .select({ + id: formEntries.id, + formCode: formEntries.formCode, + data: formEntries.data + }) + .from(formEntries) + .where( + and( + inArray(formEntries.contractItemId, contractItemIds), + eq(formEntries.formCode, formCode) + ) + ) + + // 6. TAG별 편집 가능 필드 조회 + const editableFieldsByTag = new Map<string, string[]>() + + for (const contractItemId of contractItemIds) { + const tagFields = await getEditableFieldsByTag(contractItemId, projectId) + + tagFields.forEach((fields, tagNo) => { + if (!editableFieldsByTag.has(tagNo)) { + editableFieldsByTag.set(tagNo, fields) + } else { + const existingFields = editableFieldsByTag.get(tagNo) || [] + const mergedFields = [...new Set([...existingFields, ...fields])] + editableFieldsByTag.set(tagNo, mergedFields) + } + }) + } + + for (const entry of entriesList) { + const metaResult = await db + .select({ + columns: formMetas.columns + }) + .from(formMetas) + .where( + and( + eq(formMetas.formCode, entry.formCode), + eq(formMetas.projectId, projectId) + ) + ) + .limit(1) + + if (metaResult.length === 0) continue + + const metaColumns = metaResult[0].columns as any[] + + const inputRequiredFields = metaColumns + .filter(col => col.shi === 'IN' || col.shi === 'BOTH') + .map(col => col.key) + + const dataArray = Array.isArray(entry.data) ? entry.data : [] + + for (const dataItem of dataArray) { + if (typeof dataItem !== 'object' || !dataItem) continue + + const tagNo = dataItem.TAG_NO + if (tagNo) { + uniqueTags.add(tagNo) + + // TAG별 편집 가능 필드 가져오기 + const tagEditableFields = editableFieldsByTag.get(tagNo) || [] + + const allRequiredFields = inputRequiredFields.filter(field => + tagEditableFields.includes(field) + ) + + // 해당 TAG의 필드 완료 상태 체크 + let tagHasIncompleteFields = false + + for (const fieldKey of allRequiredFields) { + vendorTotalFields++ + + const fieldValue = dataItem[fieldKey] + if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { + vendorCompletedFields++ + } else { + tagHasIncompleteFields = true + } + } + + // 미완료 TAG에 대해서만 날짜 체크 (TAG당 한 번만 처리) + if (!processedTags.has(tagNo) && tagHasIncompleteFields) { + processedTags.add(tagNo) + + const targetDate = dataItem.target_date + if (targetDate) { + const target = new Date(targetDate) + target.setHours(0, 0, 0, 0) // 시간 부분 제거 + + if (target < today) { + // 미완료이면서 지연된 경우 (오늘보다 이전) + vendorOverdueCount++ + } else if (target >= today && target <= sevenDaysLater) { + // 미완료이면서 7일 이내 임박한 경우 + vendorUpcomingCount++ + } + } + } + } + } + } + + // 완료율 계산 + const completionRate = vendorTotalFields > 0 + ? Math.round((vendorCompletedFields / vendorTotalFields) * 100 * 10) / 10 + : 0 + + vendorStatusList.push({ + tagCount: uniqueTags.size, + totalFields: vendorTotalFields, + completedFields: vendorCompletedFields, + completionRate, + upcomingCount: vendorUpcomingCount, + overdueCount: vendorOverdueCount + }) + + return vendorStatusList + + } catch (error) { + console.error('Error getting vendor form status:', error) + throw new Error('벤더별 Form 입력 현황 조회 중 오류가 발생했습니다.') + } +}
\ No newline at end of file diff --git a/lib/forms/stat.ts b/lib/forms/stat.ts index 80193c48..054f2462 100644 --- a/lib/forms/stat.ts +++ b/lib/forms/stat.ts @@ -2,8 +2,10 @@ import db from "@/db/db" import { vendors, contracts, contractItems, forms, formEntries, formMetas, tags, tagClasses, tagClassAttributes, projects } from "@/db/schema" -import { eq, and } from "drizzle-orm" +import { eq, and, inArray } from "drizzle-orm" import { getEditableFieldsByTag } from "./services" +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" interface VendorFormStatus { vendorId: number @@ -15,6 +17,15 @@ interface VendorFormStatus { completionRate: number // 완료율 (%) } +export interface FormStatusByVendor { + tagCount: number; + totalFields: number; + completedFields: number; + completionRate: number; + upcomingCount: number; // 7일 이내 임박한 개수 + overdueCount: number; // 지연된 개수 +} + export async function getProjectsWithContracts() { try { const projectList = await db @@ -204,3 +215,199 @@ export async function getVendorFormStatus(projectId?: number): Promise<VendorFor throw new Error('벤더별 Form 입력 현황 조회 중 오류가 발생했습니다.') } } + + + +export async function getFormStatusByVendor(projectId: number, formCode: string): Promise<FormStatusByVendor[]> { + try { + const session = await getServerSession(authOptions) + if (!session?.user?.id) { + throw new Error("인증이 필요합니다.") + } + + const vendorStatusList: FormStatusByVendor[] = [] + const vendorId = Number(session.user.companyId) + + const vendorContracts = await db + .select({ + id: contracts.id, + projectId: contracts.projectId + }) + .from(contracts) + .where( + and( + eq(contracts.vendorId, vendorId), + eq(contracts.projectId, projectId) + ) + ) + + const contractIds = vendorContracts.map(v => v.id) + + const contractItemsList = await db + .select({ + id: contractItems.id + }) + .from(contractItems) + .where(inArray(contractItems.contractId, contractIds)) + + const contractItemIds = contractItemsList.map(v => v.id) + + let vendorFormCount = 0 + let vendorTagCount = 0 + let vendorTotalFields = 0 + let vendorCompletedFields = 0 + let vendorUpcomingCount = 0 // 7일 이내 임박한 개수 + let vendorOverdueCount = 0 // 지연된 개수 + const uniqueTags = new Set<string>() + const processedTags = new Set<string>() // 중복 처리 방지용 + + // 현재 날짜와 7일 후 날짜 계산 + const today = new Date() + today.setHours(0, 0, 0, 0) // 시간 부분 제거 + const sevenDaysLater = new Date(today) + sevenDaysLater.setDate(sevenDaysLater.getDate() + 7) + + // 4. contractItem별 forms 조회 + const formsList = await db + .select({ + id: forms.id, + formCode: forms.formCode, + contractItemId: forms.contractItemId + }) + .from(forms) + .where( + and( + inArray(forms.contractItemId, contractItemIds), + eq(forms.formCode, formCode) + ) + ) + + vendorFormCount += formsList.length + + // 5. formEntries 조회 + const entriesList = await db + .select({ + id: formEntries.id, + formCode: formEntries.formCode, + data: formEntries.data + }) + .from(formEntries) + .where( + and( + inArray(formEntries.contractItemId, contractItemIds), + eq(formEntries.formCode, formCode) + ) + ) + + // 6. TAG별 편집 가능 필드 조회 + const editableFieldsByTag = new Map<string, string[]>() + + for (const contractItemId of contractItemIds) { + const tagFields = await getEditableFieldsByTag(contractItemId, projectId) + + tagFields.forEach((fields, tagNo) => { + if (!editableFieldsByTag.has(tagNo)) { + editableFieldsByTag.set(tagNo, fields) + } else { + const existingFields = editableFieldsByTag.get(tagNo) || [] + const mergedFields = [...new Set([...existingFields, ...fields])] + editableFieldsByTag.set(tagNo, mergedFields) + } + }) + } + + for (const entry of entriesList) { + const metaResult = await db + .select({ + columns: formMetas.columns + }) + .from(formMetas) + .where( + and( + eq(formMetas.formCode, entry.formCode), + eq(formMetas.projectId, projectId) + ) + ) + .limit(1) + + if (metaResult.length === 0) continue + + const metaColumns = metaResult[0].columns as any[] + + const inputRequiredFields = metaColumns + .filter(col => col.shi === 'IN' || col.shi === 'BOTH') + .map(col => col.key) + + const dataArray = Array.isArray(entry.data) ? entry.data : [] + + for (const dataItem of dataArray) { + if (typeof dataItem !== 'object' || !dataItem) continue + + const tagNo = dataItem.TAG_NO + if (tagNo) { + uniqueTags.add(tagNo) + + // TAG별 편집 가능 필드 가져오기 + const tagEditableFields = editableFieldsByTag.get(tagNo) || [] + + const allRequiredFields = inputRequiredFields.filter(field => + tagEditableFields.includes(field) + ) + + // 해당 TAG의 필드 완료 상태 체크 + let tagHasIncompleteFields = false + + for (const fieldKey of allRequiredFields) { + vendorTotalFields++ + + const fieldValue = dataItem[fieldKey] + if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { + vendorCompletedFields++ + } else { + tagHasIncompleteFields = true + } + } + + // 미완료 TAG에 대해서만 날짜 체크 (TAG당 한 번만 처리) + if (!processedTags.has(tagNo) && tagHasIncompleteFields) { + processedTags.add(tagNo) + + const targetDate = dataItem.DUE_DATE + if (targetDate) { + const target = new Date(targetDate) + target.setHours(0, 0, 0, 0) // 시간 부분 제거 + + if (target < today) { + // 미완료이면서 지연된 경우 (오늘보다 이전) + vendorOverdueCount++ + } else if (target >= today && target <= sevenDaysLater) { + // 미완료이면서 7일 이내 임박한 경우 + vendorUpcomingCount++ + } + } + } + } + } + } + + // 완료율 계산 + const completionRate = vendorTotalFields > 0 + ? Math.round((vendorCompletedFields / vendorTotalFields) * 100 * 10) / 10 + : 0 + + vendorStatusList.push({ + tagCount: uniqueTags.size, + totalFields: vendorTotalFields, + completedFields: vendorCompletedFields, + completionRate, + upcomingCount: vendorUpcomingCount, + overdueCount: vendorOverdueCount + }) + + return vendorStatusList + + } catch (error) { + console.error('Error getting vendor form status:', error) + throw new Error('벤더별 Form 입력 현황 조회 중 오류가 발생했습니다.') + } +}
\ No newline at end of file diff --git a/lib/mail/templates/pq.hbs b/lib/mail/templates/pq.hbs index 02523696..abdff056 100644 --- a/lib/mail/templates/pq.hbs +++ b/lib/mail/templates/pq.hbs @@ -61,9 +61,6 @@ 아래의 해당 링크를 통해 당사 eVCP시스템에 접속하시어 요청드린 PQ 항목 및 자료에 대한 제출 요청드립니다.
</p>
- <p style="font-size:16px; line-height:32px;">
- 별도의 견적을 제출하시어 당사에서 적극 검토할 수 있도록 협조 바랍니다.
- </p>
<p style="font-size:16px; line-height:32px;">
귀사의 제출 자료 및 정보는 아래의 제출 마감일 이전에 당사로 제출 되어야 하며,
diff --git a/lib/mail/templates/vendor-rejected.hbs b/lib/mail/templates/vendor-rejected.hbs new file mode 100644 index 00000000..22a1d6f3 --- /dev/null +++ b/lib/mail/templates/vendor-rejected.hbs @@ -0,0 +1,195 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>eVCP 메일</title> + <style> + body { + margin: 0 !important; + padding: 20px !important; + background-color: #f4f4f4; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; + } + .email-container { + max-width: 600px; + margin: 0 auto; + background-color: #ffffff; + padding: 20px; + border-radius: 8px; + box-shadow: 0 2px 10px rgba(0,0,0,0.1); + } + .rejected-badge { + display: inline-block; + background-color: #ef4444; + color: white; + padding: 4px 12px; + border-radius: 16px; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + margin-bottom: 16px; + } + .cta-button { + display: inline-block; + width: 250px; + padding: 12px 20px; + background-color: #163CC4; + color: #ffffff !important; + text-decoration: none; + border-radius: 8px; + text-align: center; + line-height: 28px; + margin: 8px 0; + } + .highlight-box { + background-color: #fef2f2; + border-left: 4px solid #ef4444; + padding: 16px; + margin: 16px 0; + border-radius: 0 8px 8px 0; + } + </style> +</head> +<body> + <div class="email-container"> + <!-- Header --> + <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:24px; border-bottom:1px solid #163CC4; padding-bottom:16px;"> + <tr> + <td align="center"> + <span style="display: block; text-align: left; color: #163CC4; font-weight: bold; font-size: 32px;">eVCP</span> + </td> + </tr> + </table> + + <!-- Rejected Badge --> + <div class="rejected-badge"> + {{#if (eq language 'ko')}}등록 거절{{else}}REGISTRATION REJECTED{{/if}} + </div> + + <!-- Title --> + <h1 style="font-size:28px; margin-bottom:16px; color:#111827;"> + {{#if (eq language 'ko')}} + 업체 등록 신청이 거절되었습니다 + {{else}} + Your Vendor Registration Has Been Rejected + {{/if}} + </h1> + + <!-- Greeting --> + <p style="font-size:16px; line-height:32px; margin-bottom:16px;"> + {{#if (eq language 'ko')}} + 안녕하세요, <strong>{{vendorName}}</strong> 담당자님. + {{else}} + Hello, <strong>{{vendorName}}</strong> representative. + {{/if}} + </p> + + <!-- Main Content --> + <p style="font-size:16px; line-height:32px; margin-bottom:16px;"> + {{#if (eq language 'ko')}} + 귀하의 업체 등록 신청이 검토 결과 거절되었습니다. + 등록 기준에 부합하지 않거나 추가 정보 확인이 필요하여 거절 처리되었습니다. + {{else}} + After review, your vendor registration application has been rejected. + The application did not meet our registration criteria or required additional verification. + {{/if}} + </p> + + <!-- Highlight Box --> + <div class="highlight-box"> + <h3 style="margin-top:0; margin-bottom:12px; color:#dc2626;"> + {{#if (eq language 'ko')}}거절 사유 및 향후 절차{{else}}Rejection Reason & Next Steps{{/if}} + </h3> + <ol style="margin:0; padding-left:20px;"> + <li style="margin-bottom:8px;"> + {{#if (eq language 'ko')}} + 등록 기준에 부합하지 않거나 제출 정보가 불충분합니다 + {{else}} + The application did not meet registration criteria or submitted information was insufficient + {{/if}} + </li> + <li style="margin-bottom:8px;"> + {{#if (eq language 'ko')}} + 추가 정보 확인 및 보완이 필요한 경우 재신청 가능합니다 + {{else}} + You may reapply if you can provide additional information and meet requirements + {{/if}} + </li> + <li style="margin-bottom:8px;"> + {{#if (eq language 'ko')}} + 재신청을 원하시면 모든 필요 서류를 준비하여 다시 신청해주세요 + {{else}} + If you wish to reapply, please prepare all required documents and submit again + {{/if}} + </li> + </ol> + </div> + + <!-- Action Button --> + <div style="text-align: center; margin: 24px 0;"> + <a href="{{loginUrl}}" target="_blank" class="cta-button"> + {{#if (eq language 'ko')}} + eVCP 플랫폼 방문하기 + {{else}} + Visit eVCP Platform + {{/if}} + </a> + </div> + + <!-- Account Info --> + <div style="background-color:#f9fafb; padding:16px; border-radius:8px; margin:16px 0;"> + <h4 style="margin-top:0; margin-bottom:12px; color:#374151;"> + {{#if (eq language 'ko')}}신청 정보{{else}}Application Information{{/if}} + </h4> + <p style="margin:4px 0; font-size:14px; color:#6b7280;"> + <strong>{{#if (eq language 'ko')}}업체명{{else}}Company{{/if}}:</strong> {{vendorName}} + </p> + <p style="margin:4px 0; font-size:14px; color:#6b7280;"> + <strong>{{#if (eq language 'ko')}}이메일{{else}}Email{{/if}}:</strong> {{email}} + </p> + <p style="margin:4px 0; font-size:14px; color:#6b7280;"> + <strong>{{#if (eq language 'ko')}}신청 상태{{else}}Application Status{{/if}}:</strong> + <span style="color:#ef4444; font-weight:600;"> + {{#if (eq language 'ko')}}거절됨{{else}}Rejected{{/if}} + </span> + </p> + </div> + + <!-- Support Message --> + <p style="font-size:16px; line-height:24px; margin-top:24px; color:#6b7280;"> + {{#if (eq language 'ko')}} + 등록 기준에 대한 자세한 내용은 eVCP 플랫폼을 방문하시거나 + <a href="mailto:{{supportEmail}}" style="color:#163CC4;">{{supportEmail}}</a>로 + 문의해 주세요. + {{else}} + For more information about registration criteria, please visit the eVCP platform or + contact us at <a href="mailto:{{supportEmail}}" style="color:#163CC4;">{{supportEmail}}</a>. + {{/if}} + </p> + + <!-- Footer --> + <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:32px; border-top:1px solid #e5e7eb; padding-top:16px;"> + <tr> + <td align="center"> + <p style="font-size:14px; color:#6b7280; margin:4px 0;"> + © {{currentYear}} EVCP. + {{#if (eq language 'ko')}} + 모든 권리 보유. + {{else}} + All rights reserved. + {{/if}} + </p> + <p style="font-size:14px; color:#6b7280; margin:4px 0;"> + {{#if (eq language 'ko')}} + 본 이메일은 발신 전용입니다. 회신하지 마세요. + {{else}} + This is an automated email. Please do not reply. + {{/if}} + </p> + </td> + </tr> + </table> + </div> +</body> +</html> diff --git a/lib/projects/service.ts b/lib/projects/service.ts index 3f562e20..4685fce4 100644 --- a/lib/projects/service.ts +++ b/lib/projects/service.ts @@ -112,4 +112,27 @@ export async function getAllProjectInfoByProjectCode(projectCode: string) { .from(projects) .where(eq(projects.code, projectCode)) .limit(1); +} + +/** + * projectId로 프로젝트 코드를 가져오는 함수 + * @param projectId - 프로젝트 ID + * @returns 프로젝트 코드 또는 null + */ +export async function getProjectCode(projectId: number): Promise<string | null> { + try { + const project = await db.project.findUnique({ + where: { + id: projectId, + }, + select: { + code: true, + }, + }) + + return project?.code || null + } catch (error) { + console.error("Error fetching project code:", error) + return null + } }
\ No newline at end of file diff --git a/lib/rfq-last/attachment/vendor-response-table.tsx b/lib/rfq-last/attachment/vendor-response-table.tsx index 8be5210f..076fb153 100644 --- a/lib/rfq-last/attachment/vendor-response-table.tsx +++ b/lib/rfq-last/attachment/vendor-response-table.tsx @@ -159,7 +159,6 @@ export function VendorResponseTable({ const [isUpdating, setIsUpdating] = React.useState(false); const [showTypeDialog, setShowTypeDialog] = React.useState(false); const [selectedType, setSelectedType] = React.useState<"구매" | "설계" | "">(""); - console.log(data,"data") const [selectedVendor, setSelectedVendor] = React.useState<string | null>(null); diff --git a/lib/rfq-last/service.ts b/lib/rfq-last/service.ts index 8eed9bee..09d707d7 100644 --- a/lib/rfq-last/service.ts +++ b/lib/rfq-last/service.ts @@ -3643,7 +3643,7 @@ async function handleTbeSession({ sessionCode: sessionCode, sessionTitle: `${rfqData.rfqCode} - ${vendor.vendorName} 기술검토`, sessionType: "initial", - status: "준비중", + status: "생성중", evaluationResult: null, plannedStartDate: rfqData.dueDate ? addDays(new Date(rfqData.dueDate), 1) @@ -4738,13 +4738,12 @@ export async function updateShortList( // 트랜잭션으로 처리 const result = await db.transaction(async (tx) => { - // 해당 RFQ의 모든 벤더들의 shortList를 먼저 false로 설정 (선택적) - // 만약 선택된 것만 true로 하고 나머지는 그대로 두려면 이 부분 제거 + // 1. 해당 RFQ의 모든 벤더들의 shortList를 먼저 false로 설정 await tx .update(rfqLastDetails) .set({ shortList: false, - updatedBy: session.user.id, + updatedBy: Number(session.user.id), updatedAt: new Date() }) .where( @@ -4754,15 +4753,16 @@ export async function updateShortList( ) ); - // 선택된 벤더들의 shortList를 true로 설정 + // 2. 선택된 벤더들 처리 if (vendorIds.length > 0) { - const updates = await Promise.all( + // 2-1. 선택된 벤더들의 shortList를 true로 설정 + const updatedDetails = await Promise.all( vendorIds.map(vendorId => tx .update(rfqLastDetails) .set({ shortList: shortListStatus, - updatedBy: session.user.id, + updatedBy: Number(session.user.id), updatedAt: new Date() }) .where( @@ -4776,17 +4776,84 @@ export async function updateShortList( ) ); + // 2-2. TBE 세션 처리 (shortList가 true인 경우에만) + if (shortListStatus) { + // 각 벤더에 대한 rfqLastDetailsId 추출 + const detailsMap = new Map( + updatedDetails.flat().map(detail => [detail.vendorsId, detail.id]) + ); + + // TBE 세션 생성 또는 업데이트 + await Promise.all( + vendorIds.map(async (vendorId) => { + const rfqLastDetailsId = detailsMap.get(vendorId); + + if (!rfqLastDetailsId) { + console.warn(`rfqLastDetailsId not found for vendorId: ${vendorId}`); + return; + } + + // 기존 활성 TBE 세션이 있는지 확인 + const existingSession = await tx + .select() + .from(rfqLastTbeSessions) + .where( + and( + eq(rfqLastTbeSessions.rfqsLastId, rfqId), + eq(rfqLastTbeSessions.vendorId, vendorId), + inArray(rfqLastTbeSessions.status, ["생성중", "준비중", "진행중", "검토중", "보류"]) + ) + ) + .limit(1); + + if (existingSession.length > 0) { + // 기존 세션이 있으면 상태 업데이트 + await tx + .update(rfqLastTbeSessions) + .set({ + status: "준비중", + updatedBy: session.user.id, + updatedAt: new Date() + }) + .where(eq(rfqLastTbeSessions.id, existingSession[0].id)); + } + }) + ); + } else { + // shortList가 false인 경우, 해당 벤더들의 활성 TBE 세션을 취소 상태로 변경 + await Promise.all( + vendorIds.map(vendorId => + tx + .update(rfqLastTbeSessions) + .set({ + status: "취소", + updatedBy: Number(session.user.id), + updatedAt: new Date() + }) + .where( + and( + eq(rfqLastTbeSessions.rfqsLastId, rfqId), + eq(rfqLastTbeSessions.vendorId, vendorId), + inArray(rfqLastTbeSessions.status, ["생성중", "준비중", "진행중", "검토중", "보류"]) + ) + ) + ) + ); + } + return { success: true, - updatedCount: updates.length, - vendorIds + updatedCount: updatedDetails.length, + vendorIds, + tbeSessionsUpdated: shortListStatus }; } return { success: true, updatedCount: 0, - vendorIds: [] + vendorIds: [], + tbeSessionsUpdated: false }; }); diff --git a/lib/rfq-last/validations.ts b/lib/rfq-last/validations.ts index 5615db7a..6a5816d4 100644 --- a/lib/rfq-last/validations.ts +++ b/lib/rfq-last/validations.ts @@ -56,7 +56,7 @@ import { RfqLastAttachments } from "@/db/schema"; search: parseAsString.withDefault(""), // RFQ 카테고리 (전체/일반견적/ITB/RFQ) - rfqCategory: parseAsStringEnum(["all", "general", "itb", "rfq"]).withDefault("all"), + rfqCategory: parseAsStringEnum(["all", "general", "itb", "rfq"]), }); // ============= 타입 정의 ============= diff --git a/lib/rfq-last/vendor/rfq-vendor-table.tsx b/lib/rfq-last/vendor/rfq-vendor-table.tsx index 89a42602..17433773 100644 --- a/lib/rfq-last/vendor/rfq-vendor-table.tsx +++ b/lib/rfq-last/vendor/rfq-vendor-table.tsx @@ -360,7 +360,7 @@ export function RfqVendorTable({ // 선택된 벤더 ID들 추출 const selectedVendorIds = rfqCode?.startsWith("I") ? selectedRows - .filter(v => v.shortList) + // .filter(v => v.shortList) .map(row => row.vendorId) .filter(id => id != null) : selectedRows @@ -1218,7 +1218,7 @@ export function RfqVendorTable({ }, size: 80, }, - ...(rfqCode?.startsWith("I") ? [{ + ...(!rfqCode?.startsWith("F") ? [{ accessorKey: "shortList", filterFn: createFilterFn("boolean"), // boolean으로 변경 header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Short List" />, @@ -1482,7 +1482,7 @@ export function RfqVendorTable({ label: "스페어파트", type: "boolean" }, - ...(rfqCode?.startsWith("I") ? [{ + ...(!rfqCode?.startsWith("I") ? [{ id: "shortList", label: "Short List", type: "select", @@ -1577,7 +1577,7 @@ export function RfqVendorTable({ </Button> {/* Short List 확정 버튼 */} - {rfqCode?.startsWith("I") && + {!rfqCode?.startsWith("F") && <Button variant="outline" size="sm" diff --git a/lib/sedp/get-form-tags.ts b/lib/sedp/get-form-tags.ts index 310ef486..b81762c6 100644 --- a/lib/sedp/get-form-tags.ts +++ b/lib/sedp/get-form-tags.ts @@ -44,6 +44,96 @@ interface Column { shi?: string | null; } +interface newRegister { + PROJ_NO: string; + MAP_ID: string; + EP_ID: string; + CATEGORY: string; + BYPASS: boolean; + REG_TYPE_ID: string; + TOOL_ID: string; + TOOL_TYPE: string; + SCOPES: string[]; + MAP_CLS: { + TOOL_ATT_NAME: string; + ITEMS: ClassItmes[]; + }; + MAP_ATT: MapAttribute[]; + MAP_TMPLS: string[]; + CRTER_NO: string; + CRTE_DTM: string; + CHGER_NO: string; + _id: string; +} + +interface ClassItmes { + SEDP_OBJ_CLS_ID: string; + TOOL_VALS: string; + ISDEFALUT: boolean; +} + +interface MapAttribute { + SEDP_ATT_ID: string; + TOOL_ATT_NAME: string; + KEY_YN: boolean; + DUE_DATE: string; //"YYYY-MM-DDTHH:mm:ssZ" + INOUT: string | null; +} + + + +async function getNewRegisters(projectCode: string): Promise<newRegister[]> { + try { + // 토큰(API 키) 가져오기 + const apiKey = await getSEDPToken(); + + const SEDP_API_BASE_URL = process.env.SEDP_API_BASE_URL || 'http://sedpwebapi.ship.samsung.co.kr/api'; + + const response = await fetch( + `${SEDP_API_BASE_URL}/AdapterDataMapping/GetByToolID`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'accept': '*/*', + 'ApiKey': apiKey, + 'ProjectNo': projectCode + }, + body: JSON.stringify({ + ProjectNo: projectCode, + "TOOL_ID": "eVCP" + }) + } + ); + + if (!response.ok) { + throw new Error(`새 레지스터 요청 실패: ${response.status} ${response.statusText}`); + } + + // 안전하게 JSON 파싱 + let data; + try { + data = await response.json(); + } catch (parseError) { + console.error(`프로젝트 ${projectCode}의 새 레지스터 응답 파싱 실패:`, parseError); + // 응답 내용 로깅 + const text = await response.clone().text(); + console.log(`응답 내용: ${text.substring(0, 200)}${text.length > 200 ? '...' : ''}`); + throw new Error(`새 레지스터 응답 파싱 실패: ${parseError instanceof Error ? parseError.message : String(parseError)}`); + } + + // 결과를 배열로 변환 (단일 객체인 경우 배열로 래핑) + let registers: newRegister[] = Array.isArray(data) ? data : [data]; + + console.log(`프로젝트 ${projectCode}에서 ${registers.length}개의 새 레지스터를 가져왔습니다.`); + return registers; + } catch (error) { + console.error(`프로젝트 ${projectCode}의 새 레지스터 가져오기 실패:`, error); + throw error; + } +} + + /** * 태그 가져오기 서비스 함수 * contractItemId(packageId)를 기반으로 외부 시스템에서 태그 데이터를 가져와 DB에 저장 @@ -70,6 +160,10 @@ export async function importTagsFromSEDP( // SEDP API에서 태그 데이터 가져오기 const tagData = await fetchTagDataFromSEDP(projectCode, formCode); + const newRegisters = await getNewRegisters(projectCode); + + const registerMatched = newRegisters.find(v => v.REG_TYPE_ID === formCode).MAP_ATT + // 트랜잭션으로 모든 DB 작업 처리 return await db.transaction(async (tx) => { @@ -459,7 +553,7 @@ export async function importTagsFromSEDP( } } - const packageCode = projectType === "ship" ? tagEntry.ATTRIBUTES.find(v=>v.ATT_ID === "CM3003")?.VALUE :tagEntry.ATTRIBUTES.find(v=>v.ATT_ID === "ME5074")?.VALUE + const packageCode = projectType === "ship" ? tagEntry.ATTRIBUTES.find(v => v.ATT_ID === "CM3003")?.VALUE : tagEntry.ATTRIBUTES.find(v => v.ATT_ID === "ME5074")?.VALUE // 기본 태그 데이터 객체 생성 (formEntries용) const tagObject: any = { @@ -470,9 +564,11 @@ export async function importTagsFromSEDP( VNDRCD: vendorRecord[0].vendorCode, VNDRNM_1: vendorRecord[0].vendorName, status: "From S-EDP", // SEDP에서 가져온 데이터임을 표시 - ...(projectType === "ship" ? { CM3003: packageCode } : { ME5074:packageCode }) + ...(projectType === "ship" ? { CM3003: packageCode } : { ME5074: packageCode }) } + let latestDueDate: Date | null = null; + // tags 테이블용 데이터 (UPSERT용) const tagRecord = { contractItemId: packageId, @@ -491,7 +587,7 @@ export async function importTagsFromSEDP( if (Array.isArray(tagEntry.ATTRIBUTES)) { for (const attr of tagEntry.ATTRIBUTES) { const columnInfo = columnsJSON.find(col => col.key === attr.ATT_ID); - if (columnInfo && (columnInfo.shi === "BOTH" ||columnInfo.shi === "OUT" ||columnInfo.shi === null )) { + if (columnInfo && (columnInfo.shi === "BOTH" || columnInfo.shi === "OUT" || columnInfo.shi === null)) { if (columnInfo.type === "NUMBER") { if (attr.VALUE !== undefined && attr.VALUE !== null) { if (typeof attr.VALUE === 'string') { @@ -512,9 +608,46 @@ export async function importTagsFromSEDP( tagObject[attr.ATT_ID] = attr.VALUE; } } + + // registerMatched에서 해당 SEDP_ATT_ID의 DUE_DATE 찾기 + if (registerMatched && Array.isArray(registerMatched)) { + const matchedAttribute = registerMatched.find( + regAttr => regAttr.SEDP_ATT_ID === attr.ATT_ID + ); + + if (matchedAttribute && matchedAttribute.DUE_DATE) { + try { + const dueDate = new Date(matchedAttribute.DUE_DATE); + + // 유효한 날짜인지 확인 + if (!isNaN(dueDate.getTime())) { + // 첫 번째 DUE_DATE이거나 현재까지 찾은 것보다 더 늦은 날짜인 경우 업데이트 + if (!latestDueDate || dueDate > latestDueDate) { + latestDueDate = dueDate; + } + } + } catch (dateError) { + console.warn(`Invalid DUE_DATE format for ${attr.ATT_ID}: ${matchedAttribute.DUE_DATE}`); + } + } + } + } } + if (latestDueDate) { + // ISO 형식의 문자열로 저장 (또는 원하는 형식으로 변경 가능) + tagObject.DUE_DATE = latestDueDate.toISOString(); + + // 또는 YYYY-MM-DD 형식을 원한다면: + // tagObject.DUE_DATE = latestDueDate.toISOString().split('T')[0]; + + // 또는 원본 형식 그대로 유지하려면: + // tagObject.DUE_DATE = latestDueDate.toISOString().replace('Z', ''); + } + + + // 기존 태그가 있는지 확인하고 처리 const existingTag = existingTagMap.get(tagEntry.TAG_IDX); @@ -550,8 +683,14 @@ export async function importTagsFromSEDP( continue; } + if (key === "DUE_DATE" && tagObject[key] !== existingTag.data[key]) { + updates[key] = tagObject[key]; + hasUpdates = true; + continue; + } + const columnInfo = columnsJSON.find(col => col.key === key); - if (columnInfo && (columnInfo.shi === "BOTH" ||columnInfo.shi === "OUT" ||columnInfo.shi === null )) { + if (columnInfo && (columnInfo.shi === "BOTH" || columnInfo.shi === "OUT" || columnInfo.shi === null)) { if (existingTag.data[key] !== tagObject[key]) { updates[key] = tagObject[key]; hasUpdates = true; diff --git a/lib/tbe-last/service.ts b/lib/tbe-last/service.ts index 34c274f5..b69ab71c 100644 --- a/lib/tbe-last/service.ts +++ b/lib/tbe-last/service.ts @@ -49,7 +49,7 @@ export async function getAllTBELast(input: GetTBELastSchema) { } // 최종 WHERE - const finalWhere = and(advancedWhere, globalWhere); + const finalWhere = and(advancedWhere, globalWhere, ne(tbeLastView.status,"생성중")); // 정렬 const orderBy = input.sort?.length diff --git a/lib/vendor-document-list/ship/send-to-shi-button.tsx b/lib/vendor-document-list/ship/send-to-shi-button.tsx index 532aabf5..52874702 100644 --- a/lib/vendor-document-list/ship/send-to-shi-button.tsx +++ b/lib/vendor-document-list/ship/send-to-shi-button.tsx @@ -36,8 +36,8 @@ interface SendToSHIButtonProps { projectType: "ship" | "plant" } -export function SendToSHIButton({ - documents = [], +export function SendToSHIButton({ + documents = [], onSyncComplete, projectType }: SendToSHIButtonProps) { @@ -51,13 +51,13 @@ export function SendToSHIButton({ const { t } = useTranslation(lng, "engineering") const targetSystem = projectType === 'ship' ? "DOLCE" : "SWP" - + // 문서에서 유효한 계약 ID 목록 추출 (projectId 사용) const documentsContractIds = React.useMemo(() => { const validIds = documents .map(doc => (doc as any).projectId) .filter((id): id is number => typeof id === 'number' && id > 0) - + const uniqueIds = [...new Set(validIds)] return uniqueIds.sort() }, [documents]) @@ -66,7 +66,7 @@ export function SendToSHIButton({ // ✅ 클라이언트 전용 Hook 사용 (서버 사이드 렌더링 호환) const { contractStatuses, totalStats, refetchAll } = useClientSyncStatus( - documentsContractIds, + documentsContractIds, targetSystem ) @@ -79,14 +79,14 @@ export function SendToSHIButton({ toast.info(t('shiSync.messages.noContractsToSync')) return } - + setSyncProgress(0) let successfulSyncs = 0 let failedSyncs = 0 let totalSuccessCount = 0 let totalFailureCount = 0 const errors: string[] = [] - + try { // 동기화 가능한 계약들만 필터링 const contractsToSync = contractStatuses.filter(({ syncStatus, error }) => { @@ -112,14 +112,14 @@ export function SendToSHIButton({ for (let i = 0; i < contractsToSync.length; i++) { const { projectId } = contractsToSync[i] setCurrentSyncingContract(projectId) - + try { console.log(`Syncing contract ${projectId}...`) - const result = await triggerSync({ - projectId, - targetSystem + const result = await triggerSync({ + projectId, + targetSystem }) - + if (result?.success) { successfulSyncs++ totalSuccessCount += result.successCount || 0 @@ -143,12 +143,12 @@ export function SendToSHIButton({ } setCurrentSyncingContract(null) - + // 결과 처리 및 토스트 표시 setTimeout(() => { setSyncProgress(0) setIsDialogOpen(false) - + if (failedSyncs === 0) { toast.success( t('shiSync.messages.allSyncCompleted', { successCount: totalSuccessCount }), @@ -161,12 +161,12 @@ export function SendToSHIButton({ ) } else if (successfulSyncs > 0) { toast.warning( - t('shiSync.messages.partialSyncCompleted', { - successfulCount: successfulSyncs, - failedCount: failedSyncs + t('shiSync.messages.partialSyncCompleted', { + successfulCount: successfulSyncs, + failedCount: failedSyncs }), { - description: errors.slice(0, 3).join(', ') + + description: errors.slice(0, 3).join(', ') + (errors.length > 3 ? t('shiSync.messages.andMore') : '') } ) @@ -178,16 +178,16 @@ export function SendToSHIButton({ } ) } - + // 모든 contract 상태 갱신 refetchAll() onSyncComplete?.() }, 500) - + } catch (error) { setSyncProgress(0) setCurrentSyncingContract(null) - + const errorMessage = syncUtils.formatError(error as Error) toast.error(t('shiSync.messages.syncFailed'), { description: errorMessage @@ -259,8 +259,8 @@ export function SendToSHIButton({ )} <span className="hidden sm:inline">{t('shiSync.buttons.sendToSHI')}</span> {totalStats.totalPending > 0 && ( - <Badge - variant="destructive" + <Badge + variant="destructive" className="h-5 w-5 p-0 text-xs flex items-center justify-center ml-1" > {totalStats.totalPending} @@ -269,7 +269,7 @@ export function SendToSHIButton({ </Button> </div> </PopoverTrigger> - + <PopoverContent className="w-96" align="end"> <div className="space-y-4"> <div className="space-y-2"> @@ -289,16 +289,16 @@ export function SendToSHIButton({ )} </Button> </div> - + <div className="flex items-center justify-between"> <span className="text-sm text-muted-foreground">{t('shiSync.labels.overallStatus')}</span> {getSyncStatusBadge()} </div> - + <div className="text-xs text-muted-foreground"> - {t('shiSync.descriptions.targetInfo', { - contractCount: documentsContractIds.length, - targetSystem + {t('shiSync.descriptions.targetInfo', { + contractCount: documentsContractIds.length, + targetSystem })} </div> </div> @@ -311,8 +311,8 @@ export function SendToSHIButton({ {t('shiSync.descriptions.statusCheckError')} {process.env.NODE_ENV === 'development' && ( <div className="text-xs mt-1 font-mono"> - Debug: {t('shiSync.descriptions.contractsWithError', { - count: contractStatuses.filter(({ error }) => error).length + Debug: {t('shiSync.descriptions.contractsWithError', { + count: contractStatuses.filter(({ error }) => error).length })} </div> )} @@ -324,7 +324,7 @@ export function SendToSHIButton({ {!totalStats.hasError && documentsContractIds.length > 0 && ( <div className="space-y-3"> <Separator /> - + <div className="grid grid-cols-3 gap-4 text-sm"> <div className="text-center"> <div className="text-muted-foreground">{t('shiSync.labels.pending')}</div> @@ -409,7 +409,7 @@ export function SendToSHIButton({ </> )} </Button> - + <Button variant="outline" size="sm" @@ -451,12 +451,12 @@ export function SendToSHIButton({ <span>{t('shiSync.labels.syncTarget')}</span> <span className="font-medium">{t('shiSync.labels.itemCount', { count: totalStats.totalPending })}</span> </div> - + <div className="flex items-center justify-between text-sm"> <span>{t('shiSync.labels.targetContracts')}</span> <span className="font-medium">{t('shiSync.labels.contractCount', { count: documentsContractIds.length })}</span> </div> - + <div className="text-xs text-muted-foreground"> {t('shiSync.descriptions.includesChanges')} </div> diff --git a/lib/vendors/table/request-pq-dialog.tsx b/lib/vendors/table/request-pq-dialog.tsx index 206846df..fd6da145 100644 --- a/lib/vendors/table/request-pq-dialog.tsx +++ b/lib/vendors/table/request-pq-dialog.tsx @@ -709,9 +709,22 @@ export function RequestPQDialog({ vendors, showTrigger = true, onSuccess, ...pro date={dueDate ? new Date(dueDate) : undefined}
onSelect={(date?: Date) => {
if (date) {
+ // 현재 날짜 기준으로 이전 날짜는 선택 불가능
+ const today = new Date()
+ today.setHours(0, 0, 0, 0) // 오늘 날짜의 시작 시간으로 설정
+
+ const selectedDate = new Date(date)
+ selectedDate.setHours(0, 0, 0, 0) // 선택된 날짜의 시작 시간으로 설정
+
+ if (selectedDate < today) {
+ toast.error("마감일은 오늘 날짜 이후로 선택해주세요.")
+ return
+ } else {
+
// 한국 시간대로 날짜 변환 (UTC 변환으로 인한 날짜 변경 방지)
const kstDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
setDueDate(kstDate.toISOString().slice(0, 10))
+ }
} else {
setDueDate("")
}
|
