refactor: api store

This commit is contained in:
Methapon Metanipat 2024-09-17 11:41:09 +07:00
parent 6f54693eb1
commit 66b167dea5
2 changed files with 169 additions and 264 deletions

View file

@ -6,22 +6,27 @@ import {
Customer, Customer,
CustomerCreate, CustomerCreate,
CustomerUpdate, CustomerUpdate,
BranchAttachmentCreate,
BranchAttachment,
CustomerStats, CustomerStats,
CustomerBranch, CustomerBranch,
CustomerBranchCreate, CustomerBranchCreate,
CustomerType, CustomerType,
} from './types'; } from './types';
import axios from 'axios';
import useFlowStore from '../flow'; import useFlowStore from '../flow';
import { Employee } from '../employee/types'; import { Employee } from '../employee/types';
import { baseUrl } from '../utils'; import { baseUrl, manageFile } from '../utils';
const useCustomerStore = defineStore('api-customer', () => { const useCustomerStore = defineStore('api-customer', () => {
const flowStore = useFlowStore(); const flowStore = useFlowStore();
const data = ref<Pagination<Customer[]>>(); const data = ref<Pagination<Customer[]>>();
const fileManager = manageFile<
| 'citizen'
| 'house-registration'
| 'commercial-registration'
| 'vat-registration'
| 'power-of-attorney'
>(api, 'customer-branch');
async function setImage(id: string, image: File) { async function setImage(id: string, image: File) {
await api.put(`/customer/${id}/image`, image, { await api.put(`/customer/${id}/image`, image, {
headers: { 'Content-Type': image?.type }, headers: { 'Content-Type': image?.type },
@ -29,27 +34,12 @@ const useCustomerStore = defineStore('api-customer', () => {
}); });
} }
async function fetchById( async function fetchById(customerId: string) {
customerId: string,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.get< const res = await api.get<
Customer & { branch: CustomerBranch[]; registeredBranchId: string } Customer & { branch: CustomerBranch[]; registeredBranchId: string }
>(`/customer/${customerId}`, { >(`/customer/${customerId}`);
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (res && res.status === 200) { if (res && res.status === 200) return res.data;
return res.data;
}
return false; return false;
} }
@ -62,11 +52,6 @@ const useCustomerStore = defineStore('api-customer', () => {
page?: number; page?: number;
pageSize?: number; pageSize?: number;
}, },
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) { ) {
const params = new URLSearchParams(); const params = new URLSearchParams();
for (const [k, v] of Object.entries(opts || {})) { for (const [k, v] of Object.entries(opts || {})) {
@ -77,13 +62,6 @@ const useCustomerStore = defineStore('api-customer', () => {
const res = await api.get<Pagination<Employee[]>>( const res = await api.get<Pagination<Employee[]>>(
`/customer-branch/${idBranch}/employee${(params && '?'.concat(query)) || ''}`, `/customer-branch/${idBranch}/employee${(params && '?'.concat(query)) || ''}`,
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
); );
if (res.status === 200) { if (res.status === 200) {
@ -107,14 +85,7 @@ const useCustomerStore = defineStore('api-customer', () => {
? { customer: Customer } ? { customer: Customer }
: unknown))[] : unknown))[]
>, >,
>( >(opts?: Options): Promise<Data | false> {
opts?: Options,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
): Promise<Data | false> {
const params = new URLSearchParams(); const params = new URLSearchParams();
for (const [k, v] of Object.entries(opts || {})) { for (const [k, v] of Object.entries(opts || {})) {
@ -125,13 +96,6 @@ const useCustomerStore = defineStore('api-customer', () => {
const res = await api.get<Data>( const res = await api.get<Data>(
`/customer-branch${(params && '?'.concat(query)) || ''}`, `/customer-branch${(params && '?'.concat(query)) || ''}`,
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
); );
if (!res) return false; if (!res) return false;
@ -157,14 +121,7 @@ const useCustomerStore = defineStore('api-customer', () => {
? { branch: CustomerBranch[] } ? { branch: CustomerBranch[] }
: unknown))[] : unknown))[]
>, >,
>( >(opts?: Options): Promise<Data | false> {
opts?: Options,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
): Promise<Data | false> {
const params = new URLSearchParams(); const params = new URLSearchParams();
for (const [k, v] of Object.entries(opts || {})) { for (const [k, v] of Object.entries(opts || {})) {
@ -175,13 +132,6 @@ const useCustomerStore = defineStore('api-customer', () => {
const res = await api.get<Data>( const res = await api.get<Data>(
`/customer${(params && '?'.concat(query)) || ''}`, `/customer${(params && '?'.concat(query)) || ''}`,
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
); );
if (!res) return false; if (!res) return false;
@ -192,18 +142,8 @@ const useCustomerStore = defineStore('api-customer', () => {
return false; return false;
} }
async function getStatsCustomer(flow?: { async function getStatsCustomer() {
sessionId?: string; const res = await api.get<CustomerStats>('/customer/type-stats');
refTransactionId?: string;
transactionId?: string;
}) {
const res = await api.get<CustomerStats>('/customer/type-stats', {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
@ -219,7 +159,7 @@ const useCustomerStore = defineStore('api-customer', () => {
`/customer-branch/${opts.branchId}/attachment/${opts.filename || opts.file.name}`, `/customer-branch/${opts.branchId}/attachment/${opts.filename || opts.file.name}`,
opts.file, opts.file,
{ {
headers: { 'X-Rtid': flowStore.rtid, 'Content-Type': opts.file.type }, headers: { 'Content-Type': opts.file.type },
onUploadProgress: (e) => console.log(e), onUploadProgress: (e) => console.log(e),
}, },
); );
@ -239,15 +179,12 @@ const useCustomerStore = defineStore('api-customer', () => {
} }
async function listAttachment(id: string) { async function listAttachment(id: string) {
const res = await api.get<string[]>(`/customer-branch/${id}/attachment`, { const res = await api.get<string[]>(`/customer-branch/${id}/attachment`);
headers: { 'X-Rtid': flowStore.rtid },
});
if (res.status >= 400) return false; if (res.status >= 400) return false;
return res.data; return res.data;
} }
async function getAttachment(id: string, filename: string, download = false) { async function getAttachment(id: string, filename: string, download = false) {
const url = `${baseUrl}/customer-branch/${id}/attachment/${filename}`; const url = `${baseUrl}/customer-branch/${id}/attachment/${filename}`;
const res = await api.get<string>(url); const res = await api.get<string>(url);
@ -267,21 +204,8 @@ const useCustomerStore = defineStore('api-customer', () => {
return res.data; return res.data;
} }
async function fetchImageListById( async function fetchImageListById(id: string) {
id: string, const res = await api.get(`/customer/${id}/image`);
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.get(`/customer/${id}/image`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
if (res.status === 200) return res.data; if (res.status === 200) return res.data;
@ -301,22 +225,8 @@ const useCustomerStore = defineStore('api-customer', () => {
return name; return name;
} }
async function deleteImageByName( async function deleteImageByName(id: string, name: string) {
id: string, const res = await api.delete(`/customer/${id}/image/${name}`);
name: string,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.delete(`/customer/${id}/image/${name}`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
} }
@ -327,11 +237,6 @@ const useCustomerStore = defineStore('api-customer', () => {
selectedImage: string; selectedImage: string;
list: { url: string; imgFile: File | null; name: string }[]; list: { url: string; imgFile: File | null; name: string }[];
}, },
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) { ) {
if (data.customerBranch) { if (data.customerBranch) {
if (data.customerBranch[0].citizenId) { if (data.customerBranch[0].citizenId) {
@ -357,28 +262,18 @@ const useCustomerStore = defineStore('api-customer', () => {
imageUrl: string; imageUrl: string;
imageUploadUrl: string; imageUploadUrl: string;
} }
>( >('/customer', {
'/customer', ...payload,
{ branch: data.customerBranch?.map((v) => ({
...payload, ...v,
branch: data.customerBranch?.map((v) => ({ file: undefined,
...v, branchCode: undefined,
file: undefined, id: undefined,
branchCode: undefined, customerId: undefined,
id: undefined, codeCustomer: undefined,
customerId: undefined, })),
codeCustomer: undefined, selectedImage: imgList.selectedImage,
})), });
selectedImage: imgList.selectedImage,
},
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
);
if (imgList.list.length > 0 && res.data.id) { if (imgList.list.length > 0 && res.data.id) {
for (let index = 0; index < imgList.list.length; index++) { for (let index = 0; index < imgList.list.length; index++) {
@ -393,15 +288,7 @@ const useCustomerStore = defineStore('api-customer', () => {
return res.data; return res.data;
} }
async function editById( async function editById(id: string, data: Partial<CustomerUpdate>) {
id: string,
data: Partial<CustomerUpdate>,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const { customerBranch, image, ...payload } = data; const { customerBranch, image, ...payload } = data;
const res = await api.put< const res = await api.put<
@ -410,53 +297,30 @@ const useCustomerStore = defineStore('api-customer', () => {
imageUrl: string; imageUrl: string;
imageUploadUrl: string; imageUploadUrl: string;
} }
>( >(`/customer/${id}`, {
`/customer/${id}`, ...payload,
{ branch: data.customerBranch?.map((v) => ({
...payload, ...v,
branch: data.customerBranch?.map((v) => ({ file: undefined,
...v, branchCode: undefined,
file: undefined, id: undefined,
branchCode: undefined, customerId: undefined,
id: undefined, codeCustomer: undefined,
customerId: undefined, createAt: undefined,
codeCustomer: undefined, createdByUserId: undefined,
createAt: undefined, statusOrder: undefined,
createdByUserId: undefined, updatedAt: undefined,
statusOrder: undefined, updatedByUserId: undefined,
updatedAt: undefined, })),
updatedByUserId: undefined, });
})),
},
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
);
if (!res) return false; if (!res) return false;
return res.data; return res.data;
} }
async function deleteById( async function deleteById(id: string) {
id: string, const res = await api.delete<Customer>(`/customer/${id}`);
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.delete<Customer>(`/customer/${id}`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
if (res.status === 200) return res.data; if (res.status === 200) return res.data;
@ -464,21 +328,8 @@ const useCustomerStore = defineStore('api-customer', () => {
return false; return false;
} }
async function getBranchById( async function getBranchById(id: string) {
id: string, const res = await api.get<CustomerBranch>(`/customer-branch/${id}`);
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.get<CustomerBranch>(`/customer-branch/${id}`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
return res.data; return res.data;
@ -490,11 +341,6 @@ const useCustomerStore = defineStore('api-customer', () => {
customerId: string; customerId: string;
codeCustomer: string; codeCustomer: string;
}, },
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) { ) {
const { codeCustomer, statusSave, code, file, birthDate, ...payload } = const { codeCustomer, statusSave, code, file, birthDate, ...payload } =
data; data;
@ -516,17 +362,9 @@ const useCustomerStore = defineStore('api-customer', () => {
delete data['birthDate']; delete data['birthDate'];
} }
const res = await api.post<CustomerBranch>('/customer-branch', payload, { const res = await api.post<CustomerBranch>('/customer-branch', payload);
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
// if (file) await addBranchAttachment(res.data.id, { file });
return res.data; return res.data;
} }
@ -539,11 +377,6 @@ const useCustomerStore = defineStore('api-customer', () => {
codeCustomer: string; codeCustomer: string;
} }
>, >,
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) { ) {
if (data.citizenId) { if (data.citizenId) {
delete data['authorizedNameEN']; delete data['authorizedNameEN'];
@ -573,8 +406,6 @@ const useCustomerStore = defineStore('api-customer', () => {
...payload ...payload
} = data; } = data;
console.log(payload);
if (!!payload.citizenId) { if (!!payload.citizenId) {
delete payload['registerDate']; delete payload['registerDate'];
delete payload['registerName']; delete payload['registerName'];
@ -588,37 +419,15 @@ const useCustomerStore = defineStore('api-customer', () => {
const res = await api.put<CustomerBranch>( const res = await api.put<CustomerBranch>(
`/customer-branch/${id}`, `/customer-branch/${id}`,
payload, payload,
{
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
},
); );
// if (file) await addBranchAttachment(id, { file });
if (!res) return false; if (!res) return false;
return res.data; return res.data;
} }
async function deleteBranchById( async function deleteBranchById(id: string) {
id: string, const res = await api.delete<Customer>(`/customer-branch/${id}`);
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.delete<Customer>(`/customer-branch/${id}`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (!res) return false; if (!res) return false;
if (res.status === 200) return res.data; if (res.status === 200) return res.data;
@ -626,21 +435,8 @@ const useCustomerStore = defineStore('api-customer', () => {
return false; return false;
} }
async function fetchListCustomeBranchById( async function fetchListCustomeBranchById(branchId: string) {
branchId: string, const res = await api.get(`/customer-branch/${branchId}`);
flow?: {
sessionId?: string;
refTransactionId?: string;
transactionId?: string;
},
) {
const res = await api.get(`/customer-branch/${branchId}`, {
headers: {
'X-Session-Id': flow?.sessionId,
'X-Rtid': flow?.refTransactionId || flowStore.rtid,
'X-Tid': flow?.transactionId,
},
});
if (res && res.status === 200) { if (res && res.status === 200) {
return res.data; return res.data;
@ -678,6 +474,8 @@ const useCustomerStore = defineStore('api-customer', () => {
getAttachment, getAttachment,
putAttachment, putAttachment,
deleteAttachment, deleteAttachment,
...fileManager,
}; };
}); });

View file

@ -4,6 +4,7 @@ import { ComposerTranslation, useI18n } from 'vue-i18n';
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { Ref, ref } from 'vue'; import { Ref, ref } from 'vue';
import { getRole } from 'src/services/keycloak'; import { getRole } from 'src/services/keycloak';
import { AxiosInstance } from 'axios';
export const baseUrl = import.meta.env.VITE_API_BASE_URL; export const baseUrl = import.meta.env.VITE_API_BASE_URL;
@ -234,4 +235,110 @@ export function resetScrollBar(elementId: string) {
} }
} }
export function manageAttachment(api: AxiosInstance, base: string) {
return {
listAttachment: async () => {
const res = await api.get<string[]>(`${base}/attachment`);
if (res.status >= 400) return false;
return res.data;
},
getAttachment: async (opts: {
parentId: string;
name: string;
download?: boolean;
}) => {
const url = `/${opts.parentId}/attachment/${opts.name}`;
const res = await api.get<string>(url);
if (opts.download) {
fetch(res.data)
.then(async (res) => await res.blob())
.then((blob) => {
const a = document.createElement('a');
a.download = opts.name;
a.href = window.URL.createObjectURL(blob);
a.click();
a.remove();
});
}
return res.data;
},
putAttachment: async (opts: {
parentId: string;
name: string;
file: File;
}) => {
const res = await api.put(
`/${opts.parentId}/attachment/${opts.name}`,
opts.file,
{
headers: { 'Content-Type': opts.file.type },
onUploadProgress: (e) => console.log(e),
},
);
if (res.status < 400) return true;
return false;
},
delAttachment: async (opts: { parentId: string; name: string }) => {
const res = await api.delete(`/${opts.parentId}/attachment/${opts.name}`);
if (res.status < 400) return true;
return false;
},
};
}
export function manageFile<T extends string>(api: AxiosInstance, base: string) {
return {
listFile: async (opts: { group: T }) => {
const res = await api.get<string[]>(`${base}/file-${opts.group}`);
if (res.status >= 400) return false;
return res.data;
},
getFile: async (opts: {
group: T;
parentId: string;
fileId: string;
download?: boolean;
}) => {
const url = `/${opts.parentId}/file-${opts.group}/${opts.fileId}`;
const res = await api.get<string>(url);
if (opts.download) {
fetch(res.data)
.then(async (res) => await res.blob())
.then((blob) => {
const a = document.createElement('a');
a.download = opts.fileId;
a.href = window.URL.createObjectURL(blob);
a.click();
a.remove();
});
}
return res.data;
},
putFile: async (opts: {
group: T;
parentId: string;
fileId: string;
file: File;
}) => {
const res = await api.put(
`/${opts.parentId}/file-${opts.group}/${opts.fileId}`,
opts.file,
{
headers: { 'Content-Type': opts.file.type },
onUploadProgress: (e) => console.log(e),
},
);
if (res.status < 400) return true;
return false;
},
delFile: async (opts: { group: T; parentId: string; fileId: string }) => {
const res = await api.delete(
`/${opts.parentId}/file-${opts.group}/${opts.fileId}`,
);
if (res.status < 400) return true;
return false;
},
};
}
export default useUtilsStore; export default useUtilsStore;