91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
// File: lib/services/project.service.ts
|
|
import apiClient from "@/lib/api/client";
|
|
import {
|
|
CreateProjectDto,
|
|
UpdateProjectDto,
|
|
SearchProjectDto
|
|
} from "@/types/dto/project/project.dto";
|
|
|
|
export interface ProjectListItem {
|
|
uuid: string;
|
|
id?: number;
|
|
projectCode: string;
|
|
projectName: string;
|
|
isActive: boolean;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
type ApiEnvelope<T> = {
|
|
data?: ApiEnvelope<T> | T;
|
|
message?: string;
|
|
statusCode?: number;
|
|
};
|
|
|
|
function unwrapApiData<T>(payload: ApiEnvelope<T> | T): ApiEnvelope<T> | T | null {
|
|
let current: ApiEnvelope<T> | T | null = payload;
|
|
|
|
while (
|
|
current &&
|
|
typeof current === "object" &&
|
|
"data" in current &&
|
|
current.data !== undefined
|
|
) {
|
|
current = current.data;
|
|
}
|
|
|
|
return current;
|
|
}
|
|
|
|
function unwrapArrayResponse<T>(payload: ApiEnvelope<T[]> | T[]): T[] {
|
|
const unwrapped = unwrapApiData(payload);
|
|
return Array.isArray(unwrapped) ? unwrapped : [];
|
|
}
|
|
|
|
export const projectService = {
|
|
// --- Basic CRUD ---
|
|
|
|
/**
|
|
* ดึงรายการโครงการทั้งหมด (รองรับ Search & Pagination)
|
|
* (เดิมคือ getAllProjects แต่ปรับให้รับ params ได้)
|
|
*/
|
|
getAll: async (params?: SearchProjectDto): Promise<ProjectListItem[]> => {
|
|
// GET /projects
|
|
const response = await apiClient.get<
|
|
ApiEnvelope<ProjectListItem[]> | ProjectListItem[]
|
|
>("/projects", { params });
|
|
return unwrapArrayResponse(response.data);
|
|
},
|
|
|
|
/** ดึงรายละเอียดโครงการตาม UUID */
|
|
getByUuid: async (uuid: string) => {
|
|
const response = await apiClient.get(`/projects/${uuid}`);
|
|
return response.data;
|
|
},
|
|
|
|
/** สร้างโครงการใหม่ (Admin) */
|
|
create: async (data: CreateProjectDto) => {
|
|
const response = await apiClient.post("/projects", data);
|
|
return response.data;
|
|
},
|
|
|
|
/** แก้ไขโครงการ */
|
|
update: async (uuid: string, data: UpdateProjectDto) => {
|
|
const response = await apiClient.put(`/projects/${uuid}`, data);
|
|
return response.data;
|
|
},
|
|
|
|
/** ลบโครงการ (Soft Delete) */
|
|
delete: async (uuid: string) => {
|
|
const response = await apiClient.delete(`/projects/${uuid}`);
|
|
return response.data;
|
|
},
|
|
|
|
// --- Related Data / Dropdown Helpers ---
|
|
|
|
// --- Related Data / Dropdown Helpers ---
|
|
// Organizations and Contracts should now be fetched via their respective services
|
|
// organizationService.getAll({ projectId })
|
|
// contractService.getAll({ projectId })
|
|
};
|