| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- import JSZip from 'jszip'
- import type { CertRead } from '@/api/pl'
- import { formatPlVehiclePlateDisplay } from '@/utils/pl-display'
- import {
- PL_VEHICLE_CERT_PART_TRAILER,
- normalizeVehicleCertPart
- } from '@/utils/pl-vehicle-cert'
- export type VehicleCertZipSource = {
- id: string
- licensePlate?: string | null
- trailerNo?: string | null
- certList?: CertRead[] | null
- }
- export type VehicleCertZipFile = {
- fileUrl: string
- baseName: string
- ext: string
- }
- export type VehicleCertZipEntry = {
- vehicleId: string
- plateFolder: string
- files: VehicleCertZipFile[]
- }
- export function sanitizeZipPathSegment(raw: string): string {
- return String(raw || '')
- .trim()
- .replace(/[\\/:*?"<>|]+/g, '_')
- .replace(/\s+/g, ' ')
- .trim() || '未命名'
- }
- /** Mirrors `normalizeAttachmentUrls` in download-attachment.ts (inlined for node:test). */
- function normalizeAttachmentUrls(raw?: string | null): string {
- if (!raw) return ''
- const trimmed = String(raw).trim()
- if (!trimmed) return ''
- if (trimmed.startsWith('[')) {
- try {
- const parsed = JSON.parse(trimmed)
- if (Array.isArray(parsed)) {
- return parsed.map((url) => String(url).trim()).filter(Boolean).join(',')
- }
- } catch {
- /* ignore */
- }
- }
- return trimmed
- }
- function parseUrls(raw?: string | null): string[] {
- const normalized = normalizeAttachmentUrls(raw)
- if (!normalized) return []
- return normalized
- .split(',')
- .map((item) => item.trim())
- .filter(Boolean)
- }
- function getFileExt(url: string): string {
- const name =
- String(url || '')
- .split('?')[0]
- .split('/')
- .pop() || ''
- const lastDot = name.lastIndexOf('.')
- if (lastDot === -1) return ''
- return name.slice(lastDot + 1).toLowerCase()
- }
- function partPrefix(cert: CertRead, enablePart: boolean): string {
- if (!enablePart) return ''
- return normalizeVehicleCertPart(cert.vehiclePart) === PL_VEHICLE_CERT_PART_TRAILER
- ? '挂·'
- : '主·'
- }
- export function collectVehicleCertZipEntries(
- vehicles: VehicleCertZipSource[]
- ): VehicleCertZipEntry[] {
- const result: VehicleCertZipEntry[] = []
- for (const vehicle of vehicles) {
- const certs = vehicle.certList || []
- const enablePart = certs.some(
- (cert) => normalizeVehicleCertPart(cert.vehiclePart) === PL_VEHICLE_CERT_PART_TRAILER
- )
- const files: VehicleCertZipFile[] = []
- certs.forEach((cert) => {
- const certName = String(cert.certName || '').trim() || '证书'
- const prefix = partPrefix(cert, enablePart)
- const baseName = `${prefix}${certName}`
- parseUrls(cert.attachmentUrls).forEach((fileUrl) => {
- files.push({
- fileUrl,
- baseName,
- ext: getFileExt(fileUrl)
- })
- })
- })
- if (!files.length) continue
- const plateRaw = formatPlVehiclePlateDisplay(vehicle.licensePlate, vehicle.trailerNo)
- result.push({
- vehicleId: vehicle.id,
- plateFolder: sanitizeZipPathSegment(plateRaw === '—' ? vehicle.id : plateRaw),
- files
- })
- }
- return result
- }
- export function buildVehicleCertZipFilename(
- entries: Array<{ plateFolder: string }>,
- yyyymmdd: string
- ): string {
- if (entries.length === 1) {
- return `车辆证书_${entries[0].plateFolder}.zip`
- }
- return `车辆证书批量_${entries.length}辆_${yyyymmdd}.zip`
- }
- export function uniqueZipPath(used: Set<string>, relativePath: string): string {
- if (!used.has(relativePath)) {
- used.add(relativePath)
- return relativePath
- }
- const lastSlash = relativePath.lastIndexOf('/')
- const dir = lastSlash >= 0 ? relativePath.slice(0, lastSlash + 1) : ''
- const name = lastSlash >= 0 ? relativePath.slice(lastSlash + 1) : relativePath
- const lastDot = name.lastIndexOf('.')
- const stem = lastDot > 0 ? name.slice(0, lastDot) : name
- const ext = lastDot > 0 ? name.slice(lastDot) : ''
- let i = 2
- let candidate = `${dir}${stem}_${i}${ext}`
- while (used.has(candidate)) {
- i += 1
- candidate = `${dir}${stem}_${i}${ext}`
- }
- used.add(candidate)
- return candidate
- }
- export type BuildVehicleCertZipOptions = {
- yyyymmdd?: string
- concurrency?: number
- fetchBlob?: (fileUrl: string, fileName: string) => Promise<Blob>
- saveAs?: (blob: Blob, filename: string) => void | Promise<void>
- onFileAdded?: (zipPath: string) => void
- }
- export type BuildVehicleCertZipResult = {
- okCount: number
- failCount: number
- zipName: string
- }
- export type BuildCertZipOptions = BuildVehicleCertZipOptions
- export type BuildCertZipResult = BuildVehicleCertZipResult
- function todayYyyymmdd(): string {
- const d = new Date()
- const y = d.getFullYear()
- const m = String(d.getMonth() + 1).padStart(2, '0')
- const day = String(d.getDate()).padStart(2, '0')
- return `${y}${m}${day}`
- }
- async function mapPool<T, R>(
- items: T[],
- concurrency: number,
- worker: (item: T) => Promise<R>
- ): Promise<R[]> {
- const results: R[] = new Array(items.length)
- let next = 0
- const runners = Array.from({ length: Math.min(concurrency, items.length) || 0 }, async () => {
- while (next < items.length) {
- const idx = next
- next += 1
- results[idx] = await worker(items[idx])
- }
- })
- await Promise.all(runners)
- return results
- }
- async function defaultFetchBlob(fileUrl: string, fileName: string): Promise<Blob> {
- const [{ fetchAttachmentBlob }, { resolvePhotoDisplayUrl }] = await Promise.all([
- import('@/utils/download-attachment'),
- import('@/utils/pl-photo')
- ])
- return fetchAttachmentBlob({ fileUrl, fileName }, { fullFileUrl: resolvePhotoDisplayUrl })
- }
- async function defaultSaveAs(blob: Blob, filename: string): Promise<void> {
- const { default: FileSaver } = await import('file-saver')
- FileSaver.saveAs(blob, filename)
- }
- export async function packAndSaveCertZip(
- entries: Array<{ folderLabel: string; files: VehicleCertZipFile[] }>,
- zipName: string,
- options: BuildCertZipOptions = {}
- ): Promise<BuildCertZipResult> {
- if (!entries.length) {
- return { okCount: 0, failCount: 0, zipName: '' }
- }
- const multi = entries.length > 1
- const concurrency = options.concurrency ?? 4
- const used = new Set<string>()
- const jobs: Array<{ zipPath: string; fileUrl: string; fileName: string }> = []
- for (const entry of entries) {
- for (const file of entry.files) {
- const leaf = `${file.baseName}${file.ext ? `.${file.ext}` : ''}`
- const rawPath = multi ? `${entry.folderLabel}/${leaf}` : leaf
- const zipPath = uniqueZipPath(used, rawPath)
- jobs.push({ zipPath, fileUrl: file.fileUrl, fileName: leaf })
- }
- }
- const fetchBlob = options.fetchBlob ?? defaultFetchBlob
- const zip = new JSZip()
- let okCount = 0
- let failCount = 0
- await mapPool(jobs, concurrency, async (job) => {
- try {
- const blob = await fetchBlob(job.fileUrl, job.fileName)
- const data = await blob.arrayBuffer()
- zip.file(job.zipPath, data)
- options.onFileAdded?.(job.zipPath)
- okCount += 1
- } catch {
- failCount += 1
- }
- })
- if (okCount === 0) {
- return { okCount: 0, failCount, zipName: '' }
- }
- const out = await zip.generateAsync({ type: 'blob' })
- const save = options.saveAs ?? defaultSaveAs
- await save(out, zipName)
- return { okCount, failCount, zipName }
- }
- export async function buildAndSaveVehicleCertZip(
- vehicles: VehicleCertZipSource[],
- options: BuildVehicleCertZipOptions = {}
- ): Promise<BuildVehicleCertZipResult> {
- const collected = collectVehicleCertZipEntries(vehicles)
- if (!collected.length) {
- return { okCount: 0, failCount: 0, zipName: '' }
- }
- const yyyymmdd = options.yyyymmdd || todayYyyymmdd()
- const zipName = buildVehicleCertZipFilename(collected, yyyymmdd)
- return packAndSaveCertZip(
- collected.map((e) => ({ folderLabel: e.plateFolder, files: e.files })),
- zipName,
- options
- )
- }
- export type PersonnelCertZipSource = {
- id: string
- personnelName?: string | null
- certList?: CertRead[] | null
- }
- export type PersonnelCertZipEntry = {
- personnelId: string
- folderLabel: string
- files: VehicleCertZipFile[]
- }
- export function collectPersonnelCertZipEntries(
- people: PersonnelCertZipSource[]
- ): PersonnelCertZipEntry[] {
- const result: PersonnelCertZipEntry[] = []
- const usedFolders = new Set<string>()
- for (const person of people) {
- const certs = person.certList || []
- const files: VehicleCertZipFile[] = []
- certs.forEach((cert) => {
- const certName = String(cert.certName || '').trim() || '证书'
- parseUrls(cert.attachmentUrls).forEach((fileUrl) => {
- files.push({
- fileUrl,
- baseName: certName,
- ext: getFileExt(fileUrl)
- })
- })
- })
- if (!files.length) continue
- const rawName = String(person.personnelName || '').trim()
- const baseFolder = sanitizeZipPathSegment(rawName || person.id)
- const folderLabel = uniqueZipPath(usedFolders, baseFolder)
- result.push({
- personnelId: person.id,
- folderLabel,
- files
- })
- }
- return result
- }
- export function buildPersonnelCertZipFilename(
- entries: Array<{ folderLabel: string }>,
- yyyymmdd: string
- ): string {
- if (entries.length === 1) {
- return `人员证书_${entries[0].folderLabel}.zip`
- }
- return `人员证书批量_${entries.length}人_${yyyymmdd}.zip`
- }
- export async function buildAndSavePersonnelCertZip(
- people: PersonnelCertZipSource[],
- options: BuildCertZipOptions = {}
- ): Promise<BuildCertZipResult> {
- const collected = collectPersonnelCertZipEntries(people)
- if (!collected.length) {
- return { okCount: 0, failCount: 0, zipName: '' }
- }
- const yyyymmdd = options.yyyymmdd || todayYyyymmdd()
- const zipName = buildPersonnelCertZipFilename(collected, yyyymmdd)
- return packAndSaveCertZip(
- collected.map((e) => ({ folderLabel: e.folderLabel, files: e.files })),
- zipName,
- options
- )
- }
|