Merge pull request 'feat: 国家导入/导出支持州省城市' (#27) from test into master
All checks were successful
Build and Deploy Front / deploy (push) Successful in 4m7s

Reviewed-on: https://git.ideship.com/ideship/front/pulls/27
This commit is contained in:
zzh 2026-11-19 18:10:30 +08:00
commit 4a7359f11c
5 changed files with 296 additions and 38 deletions

View File

@ -70,33 +70,166 @@ export async function deleteCountry(id: number) {
}
const TEMPLATE_HEADERS = ['国家二字码', '中文名', '英文名'] as const
const REGION_TEMPLATE_HEADERS = [
'国家二字码',
'州省中文名',
'州省英文名',
'城市中文名',
'城市英文名',
'简称',
'排序',
] as const
function writeCountryWorkbook(rows: Array<Record<string, string>>, fileName: string) {
function writeWorkbook(
rows: Array<Record<string, string | number>>,
headers: readonly string[],
cols: Array<{ wch: number }>,
fileName: string,
) {
const wb = XLSX.utils.book_new()
const sheet = XLSX.utils.json_to_sheet(rows, { header: [...TEMPLATE_HEADERS] })
sheet['!cols'] = [{ wch: 14 }, { wch: 18 }, { wch: 24 }]
const sheet = XLSX.utils.json_to_sheet(rows, { header: [...headers] })
sheet['!cols'] = cols
XLSX.utils.book_append_sheet(wb, sheet, '导入模板')
XLSX.writeFile(wb, fileName.endsWith('.xlsx') ? fileName : `${fileName}.xlsx`)
}
export function downloadCountryImportTemplate() {
writeCountryWorkbook(
writeWorkbook(
[
{ 国家二字码: 'CN', 中文名: '中国', 英文名: 'China' },
{ 国家二字码: 'US', 中文名: '美国', 英文名: 'United States' },
],
'国家地区导入模板.xlsx'
TEMPLATE_HEADERS,
[{ wch: 14 }, { wch: 18 }, { wch: 24 }],
'国家地区导入模板.xlsx',
)
}
export function downloadCountryRegionImportTemplate() {
writeWorkbook(
[
{
国家二字码: 'CN',
州省中文名: '广东',
州省英文名: 'Guangdong',
城市中文名: '深圳',
城市英文名: 'Shenzhen',
简称: '粤',
排序: 190,
},
{
国家二字码: 'CN',
州省中文名: '广东',
州省英文名: 'Guangdong',
城市中文名: '广州',
城市英文名: 'Guangzhou',
简称: '粤',
排序: 190,
},
{
国家二字码: 'CN',
州省中文名: '北京',
州省英文名: 'Beijing',
城市中文名: '',
城市英文名: '',
简称: '京',
排序: 10,
},
],
REGION_TEMPLATE_HEADERS,
[
{ wch: 12 },
{ wch: 14 },
{ wch: 16 },
{ wch: 14 },
{ wch: 16 },
{ wch: 8 },
{ wch: 8 },
],
'州省城市导入模板.xlsx',
)
}
export function exportCountryExcel(rows: CountryDto[], fileName = '国家地区.xlsx') {
writeCountryWorkbook(
writeWorkbook(
rows.map((row) => ({
国家二字码: row.countryCode,
中文名: row.chineseName,
英文名: row.englishName,
})),
fileName
TEMPLATE_HEADERS,
[{ wch: 14 }, { wch: 18 }, { wch: 24 }],
fileName,
)
}
export type CountryRegionExportRow = {
国家二字码: string
州省中文名: string
州省英文名: string
城市中文名: string
城市英文名: string
简称: string
排序: number
}
/** 按国家列表拉取州省/城市,导出为与导入模板同列的扁平表 */
export async function buildCountryRegionExportRows(
countries: CountryDto[],
): Promise<CountryRegionExportRow[]> {
const rows: CountryRegionExportRow[] = []
for (const country of countries) {
const provinces = await getCountryProvinceList(country.id)
if (!provinces.length) {
continue
}
for (const province of provinces) {
const cities = await getCountryCityList(province.id)
if (!cities.length) {
rows.push({
国家二字码: country.countryCode,
州省中文名: province.chineseName,
州省英文名: province.englishName || '',
城市中文名: '',
城市英文名: '',
简称: province.shortName || '',
排序: province.sortOrder,
})
continue
}
for (const city of cities) {
rows.push({
国家二字码: country.countryCode,
州省中文名: province.chineseName,
州省英文名: province.englishName || '',
城市中文名: city.chineseName,
城市英文名: city.englishName || '',
简称: province.shortName || '',
排序: city.sortOrder || province.sortOrder,
})
}
}
}
return rows
}
export function exportCountryRegionExcel(
rows: CountryRegionExportRow[],
fileName = '国家州省城市.xlsx',
) {
writeWorkbook(
rows,
REGION_TEMPLATE_HEADERS,
[
{ wch: 12 },
{ wch: 14 },
{ wch: 16 },
{ wch: 14 },
{ wch: 16 },
{ wch: 8 },
{ wch: 8 },
],
fileName,
)
}
@ -254,6 +387,20 @@ export async function deleteCountryCity(id: number) {
assertBusinessOk(res.data)
}
function mapImportResult(data: Record<string, unknown>): CountryImportResult {
const rawFailures = (data.failures ?? data.Failures ?? []) as Array<Record<string, unknown>>
return {
successCount: Number(data.successCount ?? data.SuccessCount ?? 0),
skipCount: Number(data.skipCount ?? data.SkipCount ?? 0),
failCount: Number(data.failCount ?? data.FailCount ?? 0),
deletedCount: Number(data.deletedCount ?? data.DeletedCount ?? 0),
failures: rawFailures.map((item) => ({
rowNumber: Number(item.rowNumber ?? item.RowNumber ?? 0),
reason: String(item.reason ?? item.Reason ?? ''),
})),
}
}
export async function importCountry(
file: File,
importMode: 'incremental' | 'full'
@ -263,16 +410,18 @@ export async function importCountry(
form.append('file', file)
const res = await axiosInstance.post(omsUrl('/system/country/import'), form)
assertBusinessOk(res.data)
const d = unwrapData<Record<string, unknown>>(res.data) ?? {}
const rawFailures = (d.failures ?? d.Failures ?? []) as Array<Record<string, unknown>>
return {
successCount: Number(d.successCount ?? d.SuccessCount ?? 0),
skipCount: Number(d.skipCount ?? d.SkipCount ?? 0),
failCount: Number(d.failCount ?? d.FailCount ?? 0),
deletedCount: Number(d.deletedCount ?? d.DeletedCount ?? 0),
failures: rawFailures.map((item) => ({
rowNumber: Number(item.rowNumber ?? item.RowNumber ?? 0),
reason: String(item.reason ?? item.Reason ?? ''),
})),
}
return mapImportResult(unwrapData<Record<string, unknown>>(res.data) ?? {})
}
/** POST /system/country/region/import */
export async function importCountryRegion(
file: File,
importMode: 'incremental' | 'full'
): Promise<CountryImportResult> {
const form = new FormData()
form.append('importMode', importMode)
form.append('file', file)
const res = await axiosInstance.post(omsUrl('/system/country/region/import'), form)
assertBusinessOk(res.data)
return mapImportResult(unwrapData<Record<string, unknown>>(res.data) ?? {})
}

View File

@ -4305,6 +4305,9 @@ export default {
'system.otherConfig.paymentQr.wechat': 'WeChat',
'system.otherConfig.paymentQr.replace': 'Replace',
'system.otherConfig.paymentQr.empty': 'Not uploaded',
'system.otherConfig.paymentQr.clickUpload': 'Click or drag to upload',
'system.otherConfig.paymentQr.clickReplace': 'Click to replace',
'system.otherConfig.paymentQr.uploading': 'Uploading…',
'system.otherConfig.paymentQr.uploadSuccess': 'Payment QR updated',
'system.otherConfig.paymentQr.uploadFailed': 'Upload failed',
'system.otherConfig.paymentQr.loadFailed': 'Failed to load payment QR',
@ -4713,6 +4716,8 @@ export default {
'system.country.actions.delete': 'Delete',
'system.country.actions.import': 'Import',
'system.country.actions.export': 'Export',
'system.country.actions.exportCountry': 'Countries only',
'system.country.actions.exportRegion': 'Country + province + city',
'system.country.rules.countryCodeRequired': 'Please enter the country code',
'system.country.rules.countryCodeFormat': 'Use 2 letters, e.g. CN, US',
'system.country.rules.chineseNameRequired': 'Please enter the Chinese name',
@ -4725,16 +4730,24 @@ export default {
'system.country.message.deleteFailed': 'Delete failed',
'system.country.message.loadFailed': 'Load failed',
'system.country.message.exportEmpty': 'Nothing to export',
'system.country.message.exportRegionEmpty': 'No provinces/cities under the listed countries',
'system.country.message.exportSuccess': 'Exported {count} rows',
'system.country.message.exportFailed': 'Export failed',
'system.country.import.modalTitle': 'Import Countries',
'system.country.import.modalTitle': 'Import Countries / Regions',
'system.country.import.scopeLabel': 'Import type',
'system.country.import.scope.country': 'Countries',
'system.country.import.scope.region': 'Provinces / Cities',
'system.country.import.tip': 'Download the template first. Country code, Chinese name, and English name are required. Code is ISO alpha-2, e.g. CN, US.',
'system.country.import.tipRegion': 'Download the template first. Country code and province Chinese name are required. Leave city blank to import province only. The country must already exist.',
'system.country.import.modeLabel': 'Import mode',
'system.country.import.mode.incremental': 'Incremental',
'system.country.import.mode.full': 'Full',
'system.country.import.mode.incrementalTip': 'Insert or update by country code. Countries missing from the file are kept.',
'system.country.import.mode.fullTip': 'Insert or update by country code, then soft-delete countries missing from the file. Export a backup first.',
'system.country.import.mode.regionIncrementalTip': 'Insert or update by country + province Chinese name, and province + city Chinese name. Missing rows are kept.',
'system.country.import.mode.regionFullTip': 'After upserts, soft-delete provinces missing under countries present in the file, and cities missing under provinces that listed cities.',
'system.country.import.mode.fullConfirm': 'Full import will soft-delete countries that are not in the Excel file. Continue?',
'system.country.import.mode.regionFullConfirm': 'Full import will soft-delete provinces/cities missing from the Excel for countries present in the file. Continue?',
'system.country.import.warningTitle': 'Confirm full import',
'system.country.import.downloadTemplate': 'Download template',
'system.country.import.submit': 'Import',

View File

@ -4316,6 +4316,9 @@ export default {
'system.otherConfig.paymentQr.wechat': '微信',
'system.otherConfig.paymentQr.replace': '更换图片',
'system.otherConfig.paymentQr.empty': '尚未上传',
'system.otherConfig.paymentQr.clickUpload': '点击或拖拽上传',
'system.otherConfig.paymentQr.clickReplace': '点击更换',
'system.otherConfig.paymentQr.uploading': '上传中…',
'system.otherConfig.paymentQr.uploadSuccess': '收款码已更新',
'system.otherConfig.paymentQr.uploadFailed': '上传失败',
'system.otherConfig.paymentQr.loadFailed': '加载收款码失败',
@ -4725,6 +4728,8 @@ export default {
'system.country.actions.delete': '删除',
'system.country.actions.import': '导入',
'system.country.actions.export': '导出',
'system.country.actions.exportCountry': '仅国家',
'system.country.actions.exportRegion': '国家+省+城市',
'system.country.rules.countryCodeRequired': '请输入国家二字码',
'system.country.rules.countryCodeFormat': '须为 2 位字母,如 CN、US',
'system.country.rules.chineseNameRequired': '请输入中文名',
@ -4737,16 +4742,24 @@ export default {
'system.country.message.deleteFailed': '删除失败',
'system.country.message.loadFailed': '加载失败',
'system.country.message.exportEmpty': '没有可导出的数据',
'system.country.message.exportRegionEmpty': '当前列表国家下没有州省/城市可导出',
'system.country.message.exportSuccess': '已导出 {count} 条',
'system.country.message.exportFailed': '导出失败',
'system.country.import.modalTitle': '导入国家地区',
'system.country.import.scopeLabel': '导入内容',
'system.country.import.scope.country': '国家',
'system.country.import.scope.region': '州省城市',
'system.country.import.tip': '请先下载模板。国家二字码、中文名、英文名均必填。二字码为 ISO 两位字母,如 CN、US。',
'system.country.import.tipRegion': '请先下载模板。国家二字码、州省中文名必填;城市中文名为空时只导入州省。国家须已存在。',
'system.country.import.modeLabel': '导入方式',
'system.country.import.mode.incremental': '增量导入',
'system.country.import.mode.full': '全量导入',
'system.country.import.mode.incrementalTip': '按二字码新增或更新已有国家,不会删除文件中没有的国家。',
'system.country.import.mode.fullTip': '按二字码新增或更新,并软删除文件中未出现的国家(请先导出备份)。',
'system.country.import.mode.regionIncrementalTip': '按国家+州省中文名、州省+城市中文名新增或更新,不会删除未出现在文件中的数据。',
'system.country.import.mode.regionFullTip': '增量写入后,软删除文件中出现过的国家下未列出的州省,以及出现过城市的州省下未列出的城市。',
'system.country.import.mode.fullConfirm': '全量导入将软删除 Excel 中未出现的国家,确认继续?',
'system.country.import.mode.regionFullConfirm': '全量导入将软删除文件中出现过的国家下未列出的州省/城市,确认继续?',
'system.country.import.warningTitle': '确认全量导入',
'system.country.import.downloadTemplate': '下载模板',
'system.country.import.submit': '开始导入',

View File

@ -2,7 +2,7 @@
<a-modal
v-model:visible="visible"
:title="t('system.country.import.modalTitle')"
:width="520"
:width="560"
:ok-loading="importing"
:ok-text="t('system.country.import.submit')"
:cancel-text="t('system.country.import.cancel')"
@ -11,7 +11,19 @@
@cancel="handleCancel"
>
<div class="country-import-modal">
<div class="import-tip">{{ t('system.country.import.tip') }}</div>
<div class="import-scope">
<div class="import-mode-label">{{ t('system.country.import.scopeLabel') }}</div>
<SlidingTabs
v-model="importScope"
size="mini"
:aria-label="t('system.country.import.scopeLabel')"
:items="importScopeTabs"
@change="handleScopeChange"
/>
</div>
<div class="import-tip">{{ tipText }}</div>
<div class="import-mode">
<div class="import-mode-label">{{ t('system.country.import.modeLabel') }}</div>
<SlidingTabs
@ -20,14 +32,9 @@
:aria-label="t('system.country.import.modeLabel')"
:items="importModeTabs"
/>
<div class="import-mode-tip">
{{
importMode === 'full'
? t('system.country.import.mode.fullTip')
: t('system.country.import.mode.incrementalTip')
}}
</div>
<div class="import-mode-tip">{{ modeTipText }}</div>
</div>
<div class="import-actions">
<a-button class="app-btn-primary-soft" @click="handleDownloadTemplate">
<template #icon>
@ -36,6 +43,7 @@
{{ t('system.country.import.downloadTemplate') }}
</a-button>
</div>
<a-upload
draggable
:auto-upload="false"
@ -45,6 +53,7 @@
:file-list="fileList"
@change="handleFileChange"
/>
<div v-if="importResult" class="import-result">
<a-alert type="info" :show-icon="false">
{{
@ -75,7 +84,9 @@ import { IconDownload } from '@arco-design/web-vue/es/icon'
import SlidingTabs from '@/components/SlidingTabs/index.vue'
import {
downloadCountryImportTemplate,
downloadCountryRegionImportTemplate,
importCountry,
importCountryRegion,
type CountryImportResult,
} from '@/api/system/country'
@ -85,25 +96,58 @@ const emit = defineEmits<{
const { t } = useI18n()
type ImportScope = 'country' | 'region'
const visible = ref(false)
const fileList = ref<FileItem[]>([])
const selectedFile = ref<File | null>(null)
const importing = ref(false)
const importScope = ref<ImportScope>('country')
const importMode = ref<'incremental' | 'full'>('incremental')
const importResult = ref<CountryImportResult | null>(null)
const importScopeTabs = computed(() => [
{ key: 'country', label: t('system.country.import.scope.country') },
{ key: 'region', label: t('system.country.import.scope.region') },
])
const importModeTabs = computed(() => [
{ key: 'incremental', label: t('system.country.import.mode.incremental') },
{ key: 'full', label: t('system.country.import.mode.full') },
])
const tipText = computed(() =>
importScope.value === 'region'
? t('system.country.import.tipRegion')
: t('system.country.import.tip'),
)
const modeTipText = computed(() => {
if (importScope.value === 'region') {
return importMode.value === 'full'
? t('system.country.import.mode.regionFullTip')
: t('system.country.import.mode.regionIncrementalTip')
}
return importMode.value === 'full'
? t('system.country.import.mode.fullTip')
: t('system.country.import.mode.incrementalTip')
})
function open() {
fileList.value = []
selectedFile.value = null
importResult.value = null
importScope.value = 'country'
importMode.value = 'incremental'
visible.value = true
}
function handleScopeChange() {
fileList.value = []
selectedFile.value = null
importResult.value = null
}
function handleFileChange(_: FileItem[], fileItem: FileItem) {
fileList.value = fileItem ? [fileItem] : []
selectedFile.value = (fileItem?.file as File) ?? null
@ -112,7 +156,11 @@ function handleFileChange(_: FileItem[], fileItem: FileItem) {
function handleDownloadTemplate() {
try {
downloadCountryImportTemplate()
if (importScope.value === 'region') {
downloadCountryRegionImportTemplate()
} else {
downloadCountryImportTemplate()
}
Message.success(t('system.country.import.downloadSuccess'))
} catch (e: unknown) {
const err = e as { message?: string }
@ -124,7 +172,10 @@ function confirmFullImport(): Promise<boolean> {
return new Promise((resolve) => {
Modal.warning({
title: t('system.country.import.warningTitle'),
content: t('system.country.import.mode.fullConfirm'),
content:
importScope.value === 'region'
? t('system.country.import.mode.regionFullConfirm')
: t('system.country.import.mode.fullConfirm'),
hideCancel: false,
okText: t('system.country.import.submit'),
cancelText: t('system.country.import.cancel'),
@ -147,7 +198,10 @@ async function handleBeforeOk() {
importing.value = true
try {
const result = await importCountry(selectedFile.value, importMode.value)
const result =
importScope.value === 'region'
? await importCountryRegion(selectedFile.value, importMode.value)
: await importCountry(selectedFile.value, importMode.value)
importResult.value = result
if (result.successCount > 0 || result.skipCount > 0 || result.deletedCount > 0) {
emit('success')
@ -192,6 +246,7 @@ defineExpose({ open })
line-height: 1.6;
}
.import-scope,
.import-mode {
display: flex;
flex-direction: column;

View File

@ -20,9 +20,20 @@
<a-button @click="openImport">
{{ t('system.country.actions.import') }}
</a-button>
<a-button :loading="exporting" @click="handleExport">
{{ t('system.country.actions.export') }}
</a-button>
<a-dropdown trigger="click" position="bl" :popup-max-height="false">
<a-button :loading="exporting">
{{ t('system.country.actions.export') }}
<icon-down />
</a-button>
<template #content>
<a-doption :disabled="exporting" @click="handleExportSelect('country')">
{{ t('system.country.actions.exportCountry') }}
</a-doption>
<a-doption :disabled="exporting" @click="handleExportSelect('region')">
{{ t('system.country.actions.exportRegion') }}
</a-doption>
</template>
</a-dropdown>
</div>
<div class="toolbar-right">
<PaginationPro
@ -98,14 +109,17 @@
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Message, Modal } from '@arco-design/web-vue'
import { IconDown } from '@arco-design/web-vue/es/icon'
import HandsontablePro from '@/components/HandsontablePro/index.vue'
import PaginationPro from '@/components/PaginationPro/index.vue'
import { useTableContainerHeight } from '@/composables/useTableContainerHeight'
import { renderWarehouseActionBtn, wrapWarehouseActions } from '@/utils/warehouseActionRenderer'
import {
buildCountryRegionExportRows,
createCountry,
deleteCountry,
exportCountryExcel,
exportCountryRegionExcel,
getCountryList,
mapCountryRow,
updateCountry,
@ -307,15 +321,29 @@ function openImport() {
importModalRef.value?.open()
}
function handleExport() {
async function handleExportSelect(scope: 'country' | 'region') {
if (!filteredRows.value.length) {
Message.warning(t('system.country.message.exportEmpty'))
return
}
exporting.value = true
try {
exportCountryExcel(filteredRows.value)
Message.success(t('system.country.message.exportSuccess', { count: filteredRows.value.length }))
if (scope === 'country') {
exportCountryExcel(filteredRows.value)
Message.success(
t('system.country.message.exportSuccess', { count: filteredRows.value.length }),
)
return
}
const rows = await buildCountryRegionExportRows(filteredRows.value)
if (!rows.length) {
Message.warning(t('system.country.message.exportRegionEmpty'))
return
}
exportCountryRegionExcel(rows)
Message.success(t('system.country.message.exportSuccess', { count: rows.length }))
} catch (e: unknown) {
const err = e as { message?: string }
Message.error(err?.message || t('system.country.message.exportFailed'))