pl-vehicle-cert-zip.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import JSZip from 'jszip'
  2. import type { CertRead } from '@/api/pl'
  3. import { formatPlVehiclePlateDisplay } from '@/utils/pl-display'
  4. import {
  5. PL_VEHICLE_CERT_PART_TRAILER,
  6. normalizeVehicleCertPart
  7. } from '@/utils/pl-vehicle-cert'
  8. export type VehicleCertZipSource = {
  9. id: string
  10. licensePlate?: string | null
  11. trailerNo?: string | null
  12. certList?: CertRead[] | null
  13. }
  14. export type VehicleCertZipFile = {
  15. fileUrl: string
  16. baseName: string
  17. ext: string
  18. }
  19. export type VehicleCertZipEntry = {
  20. vehicleId: string
  21. plateFolder: string
  22. files: VehicleCertZipFile[]
  23. }
  24. export function sanitizeZipPathSegment(raw: string): string {
  25. return String(raw || '')
  26. .trim()
  27. .replace(/[\\/:*?"<>|]+/g, '_')
  28. .replace(/\s+/g, ' ')
  29. .trim() || '未命名'
  30. }
  31. /** Mirrors `normalizeAttachmentUrls` in download-attachment.ts (inlined for node:test). */
  32. function normalizeAttachmentUrls(raw?: string | null): string {
  33. if (!raw) return ''
  34. const trimmed = String(raw).trim()
  35. if (!trimmed) return ''
  36. if (trimmed.startsWith('[')) {
  37. try {
  38. const parsed = JSON.parse(trimmed)
  39. if (Array.isArray(parsed)) {
  40. return parsed.map((url) => String(url).trim()).filter(Boolean).join(',')
  41. }
  42. } catch {
  43. /* ignore */
  44. }
  45. }
  46. return trimmed
  47. }
  48. function parseUrls(raw?: string | null): string[] {
  49. const normalized = normalizeAttachmentUrls(raw)
  50. if (!normalized) return []
  51. return normalized
  52. .split(',')
  53. .map((item) => item.trim())
  54. .filter(Boolean)
  55. }
  56. function getFileExt(url: string): string {
  57. const name =
  58. String(url || '')
  59. .split('?')[0]
  60. .split('/')
  61. .pop() || ''
  62. const lastDot = name.lastIndexOf('.')
  63. if (lastDot === -1) return ''
  64. return name.slice(lastDot + 1).toLowerCase()
  65. }
  66. function partPrefix(cert: CertRead, enablePart: boolean): string {
  67. if (!enablePart) return ''
  68. return normalizeVehicleCertPart(cert.vehiclePart) === PL_VEHICLE_CERT_PART_TRAILER
  69. ? '挂·'
  70. : '主·'
  71. }
  72. export function collectVehicleCertZipEntries(
  73. vehicles: VehicleCertZipSource[]
  74. ): VehicleCertZipEntry[] {
  75. const result: VehicleCertZipEntry[] = []
  76. for (const vehicle of vehicles) {
  77. const certs = vehicle.certList || []
  78. const enablePart = certs.some(
  79. (cert) => normalizeVehicleCertPart(cert.vehiclePart) === PL_VEHICLE_CERT_PART_TRAILER
  80. )
  81. const files: VehicleCertZipFile[] = []
  82. certs.forEach((cert) => {
  83. const certName = String(cert.certName || '').trim() || '证书'
  84. const prefix = partPrefix(cert, enablePart)
  85. const baseName = `${prefix}${certName}`
  86. parseUrls(cert.attachmentUrls).forEach((fileUrl) => {
  87. files.push({
  88. fileUrl,
  89. baseName,
  90. ext: getFileExt(fileUrl)
  91. })
  92. })
  93. })
  94. if (!files.length) continue
  95. const plateRaw = formatPlVehiclePlateDisplay(vehicle.licensePlate, vehicle.trailerNo)
  96. result.push({
  97. vehicleId: vehicle.id,
  98. plateFolder: sanitizeZipPathSegment(plateRaw === '—' ? vehicle.id : plateRaw),
  99. files
  100. })
  101. }
  102. return result
  103. }
  104. export function buildVehicleCertZipFilename(
  105. entries: Array<{ plateFolder: string }>,
  106. yyyymmdd: string
  107. ): string {
  108. if (entries.length === 1) {
  109. return `车辆证书_${entries[0].plateFolder}.zip`
  110. }
  111. return `车辆证书批量_${entries.length}辆_${yyyymmdd}.zip`
  112. }
  113. export function uniqueZipPath(used: Set<string>, relativePath: string): string {
  114. if (!used.has(relativePath)) {
  115. used.add(relativePath)
  116. return relativePath
  117. }
  118. const lastSlash = relativePath.lastIndexOf('/')
  119. const dir = lastSlash >= 0 ? relativePath.slice(0, lastSlash + 1) : ''
  120. const name = lastSlash >= 0 ? relativePath.slice(lastSlash + 1) : relativePath
  121. const lastDot = name.lastIndexOf('.')
  122. const stem = lastDot > 0 ? name.slice(0, lastDot) : name
  123. const ext = lastDot > 0 ? name.slice(lastDot) : ''
  124. let i = 2
  125. let candidate = `${dir}${stem}_${i}${ext}`
  126. while (used.has(candidate)) {
  127. i += 1
  128. candidate = `${dir}${stem}_${i}${ext}`
  129. }
  130. used.add(candidate)
  131. return candidate
  132. }
  133. export type BuildVehicleCertZipOptions = {
  134. yyyymmdd?: string
  135. concurrency?: number
  136. fetchBlob?: (fileUrl: string, fileName: string) => Promise<Blob>
  137. saveAs?: (blob: Blob, filename: string) => void | Promise<void>
  138. onFileAdded?: (zipPath: string) => void
  139. }
  140. export type BuildVehicleCertZipResult = {
  141. okCount: number
  142. failCount: number
  143. zipName: string
  144. }
  145. export type BuildCertZipOptions = BuildVehicleCertZipOptions
  146. export type BuildCertZipResult = BuildVehicleCertZipResult
  147. function todayYyyymmdd(): string {
  148. const d = new Date()
  149. const y = d.getFullYear()
  150. const m = String(d.getMonth() + 1).padStart(2, '0')
  151. const day = String(d.getDate()).padStart(2, '0')
  152. return `${y}${m}${day}`
  153. }
  154. async function mapPool<T, R>(
  155. items: T[],
  156. concurrency: number,
  157. worker: (item: T) => Promise<R>
  158. ): Promise<R[]> {
  159. const results: R[] = new Array(items.length)
  160. let next = 0
  161. const runners = Array.from({ length: Math.min(concurrency, items.length) || 0 }, async () => {
  162. while (next < items.length) {
  163. const idx = next
  164. next += 1
  165. results[idx] = await worker(items[idx])
  166. }
  167. })
  168. await Promise.all(runners)
  169. return results
  170. }
  171. async function defaultFetchBlob(fileUrl: string, fileName: string): Promise<Blob> {
  172. const [{ fetchAttachmentBlob }, { resolvePhotoDisplayUrl }] = await Promise.all([
  173. import('@/utils/download-attachment'),
  174. import('@/utils/pl-photo')
  175. ])
  176. return fetchAttachmentBlob({ fileUrl, fileName }, { fullFileUrl: resolvePhotoDisplayUrl })
  177. }
  178. async function defaultSaveAs(blob: Blob, filename: string): Promise<void> {
  179. const { default: FileSaver } = await import('file-saver')
  180. FileSaver.saveAs(blob, filename)
  181. }
  182. export async function packAndSaveCertZip(
  183. entries: Array<{ folderLabel: string; files: VehicleCertZipFile[] }>,
  184. zipName: string,
  185. options: BuildCertZipOptions = {}
  186. ): Promise<BuildCertZipResult> {
  187. if (!entries.length) {
  188. return { okCount: 0, failCount: 0, zipName: '' }
  189. }
  190. const multi = entries.length > 1
  191. const concurrency = options.concurrency ?? 4
  192. const used = new Set<string>()
  193. const jobs: Array<{ zipPath: string; fileUrl: string; fileName: string }> = []
  194. for (const entry of entries) {
  195. for (const file of entry.files) {
  196. const leaf = `${file.baseName}${file.ext ? `.${file.ext}` : ''}`
  197. const rawPath = multi ? `${entry.folderLabel}/${leaf}` : leaf
  198. const zipPath = uniqueZipPath(used, rawPath)
  199. jobs.push({ zipPath, fileUrl: file.fileUrl, fileName: leaf })
  200. }
  201. }
  202. const fetchBlob = options.fetchBlob ?? defaultFetchBlob
  203. const zip = new JSZip()
  204. let okCount = 0
  205. let failCount = 0
  206. await mapPool(jobs, concurrency, async (job) => {
  207. try {
  208. const blob = await fetchBlob(job.fileUrl, job.fileName)
  209. const data = await blob.arrayBuffer()
  210. zip.file(job.zipPath, data)
  211. options.onFileAdded?.(job.zipPath)
  212. okCount += 1
  213. } catch {
  214. failCount += 1
  215. }
  216. })
  217. if (okCount === 0) {
  218. return { okCount: 0, failCount, zipName: '' }
  219. }
  220. const out = await zip.generateAsync({ type: 'blob' })
  221. const save = options.saveAs ?? defaultSaveAs
  222. await save(out, zipName)
  223. return { okCount, failCount, zipName }
  224. }
  225. export async function buildAndSaveVehicleCertZip(
  226. vehicles: VehicleCertZipSource[],
  227. options: BuildVehicleCertZipOptions = {}
  228. ): Promise<BuildVehicleCertZipResult> {
  229. const collected = collectVehicleCertZipEntries(vehicles)
  230. if (!collected.length) {
  231. return { okCount: 0, failCount: 0, zipName: '' }
  232. }
  233. const yyyymmdd = options.yyyymmdd || todayYyyymmdd()
  234. const zipName = buildVehicleCertZipFilename(collected, yyyymmdd)
  235. return packAndSaveCertZip(
  236. collected.map((e) => ({ folderLabel: e.plateFolder, files: e.files })),
  237. zipName,
  238. options
  239. )
  240. }
  241. export type PersonnelCertZipSource = {
  242. id: string
  243. personnelName?: string | null
  244. certList?: CertRead[] | null
  245. }
  246. export type PersonnelCertZipEntry = {
  247. personnelId: string
  248. folderLabel: string
  249. files: VehicleCertZipFile[]
  250. }
  251. export function collectPersonnelCertZipEntries(
  252. people: PersonnelCertZipSource[]
  253. ): PersonnelCertZipEntry[] {
  254. const result: PersonnelCertZipEntry[] = []
  255. const usedFolders = new Set<string>()
  256. for (const person of people) {
  257. const certs = person.certList || []
  258. const files: VehicleCertZipFile[] = []
  259. certs.forEach((cert) => {
  260. const certName = String(cert.certName || '').trim() || '证书'
  261. parseUrls(cert.attachmentUrls).forEach((fileUrl) => {
  262. files.push({
  263. fileUrl,
  264. baseName: certName,
  265. ext: getFileExt(fileUrl)
  266. })
  267. })
  268. })
  269. if (!files.length) continue
  270. const rawName = String(person.personnelName || '').trim()
  271. const baseFolder = sanitizeZipPathSegment(rawName || person.id)
  272. const folderLabel = uniqueZipPath(usedFolders, baseFolder)
  273. result.push({
  274. personnelId: person.id,
  275. folderLabel,
  276. files
  277. })
  278. }
  279. return result
  280. }
  281. export function buildPersonnelCertZipFilename(
  282. entries: Array<{ folderLabel: string }>,
  283. yyyymmdd: string
  284. ): string {
  285. if (entries.length === 1) {
  286. return `人员证书_${entries[0].folderLabel}.zip`
  287. }
  288. return `人员证书批量_${entries.length}人_${yyyymmdd}.zip`
  289. }
  290. export async function buildAndSavePersonnelCertZip(
  291. people: PersonnelCertZipSource[],
  292. options: BuildCertZipOptions = {}
  293. ): Promise<BuildCertZipResult> {
  294. const collected = collectPersonnelCertZipEntries(people)
  295. if (!collected.length) {
  296. return { okCount: 0, failCount: 0, zipName: '' }
  297. }
  298. const yyyymmdd = options.yyyymmdd || todayYyyymmdd()
  299. const zipName = buildPersonnelCertZipFilename(collected, yyyymmdd)
  300. return packAndSaveCertZip(
  301. collected.map((e) => ({ folderLabel: e.folderLabel, files: e.files })),
  302. zipName,
  303. options
  304. )
  305. }