From 7daaad73afa69d902e9a91dd8eabb7512de05a9d Mon Sep 17 00:00:00 2001 From: puriphatt Date: Thu, 6 Jun 2024 09:52:15 +0000 Subject: [PATCH] feat: branch attachment --- src/stores/customer/index.ts | 70 +++++++++++++++++++++++++++++++++++- src/stores/customer/types.ts | 9 +++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/src/stores/customer/index.ts b/src/stores/customer/index.ts index 4d619b60..9103dca7 100644 --- a/src/stores/customer/index.ts +++ b/src/stores/customer/index.ts @@ -2,7 +2,13 @@ import { ref } from 'vue'; import { defineStore } from 'pinia'; import { Pagination } from '../types'; import { api } from 'src/boot/axios'; -import { Customer, CustomerCreate, CustomerUpdate } from './types'; +import { + Customer, + CustomerCreate, + CustomerUpdate, + BranchAttachmentCreate, + BranchAttachment, +} from './types'; import axios from 'axios'; const useCustomerStore = defineStore('api-customer', () => { @@ -134,6 +140,68 @@ const useCustomerStore = defineStore('api-customer', () => { return false; } + async function addBranchAttachment( + branchId: string, + payload: BranchAttachmentCreate, + flow?: { + sessionId: string; + refTransactionId: string; + transactionId: string; + }, + ) { + const list: { name: string; file: File }[] = []; + + payload.file.forEach((v) => { + let filename = v.name; + + if (list.some((v) => v.name === filename)) { + const dotIndex = filename.lastIndexOf('.'); + const originalName = + dotIndex !== -1 && !filename.startsWith('.') + ? filename.slice(0, dotIndex) + : filename; + const extension = + dotIndex !== -1 && !filename.startsWith('.') + ? filename.slice(dotIndex) + : ''; + + let i = 0; + + while (list.some((v) => v.name === filename)) { + filename = `${originalName} (${++i})`; + if (dotIndex !== -1) filename += extension; + } + } + + list.push({ name: filename, file: v }); + }); + + const res = await api.post<(BranchAttachment & { uploadUrl: string })[]>( + `/customer-branch/${branchId}/attachment`, + { file: list.map((v) => v.name) }, + { + headers: { + 'X-Session-Id': flow?.sessionId, + 'X-Rtid': flow?.refTransactionId, + 'X-Tid': flow?.transactionId, + }, + }, + ); + + await Promise.all( + res.data.map(async (a) => { + const found = list.find((b) => b.name === a.name)!; + + await axios + .put(a.uploadUrl, found.file, { + headers: { 'Content-Type': found.file.type }, + onUploadProgress: (e) => console.log(e), + }) + .catch((e) => console.error(e)); + }), + ); + } + return { data, diff --git a/src/stores/customer/types.ts b/src/stores/customer/types.ts index 28442f5e..cd967a5b 100644 --- a/src/stores/customer/types.ts +++ b/src/stores/customer/types.ts @@ -89,3 +89,12 @@ export type CustomerUpdate = { customerBranch?: CustomerBranchUpdate[]; image?: File; }; + +export type BranchAttachmentCreate = { + file: File[]; +}; + +export type BranchAttachment = { + name: string; + url: string; +};