Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 101b27c92c | |||
| 5ed9f79a5e | |||
| 6880b5daf4 | |||
| 1000b489a0 | |||
| 72fef35807 | |||
| f570383717 | |||
| fe557c912d | |||
| 84fb2f314a |
@@ -0,0 +1,88 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Form, Input, Modal, message } from 'antd';
|
||||||
|
import type { UpdateMyHqCredentialsRequest } from '@dukang/shared-types';
|
||||||
|
import { request, type HqProfile } from '../lib/api';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean;
|
||||||
|
profile: HqProfile | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onUpdated: (profile: HqProfile) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function HqAccountSettingsModal({ open, profile, onClose, onUpdated }: Props) {
|
||||||
|
const [form] = Form.useForm<UpdateMyHqCredentialsRequest & { confirmPassword?: string }>();
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
form.setFieldsValue({
|
||||||
|
loginName: profile?.loginName ?? '',
|
||||||
|
oldPassword: '',
|
||||||
|
newPassword: '',
|
||||||
|
confirmPassword: '',
|
||||||
|
});
|
||||||
|
}, [open, profile, form]);
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
if (values.newPassword && values.newPassword !== values.confirmPassword) {
|
||||||
|
message.error('两次输入的新密码不一致');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body: UpdateMyHqCredentialsRequest = {};
|
||||||
|
const nextLogin = values.loginName?.trim();
|
||||||
|
if (nextLogin && nextLogin !== (profile?.loginName ?? '')) {
|
||||||
|
body.loginName = nextLogin;
|
||||||
|
}
|
||||||
|
if (values.newPassword?.trim()) {
|
||||||
|
body.newPassword = values.newPassword.trim();
|
||||||
|
if (values.oldPassword?.trim()) body.oldPassword = values.oldPassword.trim();
|
||||||
|
}
|
||||||
|
if (!body.loginName && !body.newPassword) {
|
||||||
|
message.warning('请填写要修改的内容');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await request('/admin/me/credentials', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const updated = await request<HqProfile>('/admin/auth/me');
|
||||||
|
message.success('账号信息已更新');
|
||||||
|
onUpdated(updated);
|
||||||
|
onClose();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title="账号设置"
|
||||||
|
open={open}
|
||||||
|
onCancel={onClose}
|
||||||
|
onOk={() => void submit()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="loginName" label="登录用户名" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||||
|
<Input autoComplete="username" placeholder="用于密码登录" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="oldPassword" label="当前密码" extra="已设置过密码时,修改密码必填">
|
||||||
|
<Input.Password autoComplete="current-password" placeholder="不修改密码请留空" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="newPassword" label="新密码" rules={[{ min: 6, message: '至少 6 位' }]}>
|
||||||
|
<Input.Password autoComplete="new-password" placeholder="不修改请留空" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="confirmPassword" label="确认新密码">
|
||||||
|
<Input.Password autoComplete="new-password" placeholder="不修改请留空" />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ import { clearAuth, request, type HqProfile } from '../lib/api';
|
|||||||
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
||||||
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
||||||
import { ListColumnPrefsProvider } from '../lib/ListColumnPrefsContext';
|
import { ListColumnPrefsProvider } from '../lib/ListColumnPrefsContext';
|
||||||
|
import { HqAccountSettingsModal } from '../components/HqAccountSettingsModal';
|
||||||
|
|
||||||
const { Header, Sider, Content } = Layout;
|
const { Header, Sider, Content } = Layout;
|
||||||
|
|
||||||
@@ -292,6 +293,7 @@ export default function AdminLayout() {
|
|||||||
const contentRef = useRef<HTMLDivElement>(null);
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
const [profile, setProfile] = useState<HqProfile | null>(null);
|
const [profile, setProfile] = useState<HqProfile | null>(null);
|
||||||
const [auditPendingCount, setAuditPendingCount] = useState(0);
|
const [auditPendingCount, setAuditPendingCount] = useState(0);
|
||||||
|
const [accountSettingsOpen, setAccountSettingsOpen] = useState(false);
|
||||||
|
|
||||||
function refreshAuditPendingCount() {
|
function refreshAuditPendingCount() {
|
||||||
Promise.all([
|
Promise.all([
|
||||||
@@ -419,11 +421,20 @@ export default function AdminLayout() {
|
|||||||
<span style={{ color: '#999' }}>
|
<span style={{ color: '#999' }}>
|
||||||
{HQ_ROLE_LABELS[profile?.adminRole ?? ''] || profile?.adminRole || ''}
|
{HQ_ROLE_LABELS[profile?.adminRole ?? ''] || profile?.adminRole || ''}
|
||||||
</span>
|
</span>
|
||||||
|
<Button type="text" icon={<UserOutlined />} onClick={() => setAccountSettingsOpen(true)}>
|
||||||
|
账号设置
|
||||||
|
</Button>
|
||||||
<Button type="text" icon={<LogoutOutlined />} onClick={logout}>
|
<Button type="text" icon={<LogoutOutlined />} onClick={logout}>
|
||||||
退出
|
退出
|
||||||
</Button>
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
</Header>
|
</Header>
|
||||||
|
<HqAccountSettingsModal
|
||||||
|
open={accountSettingsOpen}
|
||||||
|
profile={profile}
|
||||||
|
onClose={() => setAccountSettingsOpen(false)}
|
||||||
|
onUpdated={setProfile}
|
||||||
|
/>
|
||||||
<div
|
<div
|
||||||
ref={contentRef}
|
ref={contentRef}
|
||||||
className="admin-layout"
|
className="admin-layout"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export const CLIENT_APP = 'HQ_WEB';
|
|||||||
export type HqProfile = {
|
export type HqProfile = {
|
||||||
id: string;
|
id: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
|
loginName?: string | null;
|
||||||
name: string;
|
name: string;
|
||||||
adminRole: string;
|
adminRole: string;
|
||||||
status: string;
|
status: string;
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/** 将列表可见列 key 追加到导出 query */
|
||||||
|
export function appendExportColumns(qs: URLSearchParams, keys: string[]) {
|
||||||
|
if (keys.length) qs.set('columns', keys.join(','));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exportColumnsBody(keys: string[]): { columns?: string[] } {
|
||||||
|
return keys.length ? { columns: keys } : {};
|
||||||
|
}
|
||||||
@@ -8,8 +8,11 @@ export type StoreCreateForm = {
|
|||||||
city?: string;
|
city?: string;
|
||||||
district: string;
|
district: string;
|
||||||
districtCode?: string;
|
districtCode?: string;
|
||||||
|
/** @deprecated 使用 categoryIds */
|
||||||
categoryParentId?: string;
|
categoryParentId?: string;
|
||||||
categoryId: string;
|
/** @deprecated 使用 categoryIds */
|
||||||
|
categoryId?: string;
|
||||||
|
categoryIds: string[];
|
||||||
name: string;
|
name: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
address: string;
|
address: string;
|
||||||
@@ -52,7 +55,7 @@ export function validateStoreCreateStep1(
|
|||||||
| 'partnerAccountId'
|
| 'partnerAccountId'
|
||||||
| 'cityId'
|
| 'cityId'
|
||||||
| 'regionCodes'
|
| 'regionCodes'
|
||||||
| 'categoryId'
|
| 'categoryIds'
|
||||||
| 'name'
|
| 'name'
|
||||||
| 'phone'
|
| 'phone'
|
||||||
| 'address'
|
| 'address'
|
||||||
@@ -69,7 +72,7 @@ export function validateStoreCreateStep1(
|
|||||||
if (!form.partnerAccountId) return '请选择开城合伙人';
|
if (!form.partnerAccountId) return '请选择开城合伙人';
|
||||||
if (!form.regionCodes || form.regionCodes.length < 3) return '请选择省 / 市 / 区县';
|
if (!form.regionCodes || form.regionCodes.length < 3) return '请选择省 / 市 / 区县';
|
||||||
if (!form.cityId) return '所选地区未匹配到开城城市,请先在「开城 → 城市」配置对应区划';
|
if (!form.cityId) return '所选地区未匹配到开城城市,请先在「开城 → 城市」配置对应区划';
|
||||||
if (!form.categoryId?.trim()) return '请选择门店分类(细类)';
|
if (!form.categoryIds?.length) return '请至少选择一个门店分类(细类)';
|
||||||
if (!form.name?.trim()) return '请填写门店名称';
|
if (!form.name?.trim()) return '请填写门店名称';
|
||||||
if (!form.phone?.trim()) return '请填写门店手机号';
|
if (!form.phone?.trim()) return '请填写门店手机号';
|
||||||
if (!PHONE_RE.test(form.phone.trim())) return '门店手机号须为11位手机号';
|
if (!PHONE_RE.test(form.phone.trim())) return '门店手机号须为11位手机号';
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
applyColumnPrefs,
|
applyColumnPrefs,
|
||||||
columnKey,
|
columnKey,
|
||||||
settingItems,
|
settingItems,
|
||||||
|
visibleColumnKeys,
|
||||||
type ListColumnSettingItem,
|
type ListColumnSettingItem,
|
||||||
} from './list-column-prefs';
|
} from './list-column-prefs';
|
||||||
import { beginColumnResize, withResizeTitle } from './column-resize';
|
import { beginColumnResize, withResizeTitle } from './column-resize';
|
||||||
@@ -48,6 +49,16 @@ export function useAdminListColumns<T>(
|
|||||||
);
|
);
|
||||||
itemsRef.current = items;
|
itemsRef.current = items;
|
||||||
|
|
||||||
|
const exportColumnKeys = useMemo(() => {
|
||||||
|
const keyed = (allColumns as ColumnType<T>[]).map((col, i) => ({
|
||||||
|
col,
|
||||||
|
key: columnKey(col, i),
|
||||||
|
actions: col.title === '操作' || col.key === ACTIONS_COLUMN_KEY || col.key === 'actions',
|
||||||
|
}));
|
||||||
|
const defaultKeys = keyed.filter((c) => !c.actions).map((c) => c.key);
|
||||||
|
return visibleColumnKeys(defaultKeys, pref);
|
||||||
|
}, [allColumns, pref]);
|
||||||
|
|
||||||
const serialCol: ColumnType<T> = useMemo(
|
const serialCol: ColumnType<T> = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
key: SERIAL_COLUMN_KEY,
|
key: SERIAL_COLUMN_KEY,
|
||||||
@@ -171,5 +182,5 @@ export function useAdminListColumns<T>(
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
return { columns, settingsButton, settingsModal };
|
return { columns, settingsButton, settingsModal, exportColumnKeys };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import {
|
|||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { downloadBase64File } from '../lib/exportExcel';
|
import { downloadBase64File } from '../lib/exportExcel';
|
||||||
|
import { exportColumnsBody } from '../lib/export-columns';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import OssUpload from '../components/OssUpload';
|
import OssUpload from '../components/OssUpload';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
@@ -62,6 +63,8 @@ export default function DevPlanTasksPage() {
|
|||||||
const [dispatchOpen, setDispatchOpen] = useState(false);
|
const [dispatchOpen, setDispatchOpen] = useState(false);
|
||||||
const [batchEditOpen, setBatchEditOpen] = useState(false);
|
const [batchEditOpen, setBatchEditOpen] = useState(false);
|
||||||
const [batchSaving, setBatchSaving] = useState(false);
|
const [batchSaving, setBatchSaving] = useState(false);
|
||||||
|
const [creatingVersion, setCreatingVersion] = useState(false);
|
||||||
|
const [newVersionNo, setNewVersionNo] = useState('');
|
||||||
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
||||||
const [supportTickets, setSupportTickets] = useState<SupportTicketDto[]>([]);
|
const [supportTickets, setSupportTickets] = useState<SupportTicketDto[]>([]);
|
||||||
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
||||||
@@ -172,9 +175,34 @@ export default function DevPlanTasksPage() {
|
|||||||
|
|
||||||
function openBatchEdit() {
|
function openBatchEdit() {
|
||||||
batchForm.setFieldsValue({ status: undefined, versionId: undefined });
|
batchForm.setFieldsValue({ status: undefined, versionId: undefined });
|
||||||
|
setNewVersionNo('');
|
||||||
setBatchEditOpen(true);
|
setBatchEditOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function createVersionInBatch() {
|
||||||
|
const versionNo = newVersionNo.trim();
|
||||||
|
if (!versionNo) {
|
||||||
|
message.warning('请输入版本号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCreatingVersion(true);
|
||||||
|
try {
|
||||||
|
const created = await request<DevPlanVersionDto>('/admin/dev-plan/versions', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ versionNo }),
|
||||||
|
});
|
||||||
|
const res = await request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100');
|
||||||
|
setVersions(res.items ?? []);
|
||||||
|
batchForm.setFieldsValue({ versionId: created.id });
|
||||||
|
setNewVersionNo('');
|
||||||
|
message.success(`已创建版本 ${versionNo}`);
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '创建失败');
|
||||||
|
} finally {
|
||||||
|
setCreatingVersion(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function submitBatchEdit() {
|
async function submitBatchEdit() {
|
||||||
const values = await batchForm.validateFields();
|
const values = await batchForm.validateFields();
|
||||||
if (!values.status && !values.versionId) {
|
if (!values.status && !values.versionId) {
|
||||||
@@ -224,34 +252,6 @@ export default function DevPlanTasksPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function exportTasks(scope: 'filter' | 'selected') {
|
|
||||||
setExporting(true);
|
|
||||||
try {
|
|
||||||
const result = await request<{
|
|
||||||
filename: string;
|
|
||||||
mimeType: string;
|
|
||||||
contentBase64: string;
|
|
||||||
count: number;
|
|
||||||
}>('/admin/dev-plan/tasks/export', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify({
|
|
||||||
scope,
|
|
||||||
format: exportFormat,
|
|
||||||
ids: scope === 'selected' ? selectedRowKeys : undefined,
|
|
||||||
status: filters.status || undefined,
|
|
||||||
type: filters.type || undefined,
|
|
||||||
keyword: filters.keyword || undefined,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
downloadBase64File(result.contentBase64, result.filename, result.mimeType);
|
|
||||||
message.success(`已导出 ${result.count} 条任务`);
|
|
||||||
} catch (e) {
|
|
||||||
message.error(e instanceof Error ? e.message : '导出失败');
|
|
||||||
} finally {
|
|
||||||
setExporting(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseColumns: ColumnsType<DevPlanTaskDto> = [
|
const baseColumns: ColumnsType<DevPlanTaskDto> = [
|
||||||
{
|
{
|
||||||
title: '任务号',
|
title: '任务号',
|
||||||
@@ -285,6 +285,7 @@ export default function DevPlanTasksPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '附件',
|
title: '附件',
|
||||||
|
key: 'attachmentUrls',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.attachmentUrls?.length ? (
|
row.attachmentUrls?.length ? (
|
||||||
@@ -314,6 +315,7 @@ export default function DevPlanTasksPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '关联版本',
|
title: '关联版本',
|
||||||
|
key: 'versions',
|
||||||
dataIndex: 'versions',
|
dataIndex: 'versions',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
@@ -347,7 +349,36 @@ export default function DevPlanTasksPage() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('dev-plan-tasks', baseColumns, { page, pageSize });
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('dev-plan-tasks', baseColumns, { page, pageSize });
|
||||||
|
|
||||||
|
async function exportTasks(scope: 'filter' | 'selected') {
|
||||||
|
setExporting(true);
|
||||||
|
try {
|
||||||
|
const result = await request<{
|
||||||
|
filename: string;
|
||||||
|
mimeType: string;
|
||||||
|
contentBase64: string;
|
||||||
|
count: number;
|
||||||
|
}>('/admin/dev-plan/tasks/export', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
scope,
|
||||||
|
format: exportFormat,
|
||||||
|
ids: scope === 'selected' ? selectedRowKeys : undefined,
|
||||||
|
status: filters.status || undefined,
|
||||||
|
type: filters.type || undefined,
|
||||||
|
keyword: filters.keyword || undefined,
|
||||||
|
...exportColumnsBody(exportColumnKeys),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
downloadBase64File(result.contentBase64, result.filename, result.mimeType);
|
||||||
|
message.success(`已导出 ${result.count} 条任务`);
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '导出失败');
|
||||||
|
} finally {
|
||||||
|
setExporting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -541,6 +572,19 @@ export default function DevPlanTasksPage() {
|
|||||||
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
|
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item label="创建新版本">
|
||||||
|
<Space.Compact style={{ width: '100%' }}>
|
||||||
|
<Input
|
||||||
|
placeholder="版本号,如 v4.0.11"
|
||||||
|
value={newVersionNo}
|
||||||
|
onChange={(e) => setNewVersionNo(e.target.value)}
|
||||||
|
onPressEnter={() => void createVersionInBatch()}
|
||||||
|
/>
|
||||||
|
<Button loading={creatingVersion} onClick={() => void createVersionInBatch()}>
|
||||||
|
创建
|
||||||
|
</Button>
|
||||||
|
</Space.Compact>
|
||||||
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ export default function DevPlanVersionsPage() {
|
|||||||
useAdminList<DevPlanVersionDto>('/admin/dev-plan/versions', () => {
|
useAdminList<DevPlanVersionDto>('/admin/dev-plan/versions', () => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (filters.status) qs.set('status', filters.status);
|
if (filters.status) qs.set('status', filters.status);
|
||||||
|
if (filters.keyword) qs.set('keyword', filters.keyword);
|
||||||
return qs;
|
return qs;
|
||||||
}, [filters]);
|
}, [filters]);
|
||||||
|
|
||||||
@@ -190,6 +191,9 @@ export default function DevPlanVersionsPage() {
|
|||||||
<Form.Item name="status" label="状态">
|
<Form.Item name="status" label="状态">
|
||||||
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item name="keyword" label="查找">
|
||||||
|
<Input allowClear placeholder="版本号或内容" style={{ width: 220 }} />
|
||||||
|
</Form.Item>
|
||||||
<Button type="primary" htmlType="submit">
|
<Button type="primary" htmlType="submit">
|
||||||
筛选
|
筛选
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
@@ -27,6 +28,7 @@ import {
|
|||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||||
|
import { appendExportColumns } from '../lib/export-columns';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
@@ -98,6 +100,7 @@ const STATUS_COLORS: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function LogisticsBillsPage() {
|
export default function LogisticsBillsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [summaryForm] = Form.useForm();
|
const [summaryForm] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
@@ -202,6 +205,7 @@ export default function LogisticsBillsPage() {
|
|||||||
if (filters.providerId) qs.set('providerId', filters.providerId);
|
if (filters.providerId) qs.set('providerId', filters.providerId);
|
||||||
if (filters.year) qs.set('year', filters.year);
|
if (filters.year) qs.set('year', filters.year);
|
||||||
if (filters.month) qs.set('month', filters.month);
|
if (filters.month) qs.set('month', filters.month);
|
||||||
|
appendExportColumns(qs, exportColumnKeys);
|
||||||
const result = await request<{ csv: string; count: number }>(
|
const result = await request<{ csv: string; count: number }>(
|
||||||
`/admin/logistics-bills/export?${qs}`,
|
`/admin/logistics-bills/export?${qs}`,
|
||||||
);
|
);
|
||||||
@@ -250,6 +254,7 @@ export default function LogisticsBillsPage() {
|
|||||||
const billColumns: ColumnsType<BillRow> = [
|
const billColumns: ColumnsType<BillRow> = [
|
||||||
{
|
{
|
||||||
title: '账单号',
|
title: '账单号',
|
||||||
|
key: '账单号',
|
||||||
dataIndex: 'billNo',
|
dataIndex: 'billNo',
|
||||||
width: 170,
|
width: 170,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
@@ -258,42 +263,49 @@ export default function LogisticsBillsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '承运商',
|
title: '承运商',
|
||||||
|
key: '承运商',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (_, r) => `${r.providerName || ''} (${r.providerCode || ''})`,
|
render: (_, r) => `${r.providerName || ''} (${r.providerCode || ''})`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '账期',
|
title: '账期',
|
||||||
|
key: '账期',
|
||||||
width: 200,
|
width: 200,
|
||||||
render: (_, r) =>
|
render: (_, r) =>
|
||||||
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '结算方式',
|
title: '结算方式',
|
||||||
|
key: '结算方式',
|
||||||
dataIndex: 'settlementMethod',
|
dataIndex: 'settlementMethod',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (v) =>
|
render: (v) =>
|
||||||
LOGISTICS_SETTLEMENT_METHOD_LABELS[v as LogisticsSettlementMethod] || v,
|
LOGISTICS_SETTLEMENT_METHOD_LABELS[v as LogisticsSettlementMethod] || v,
|
||||||
},
|
},
|
||||||
{ title: '订单数', dataIndex: 'orderCount', width: 80 },
|
{ title: '订单数', key: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||||
{ title: '瓶数', dataIndex: 'bottleCount', width: 80 },
|
{ title: '瓶数', key: '瓶数', dataIndex: 'bottleCount', width: 80 },
|
||||||
{
|
{
|
||||||
title: '物流费',
|
title: '物流费',
|
||||||
|
key: '物流费',
|
||||||
dataIndex: 'logisticsAmount',
|
dataIndex: 'logisticsAmount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收款户名',
|
title: '收款户名',
|
||||||
|
key: '收款户名',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (_, r) => providerBank(r)?.bankAccountName || '—',
|
render: (_, r) => providerBank(r)?.bankAccountName || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收款账号',
|
title: '收款账号',
|
||||||
|
key: '收款账号',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (_, r) => providerBank(r)?.bankAccountNo || '—',
|
render: (_, r) => providerBank(r)?.bankAccountNo || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
|
key: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 90,
|
width: 90,
|
||||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
||||||
@@ -398,7 +410,7 @@ export default function LogisticsBillsPage() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-logistics-bills', billColumns, {
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-logistics-bills', billColumns, {
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
});
|
});
|
||||||
@@ -627,7 +639,20 @@ export default function LogisticsBillsPage() {
|
|||||||
pagination={false}
|
pagination={false}
|
||||||
dataSource={detail.items ?? []}
|
dataSource={detail.items ?? []}
|
||||||
columns={[
|
columns={[
|
||||||
{ title: '订单号', dataIndex: 'orderNo' },
|
{
|
||||||
|
title: '订单号',
|
||||||
|
dataIndex: 'orderNo',
|
||||||
|
render: (v: string) =>
|
||||||
|
v ? (
|
||||||
|
<AdminPrimaryLink
|
||||||
|
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||||
|
>
|
||||||
|
{v}
|
||||||
|
</AdminPrimaryLink>
|
||||||
|
) : (
|
||||||
|
'—'
|
||||||
|
),
|
||||||
|
},
|
||||||
{ title: '瓶数', dataIndex: 'quantity', width: 70 },
|
{ title: '瓶数', dataIndex: 'quantity', width: 70 },
|
||||||
{
|
{
|
||||||
title: '物流费',
|
title: '物流费',
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { useAdminListColumns } from '../lib/useAdminListColumns';
|
|||||||
import { AdminListHeader } from '../components/AdminListHeader';
|
import { AdminListHeader } from '../components/AdminListHeader';
|
||||||
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
|
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
|
||||||
import { downloadBase64File } from '../lib/exportExcel';
|
import { downloadBase64File } from '../lib/exportExcel';
|
||||||
|
import { exportColumnsBody } from '../lib/export-columns';
|
||||||
import {
|
import {
|
||||||
ADMIN_OPTIONS_PAGE_SIZE,
|
ADMIN_OPTIONS_PAGE_SIZE,
|
||||||
DELIVERY_PROVIDER_LABELS,
|
DELIVERY_PROVIDER_LABELS,
|
||||||
@@ -265,8 +266,9 @@ function buildExportPayload(
|
|||||||
format: OrderExportFormat,
|
format: OrderExportFormat,
|
||||||
filters: OrderExportFilters,
|
filters: OrderExportFilters,
|
||||||
selectedIds: string[],
|
selectedIds: string[],
|
||||||
|
columns?: string[],
|
||||||
) {
|
) {
|
||||||
const payload: Record<string, unknown> = { scope, format };
|
const payload: Record<string, unknown> = { scope, format, ...exportColumnsBody(columns ?? []) };
|
||||||
if (scope === 'selected') {
|
if (scope === 'selected') {
|
||||||
payload.ids = selectedIds;
|
payload.ids = selectedIds;
|
||||||
return payload;
|
return payload;
|
||||||
@@ -671,6 +673,7 @@ export default function OrdersPage() {
|
|||||||
status: selectedStatuses(values.status).length ? values.status : initialStatuses,
|
status: selectedStatuses(values.status).length ? values.status : initialStatuses,
|
||||||
},
|
},
|
||||||
selectedRowKeys,
|
selectedRowKeys,
|
||||||
|
exportColumnKeys,
|
||||||
);
|
);
|
||||||
const result = await request<OrderExportResult>('/admin/orders/export', {
|
const result = await request<OrderExportResult>('/admin/orders/export', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -688,6 +691,7 @@ export default function OrdersPage() {
|
|||||||
const baseColumns: ColumnsType<AdminOrderRow> = [
|
const baseColumns: ColumnsType<AdminOrderRow> = [
|
||||||
{
|
{
|
||||||
title: '订单号',
|
title: '订单号',
|
||||||
|
key: '订单号',
|
||||||
dataIndex: 'orderNo',
|
dataIndex: 'orderNo',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
@@ -699,7 +703,7 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '用户',
|
title: '用户',
|
||||||
key: 'user',
|
key: '用户',
|
||||||
width: 200,
|
width: 200,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.user?.id ? (
|
row.user?.id ? (
|
||||||
@@ -712,7 +716,7 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '商品',
|
title: '商品',
|
||||||
key: 'productName',
|
key: '商品',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space size={4} wrap>
|
<Space size={4} wrap>
|
||||||
@@ -726,12 +730,14 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '规格',
|
title: '规格',
|
||||||
|
key: '规格',
|
||||||
dataIndex: 'productSpec',
|
dataIndex: 'productSpec',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (v: string | undefined) => v || '—',
|
render: (v: string | undefined) => v || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '数量',
|
title: '数量',
|
||||||
|
key: '数量',
|
||||||
dataIndex: 'quantity',
|
dataIndex: 'quantity',
|
||||||
width: 80,
|
width: 80,
|
||||||
render: (v: number | undefined, row) =>
|
render: (v: number | undefined, row) =>
|
||||||
@@ -739,12 +745,14 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '配送方式',
|
title: '配送方式',
|
||||||
|
key: '配送方式',
|
||||||
dataIndex: 'deliveryType',
|
dataIndex: 'deliveryType',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
|
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
|
key: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (s: string) => (
|
render: (s: string) => (
|
||||||
@@ -753,42 +761,47 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '实付',
|
title: '实付',
|
||||||
|
key: '实付',
|
||||||
dataIndex: 'payAmount',
|
dataIndex: 'payAmount',
|
||||||
width: 90,
|
width: 90,
|
||||||
render: (v: number) => `¥${v}`,
|
render: (v: number) => `¥${v}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '运费',
|
title: '运费',
|
||||||
key: 'logisticsFee',
|
key: '运费',
|
||||||
width: 90,
|
width: 90,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.delivery?.logisticsFee == null ? '—' : `¥${Number(row.delivery.logisticsFee).toFixed(2)}`,
|
row.delivery?.logisticsFee == null ? '—' : `¥${Number(row.delivery.logisticsFee).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '好客权益',
|
title: '好客权益',
|
||||||
|
key: '好客权益',
|
||||||
width: 200,
|
width: 200,
|
||||||
render: (_, row) => formatBenefitBrief(row),
|
render: (_, row) => formatBenefitBrief(row),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收货人',
|
title: '收货人',
|
||||||
|
key: '收货人',
|
||||||
dataIndex: 'receiverName',
|
dataIndex: 'receiverName',
|
||||||
width: 90,
|
width: 90,
|
||||||
render: (v: string | undefined) => v || '—',
|
render: (v: string | undefined) => v || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '电话',
|
title: '电话',
|
||||||
|
key: '电话',
|
||||||
dataIndex: 'receiverPhone',
|
dataIndex: 'receiverPhone',
|
||||||
width: 120,
|
width: 120,
|
||||||
render: (v: string | undefined) => v || '—',
|
render: (v: string | undefined) => v || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '地址',
|
title: '地址',
|
||||||
key: 'receiverAddress',
|
key: '地址',
|
||||||
width: 260,
|
width: 260,
|
||||||
render: (_, row) => formatReceiverAddress(row) || '—',
|
render: (_, row) => formatReceiverAddress(row) || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '下单时间',
|
title: '下单时间',
|
||||||
|
key: '下单时间',
|
||||||
dataIndex: 'createdAt',
|
dataIndex: 'createdAt',
|
||||||
width: 170,
|
width: 170,
|
||||||
render: fmtTime,
|
render: fmtTime,
|
||||||
@@ -823,7 +836,7 @@ export default function OrdersPage() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('orders', baseColumns, {
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('orders', baseColumns, {
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
@@ -14,6 +15,7 @@ import {
|
|||||||
Table,
|
Table,
|
||||||
Tabs,
|
Tabs,
|
||||||
Tag,
|
Tag,
|
||||||
|
Tooltip,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
@@ -22,6 +24,7 @@ import dayjs, { type Dayjs } from 'dayjs';
|
|||||||
import { request, type Paginated } from '../lib/api';
|
import { request, type Paginated } from '../lib/api';
|
||||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||||
|
import { appendExportColumns } from '../lib/export-columns';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
import { AdminListHeader } from '../components/AdminListHeader';
|
import { AdminListHeader } from '../components/AdminListHeader';
|
||||||
@@ -48,6 +51,7 @@ type Row = {
|
|||||||
redeemCommission: number;
|
redeemCommission: number;
|
||||||
totalAmount: number;
|
totalAmount: number;
|
||||||
status: string;
|
status: string;
|
||||||
|
billDate: string;
|
||||||
periodStart: string;
|
periodStart: string;
|
||||||
periodEnd: string;
|
periodEnd: string;
|
||||||
rejectReason?: string | null;
|
rejectReason?: string | null;
|
||||||
@@ -109,6 +113,7 @@ function weekMonday(d: Dayjs) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PartnerBillsPage() {
|
export default function PartnerBillsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const [partners, setPartners] = useState<PartnerOption[]>([]);
|
const [partners, setPartners] = useState<PartnerOption[]>([]);
|
||||||
@@ -263,6 +268,7 @@ export default function PartnerBillsPage() {
|
|||||||
if (filters.status) qs.set('status', filters.status);
|
if (filters.status) qs.set('status', filters.status);
|
||||||
if (filters.partnerId) qs.set('partnerId', filters.partnerId);
|
if (filters.partnerId) qs.set('partnerId', filters.partnerId);
|
||||||
if (filters.weekStartYmd) qs.set('weekStartYmd', filters.weekStartYmd);
|
if (filters.weekStartYmd) qs.set('weekStartYmd', filters.weekStartYmd);
|
||||||
|
appendExportColumns(qs, exportColumnKeys);
|
||||||
const result = await request<{ csv: string; count: number }>(`/admin/partner-bills/export?${qs}`);
|
const result = await request<{ csv: string; count: number }>(`/admin/partner-bills/export?${qs}`);
|
||||||
const suffix = filters.weekStartYmd || 'all';
|
const suffix = filters.weekStartYmd || 'all';
|
||||||
downloadExcelCsv(result.csv, `合伙人账单_${suffix}.csv`);
|
downloadExcelCsv(result.csv, `合伙人账单_${suffix}.csv`);
|
||||||
@@ -285,6 +291,7 @@ export default function PartnerBillsPage() {
|
|||||||
const baseColumns: ColumnsType<Row> = [
|
const baseColumns: ColumnsType<Row> = [
|
||||||
{
|
{
|
||||||
title: '账单号',
|
title: '账单号',
|
||||||
|
key: '账单号',
|
||||||
dataIndex: 'billNo',
|
dataIndex: 'billNo',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
@@ -293,29 +300,45 @@ export default function PartnerBillsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '合伙人',
|
title: '合伙人',
|
||||||
|
key: '合伙人',
|
||||||
width: 200,
|
width: 200,
|
||||||
render: (_, r) => partnerName(r),
|
render: (_, r) => partnerName(r),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<Tooltip title="周账出账日为账期结束后的下周一;历史月账为次月 1 日">
|
||||||
|
出账日
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
key: '出账日',
|
||||||
|
dataIndex: 'billDate',
|
||||||
|
width: 110,
|
||||||
|
render: (v) => String(v || '').slice(0, 10),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '账期',
|
title: '账期',
|
||||||
|
key: '账期',
|
||||||
width: 200,
|
width: 200,
|
||||||
render: (_, r) =>
|
render: (_, r) =>
|
||||||
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '酒单佣金',
|
title: '酒单佣金',
|
||||||
|
key: '酒单佣金',
|
||||||
dataIndex: 'orderCommission',
|
dataIndex: 'orderCommission',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '核销佣金',
|
title: '核销佣金',
|
||||||
|
key: '核销佣金',
|
||||||
dataIndex: 'redeemCommission',
|
dataIndex: 'redeemCommission',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '合计应付',
|
title: '合计应付',
|
||||||
|
key: '合计应付',
|
||||||
dataIndex: 'totalAmount',
|
dataIndex: 'totalAmount',
|
||||||
width: 130,
|
width: 130,
|
||||||
render: (v) =>
|
render: (v) =>
|
||||||
@@ -323,16 +346,19 @@ export default function PartnerBillsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收款户名',
|
title: '收款户名',
|
||||||
|
key: '收款户名',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (_, r) => partnerBank(r)?.bankAccountName || '—',
|
render: (_, r) => partnerBank(r)?.bankAccountName || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收款账号',
|
title: '收款账号',
|
||||||
|
key: '收款账号',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (_, r) => partnerBank(r)?.bankAccountNo || '—',
|
render: (_, r) => partnerBank(r)?.bankAccountNo || '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
|
key: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 130,
|
width: 130,
|
||||||
render: (s, row) => (
|
render: (s, row) => (
|
||||||
@@ -380,7 +406,7 @@ export default function PartnerBillsPage() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-partner-bills', baseColumns, { page, pageSize });
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-partner-bills', baseColumns, { page, pageSize });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -572,6 +598,7 @@ export default function PartnerBillsPage() {
|
|||||||
<Descriptions column={1} size="small" bordered>
|
<Descriptions column={1} size="small" bordered>
|
||||||
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
||||||
<Descriptions.Item label="合伙人">{partnerName(detail)}</Descriptions.Item>
|
<Descriptions.Item label="合伙人">{partnerName(detail)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="出账日">{String(detail.billDate || '').slice(0, 10)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="账期">
|
<Descriptions.Item label="账期">
|
||||||
{String(detail.periodStart).slice(0, 10)} ~ {String(detail.periodEnd).slice(0, 10)}
|
{String(detail.periodStart).slice(0, 10)} ~ {String(detail.periodEnd).slice(0, 10)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
@@ -610,7 +637,21 @@ export default function PartnerBillsPage() {
|
|||||||
pagination={false}
|
pagination={false}
|
||||||
dataSource={detail.orderItems ?? []}
|
dataSource={detail.orderItems ?? []}
|
||||||
columns={[
|
columns={[
|
||||||
{ title: '订单号', dataIndex: 'refNo', width: 160 },
|
{
|
||||||
|
title: '订单号',
|
||||||
|
dataIndex: 'refNo',
|
||||||
|
width: 160,
|
||||||
|
render: (v: string) =>
|
||||||
|
v ? (
|
||||||
|
<AdminPrimaryLink
|
||||||
|
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||||
|
>
|
||||||
|
{v}
|
||||||
|
</AdminPrimaryLink>
|
||||||
|
) : (
|
||||||
|
'—'
|
||||||
|
),
|
||||||
|
},
|
||||||
{ title: '商品', dataIndex: 'title' },
|
{ title: '商品', dataIndex: 'title' },
|
||||||
{ title: '数量', dataIndex: 'extra', width: 70 },
|
{ title: '数量', dataIndex: 'extra', width: 70 },
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
import { request, type Paginated } from '../lib/api';
|
import { request, type Paginated } from '../lib/api';
|
||||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||||
|
import { appendExportColumns } from '../lib/export-columns';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
import { AdminListHeader } from '../components/AdminListHeader';
|
import { AdminListHeader } from '../components/AdminListHeader';
|
||||||
@@ -44,6 +45,8 @@ type Row = {
|
|||||||
amount: number;
|
amount: number;
|
||||||
status: StoreSettlementStatus;
|
status: StoreSettlementStatus;
|
||||||
date: string;
|
date: string;
|
||||||
|
periodStart?: string | null;
|
||||||
|
periodEnd?: string | null;
|
||||||
overdue?: boolean;
|
overdue?: boolean;
|
||||||
redeemCount?: number | null;
|
redeemCount?: number | null;
|
||||||
redeemAmount?: number | null;
|
redeemAmount?: number | null;
|
||||||
@@ -198,6 +201,7 @@ export default function StoreBillsPage() {
|
|||||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||||
|
appendExportColumns(qs, exportColumnKeys);
|
||||||
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
||||||
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
||||||
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
||||||
@@ -218,6 +222,7 @@ export default function StoreBillsPage() {
|
|||||||
const baseColumns: ColumnsType<Row> = [
|
const baseColumns: ColumnsType<Row> = [
|
||||||
{
|
{
|
||||||
title: '类型',
|
title: '类型',
|
||||||
|
key: '类型',
|
||||||
dataIndex: 'kind',
|
dataIndex: 'kind',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (k: StoreSettlementKind) => (
|
render: (k: StoreSettlementKind) => (
|
||||||
@@ -228,6 +233,7 @@ export default function StoreBillsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '单号',
|
title: '单号',
|
||||||
|
key: '账单号',
|
||||||
dataIndex: 'billNo',
|
dataIndex: 'billNo',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
@@ -243,39 +249,58 @@ export default function StoreBillsPage() {
|
|||||||
出账日
|
出账日
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
),
|
),
|
||||||
|
key: '出账日',
|
||||||
dataIndex: 'date',
|
dataIndex: 'date',
|
||||||
width: 160,
|
width: 160,
|
||||||
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
|
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
|
||||||
},
|
},
|
||||||
{ title: '门店', dataIndex: ['store', 'name'], width: 140 },
|
{
|
||||||
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
title: (
|
||||||
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
<Tooltip title="T+1 账期为出账日前一日的核销窗口;手动提现无账期">
|
||||||
|
账期
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
key: '账期',
|
||||||
|
width: 200,
|
||||||
|
render: (_, row) =>
|
||||||
|
row.kind === 'T1_BILL' && row.periodStart
|
||||||
|
? `${row.periodStart} ~ ${row.periodEnd}`
|
||||||
|
: '—',
|
||||||
|
},
|
||||||
|
{ title: '门店', key: '门店', dataIndex: ['store', 'name'], width: 140 },
|
||||||
|
{ title: '登录手机', key: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||||
|
{ title: '城市', key: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||||
{
|
{
|
||||||
title: '收款户名',
|
title: '收款户名',
|
||||||
|
key: '收款户名',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountName || '—' : '—',
|
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountName || '—' : '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '收款账号',
|
title: '收款账号',
|
||||||
|
key: '收款账号',
|
||||||
width: 140,
|
width: 140,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountNo || '—' : '—',
|
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountNo || '—' : '—',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '笔数',
|
title: '笔数',
|
||||||
|
key: '笔数',
|
||||||
width: 80,
|
width: 80,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '应付金额',
|
title: '应付金额',
|
||||||
|
key: '应付金额',
|
||||||
dataIndex: 'amount',
|
dataIndex: 'amount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
|
key: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (s: string, row) => (
|
render: (s: string, row) => (
|
||||||
@@ -325,7 +350,7 @@ export default function StoreBillsPage() {
|
|||||||
}
|
}
|
||||||
| undefined;
|
| undefined;
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-store-bills', baseColumns, { page, pageSize });
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-store-bills', baseColumns, { page, pageSize });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -495,6 +520,11 @@ export default function StoreBillsPage() {
|
|||||||
<Descriptions.Item label="出账日">
|
<Descriptions.Item label="出账日">
|
||||||
{String(detail.billDate || '').slice(0, 10)}
|
{String(detail.billDate || '').slice(0, 10)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="账期">
|
||||||
|
{detail.periodStart
|
||||||
|
? `${String(detail.periodStart).slice(0, 10)} ~ ${String(detail.periodEnd || '').slice(0, 10)}`
|
||||||
|
: '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="应付">
|
<Descriptions.Item label="应付">
|
||||||
¥{Number(detail.payoutAmount ?? 0).toFixed(2)}
|
¥{Number(detail.payoutAmount ?? 0).toFixed(2)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
|||||||
@@ -224,6 +224,7 @@ type StoreRow = {
|
|||||||
settlementRate?: number;
|
settlementRate?: number;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
category?: { id: string; name: string; parentId?: string | null } | null;
|
category?: { id: string; name: string; parentId?: string | null } | null;
|
||||||
|
categories?: { id: string; name: string; parentId?: string | null }[] | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PartnerOption = { id: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
type PartnerOption = { id: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||||
@@ -350,29 +351,17 @@ export default function StoresPage() {
|
|||||||
const selectedPartnerId = Form.useWatch('partnerAccountId', createForm);
|
const selectedPartnerId = Form.useWatch('partnerAccountId', createForm);
|
||||||
const selectedRegionCodes = Form.useWatch('regionCodes', createForm);
|
const selectedRegionCodes = Form.useWatch('regionCodes', createForm);
|
||||||
const selectedCityId = Form.useWatch('cityId', createForm);
|
const selectedCityId = Form.useWatch('cityId', createForm);
|
||||||
const selectedCategoryParentId = Form.useWatch('categoryParentId', createForm);
|
const categoryLeafOptions = useMemo(() => {
|
||||||
const editCategoryParentId = Form.useWatch('categoryParentId', editForm);
|
const options: { value: string; label: string }[] = [];
|
||||||
|
for (const parent of categoryTree) {
|
||||||
const categoryParentOptions = useMemo(
|
if (parent.status === 'INACTIVE') continue;
|
||||||
() =>
|
for (const child of parent.children ?? []) {
|
||||||
categoryTree
|
if (child.status === 'INACTIVE') continue;
|
||||||
.filter((n) => n.status !== 'INACTIVE')
|
options.push({ value: child.id, label: `${parent.name} / ${child.name}` });
|
||||||
.map((n) => ({ value: n.id, label: n.name })),
|
}
|
||||||
[categoryTree],
|
}
|
||||||
);
|
return options;
|
||||||
const categoryChildOptions = useMemo(() => {
|
}, [categoryTree]);
|
||||||
const parent = categoryTree.find((n) => n.id === selectedCategoryParentId);
|
|
||||||
return (parent?.children ?? [])
|
|
||||||
.filter((n) => n.status !== 'INACTIVE')
|
|
||||||
.map((n) => ({ value: n.id, label: n.name }));
|
|
||||||
}, [categoryTree, selectedCategoryParentId]);
|
|
||||||
|
|
||||||
const editCategoryChildOptions = useMemo(() => {
|
|
||||||
const parent = categoryTree.find((n) => n.id === editCategoryParentId);
|
|
||||||
return (parent?.children ?? [])
|
|
||||||
.filter((n) => n.status !== 'INACTIVE')
|
|
||||||
.map((n) => ({ value: n.id, label: n.name }));
|
|
||||||
}, [categoryTree, editCategoryParentId]);
|
|
||||||
|
|
||||||
async function deleteStore(id: string) {
|
async function deleteStore(id: string) {
|
||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
@@ -414,20 +403,14 @@ export default function StoresPage() {
|
|||||||
bankBranch?: string | null;
|
bankBranch?: string | null;
|
||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
const categoryId = category?.id != null ? String(category.id) : undefined;
|
const categories = Array.isArray(d.categories)
|
||||||
let parentId = category?.parentId != null ? String(category.parentId) : undefined;
|
? (d.categories as { id?: string }[])
|
||||||
if (!parentId && categoryId) {
|
: [];
|
||||||
for (const parent of cats) {
|
const categoryIds = categories.length
|
||||||
if (parent.id === categoryId) {
|
? categories.map((c) => String(c.id)).filter(Boolean)
|
||||||
parentId = parent.id;
|
: category?.id != null
|
||||||
break;
|
? [String(category.id)]
|
||||||
}
|
: [];
|
||||||
if ((parent.children ?? []).some((c) => c.id === categoryId)) {
|
|
||||||
parentId = parent.id;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const loginPhone =
|
const loginPhone =
|
||||||
(typeof d.loginPhone === 'string' && d.loginPhone) ||
|
(typeof d.loginPhone === 'string' && d.loginPhone) ||
|
||||||
account?.phone ||
|
account?.phone ||
|
||||||
@@ -466,8 +449,7 @@ export default function StoresPage() {
|
|||||||
city: d.cityName,
|
city: d.cityName,
|
||||||
district: d.district,
|
district: d.district,
|
||||||
address: d.address,
|
address: d.address,
|
||||||
categoryParentId: parentId,
|
categoryIds,
|
||||||
categoryId,
|
|
||||||
latitude: d.latitude != null ? Number(d.latitude) : undefined,
|
latitude: d.latitude != null ? Number(d.latitude) : undefined,
|
||||||
longitude: d.longitude != null ? Number(d.longitude) : undefined,
|
longitude: d.longitude != null ? Number(d.longitude) : undefined,
|
||||||
settlementRate: d.settlementRate != null ? Number(d.settlementRate) * 100 : 60,
|
settlementRate: d.settlementRate != null ? Number(d.settlementRate) * 100 : 60,
|
||||||
@@ -530,7 +512,7 @@ export default function StoresPage() {
|
|||||||
!/^null$/i.test(v.benefitUsageRule.trim())
|
!/^null$/i.test(v.benefitUsageRule.trim())
|
||||||
? v.benefitUsageRule.trim()
|
? v.benefitUsageRule.trim()
|
||||||
: null,
|
: null,
|
||||||
categoryId: v.categoryId,
|
categoryIds: v.categoryIds,
|
||||||
province: v.province,
|
province: v.province,
|
||||||
city: v.city,
|
city: v.city,
|
||||||
district: v.district,
|
district: v.district,
|
||||||
@@ -661,8 +643,7 @@ export default function StoresPage() {
|
|||||||
'partnerAccountId',
|
'partnerAccountId',
|
||||||
'regionCodes',
|
'regionCodes',
|
||||||
'cityId',
|
'cityId',
|
||||||
'categoryParentId',
|
'categoryIds',
|
||||||
'categoryId',
|
|
||||||
'name',
|
'name',
|
||||||
'phone',
|
'phone',
|
||||||
'address',
|
'address',
|
||||||
@@ -691,7 +672,7 @@ export default function StoresPage() {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
partnerAccountId: values.partnerAccountId,
|
partnerAccountId: values.partnerAccountId,
|
||||||
cityId: values.cityId,
|
cityId: values.cityId,
|
||||||
categoryId: values.categoryId,
|
categoryIds: values.categoryIds,
|
||||||
province: values.province,
|
province: values.province,
|
||||||
city: values.city,
|
city: values.city,
|
||||||
name: values.name.trim(),
|
name: values.name.trim(),
|
||||||
@@ -769,8 +750,14 @@ export default function StoresPage() {
|
|||||||
{
|
{
|
||||||
key: 'category',
|
key: 'category',
|
||||||
title: '分类',
|
title: '分类',
|
||||||
width: 100,
|
width: 140,
|
||||||
render: (_, row) => row.category?.name || '—',
|
render: (_, row) => {
|
||||||
|
const cats = Array.isArray(row.categories)
|
||||||
|
? row.categories.map((c: { name?: string }) => c.name).filter(Boolean)
|
||||||
|
: [];
|
||||||
|
if (cats.length) return cats.join('、');
|
||||||
|
return row.category?.name || '—';
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{ key: 'cityName', title: '城市', dataIndex: 'cityName', width: 80 },
|
{ key: 'cityName', title: '城市', dataIndex: 'cityName', width: 80 },
|
||||||
{ key: 'phone', title: '登录号', dataIndex: 'phone', width: 120 },
|
{ key: 'phone', title: '登录号', dataIndex: 'phone', width: 120 },
|
||||||
@@ -1156,29 +1143,17 @@ export default function StoresPage() {
|
|||||||
<Input placeholder="手机号或座机,如 0379-8888888" />
|
<Input placeholder="手机号或座机,如 0379-8888888" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="categoryParentId"
|
name="categoryIds"
|
||||||
label="门店分类(大类)"
|
label="门店分类(细类,可多选)"
|
||||||
rules={[{ required: true, message: '请选择门店大类' }]}
|
rules={[{ required: true, message: '请至少选择一个门店细类' }]}
|
||||||
>
|
>
|
||||||
<Select
|
<Select
|
||||||
|
mode="multiple"
|
||||||
showSearch
|
showSearch
|
||||||
loading={optionsLoading}
|
loading={optionsLoading}
|
||||||
optionFilterProp="label"
|
optionFilterProp="label"
|
||||||
options={categoryParentOptions}
|
placeholder="选择细类,可多选"
|
||||||
onChange={() => editForm.setFieldValue('categoryId', undefined)}
|
options={categoryLeafOptions}
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="categoryId"
|
|
||||||
label="门店分类(细类)"
|
|
||||||
rules={[{ required: true, message: '请选择门店细类' }]}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
showSearch
|
|
||||||
optionFilterProp="label"
|
|
||||||
placeholder={editCategoryParentId ? '选择细类' : '请先选大类'}
|
|
||||||
disabled={!editCategoryParentId}
|
|
||||||
options={editCategoryChildOptions}
|
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="coverUrl" label="封面图 / 门头照">
|
<Form.Item name="coverUrl" label="封面图 / 门头照">
|
||||||
@@ -1457,23 +1432,9 @@ export default function StoresPage() {
|
|||||||
<Form.Item name="district" hidden><Input /></Form.Item>
|
<Form.Item name="district" hidden><Input /></Form.Item>
|
||||||
<Form.Item name="districtCode" hidden><Input /></Form.Item>
|
<Form.Item name="districtCode" hidden><Input /></Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="categoryParentId"
|
name="categoryIds"
|
||||||
label="门店分类(大类)"
|
label="门店分类(细类,可多选)"
|
||||||
rules={[{ required: true, message: '请选择门店大类' }]}
|
rules={[{ required: true, message: '请至少选择一个门店细类' }]}
|
||||||
>
|
|
||||||
<Select
|
|
||||||
showSearch
|
|
||||||
loading={optionsLoading}
|
|
||||||
optionFilterProp="label"
|
|
||||||
placeholder={optionsLoading ? '加载中…' : '选择大类'}
|
|
||||||
options={categoryParentOptions}
|
|
||||||
onChange={() => createForm.setFieldValue('categoryId', undefined)}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="categoryId"
|
|
||||||
label="门店分类(细类)"
|
|
||||||
rules={[{ required: true, message: '请选择门店细类' }]}
|
|
||||||
extra={
|
extra={
|
||||||
<Typography.Link onClick={() => navigate('/store-categories')}>
|
<Typography.Link onClick={() => navigate('/store-categories')}>
|
||||||
去配置门店分类
|
去配置门店分类
|
||||||
@@ -1481,11 +1442,12 @@ export default function StoresPage() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Select
|
<Select
|
||||||
|
mode="multiple"
|
||||||
showSearch
|
showSearch
|
||||||
|
loading={optionsLoading}
|
||||||
optionFilterProp="label"
|
optionFilterProp="label"
|
||||||
placeholder={selectedCategoryParentId ? '选择细类' : '请先选大类'}
|
placeholder={optionsLoading ? '加载中…' : '选择细类,可多选'}
|
||||||
disabled={!selectedCategoryParentId}
|
options={categoryLeafOptions}
|
||||||
options={categoryChildOptions}
|
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="name" label="门店名称" rules={[{ required: true, message: '请填写门店名称' }]}>
|
<Form.Item name="name" label="门店名称" rules={[{ required: true, message: '请填写门店名称' }]}>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
@@ -26,6 +27,7 @@ import {
|
|||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||||
|
import { appendExportColumns } from '../lib/export-columns';
|
||||||
import { request, type HqProfile } from '../lib/api';
|
import { request, type HqProfile } from '../lib/api';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
@@ -37,6 +39,8 @@ type Row = {
|
|||||||
id: string;
|
id: string;
|
||||||
billNo: string;
|
billNo: string;
|
||||||
billDate: string;
|
billDate: string;
|
||||||
|
periodStart: string;
|
||||||
|
periodEnd: string;
|
||||||
orderCount: number;
|
orderCount: number;
|
||||||
orderAmount: number;
|
orderAmount: number;
|
||||||
wineryRate: number;
|
wineryRate: number;
|
||||||
@@ -107,6 +111,7 @@ const WINERY_BANK_KEYS = [
|
|||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export default function WineryBillsPage() {
|
export default function WineryBillsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [bankForm] = Form.useForm<Record<string, string>>();
|
const [bankForm] = Form.useForm<Record<string, string>>();
|
||||||
const [reconcileForm] = Form.useForm<{ range?: [Dayjs, Dayjs] }>();
|
const [reconcileForm] = Form.useForm<{ range?: [Dayjs, Dayjs] }>();
|
||||||
@@ -196,6 +201,7 @@ export default function WineryBillsPage() {
|
|||||||
if (filters.month) qs.set('month', filters.month);
|
if (filters.month) qs.set('month', filters.month);
|
||||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||||
|
appendExportColumns(qs, exportColumnKeys);
|
||||||
const result = await request<{ csv: string; count: number }>(`/admin/winery-bills/export?${qs}`);
|
const result = await request<{ csv: string; count: number }>(`/admin/winery-bills/export?${qs}`);
|
||||||
const suffix = filters.year && filters.month ? `${filters.year}-${filters.month}` : 'all';
|
const suffix = filters.year && filters.month ? `${filters.year}-${filters.month}` : 'all';
|
||||||
downloadExcelCsv(result.csv, `酒厂对账单_${suffix}.csv`);
|
downloadExcelCsv(result.csv, `酒厂对账单_${suffix}.csv`);
|
||||||
@@ -275,6 +281,7 @@ export default function WineryBillsPage() {
|
|||||||
const baseColumns: ColumnsType<Row> = [
|
const baseColumns: ColumnsType<Row> = [
|
||||||
{
|
{
|
||||||
title: '账单号',
|
title: '账单号',
|
||||||
|
key: '账单号',
|
||||||
dataIndex: 'billNo',
|
dataIndex: 'billNo',
|
||||||
width: 170,
|
width: 170,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
@@ -284,34 +291,49 @@ export default function WineryBillsPage() {
|
|||||||
{
|
{
|
||||||
title: (
|
title: (
|
||||||
<Tooltip title="出账当天的北京日历日;T+3 只决定纳入哪天完成的订单">
|
<Tooltip title="出账当天的北京日历日;T+3 只决定纳入哪天完成的订单">
|
||||||
账单日
|
出账日
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
),
|
),
|
||||||
|
key: '出账日',
|
||||||
dataIndex: 'billDate',
|
dataIndex: 'billDate',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => String(v || '').slice(0, 10),
|
render: (v) => String(v || '').slice(0, 10),
|
||||||
},
|
},
|
||||||
{ title: '订单数', dataIndex: 'orderCount', width: 80 },
|
|
||||||
{
|
{
|
||||||
title: '酒单实付合计',
|
title: (
|
||||||
|
<Tooltip title="纳入本账单的订单完成日区间(含起止日)">
|
||||||
|
账期
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
key: '账期',
|
||||||
|
width: 200,
|
||||||
|
render: (_, row) => `${row.periodStart} ~ ${row.periodEnd}`,
|
||||||
|
},
|
||||||
|
{ title: '订单数', key: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||||
|
{
|
||||||
|
title: '订单总额',
|
||||||
|
key: '订单总额',
|
||||||
dataIndex: 'orderAmount',
|
dataIndex: 'orderAmount',
|
||||||
width: 120,
|
width: 120,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '酒厂比例',
|
title: '酒厂比例',
|
||||||
|
key: '酒厂比例',
|
||||||
dataIndex: 'wineryRate',
|
dataIndex: 'wineryRate',
|
||||||
width: 90,
|
width: 90,
|
||||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '应付',
|
title: '应付',
|
||||||
|
key: '应付',
|
||||||
dataIndex: 'wineryAmount',
|
dataIndex: 'wineryAmount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
|
key: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (s, row) => {
|
render: (s, row) => {
|
||||||
@@ -338,7 +360,7 @@ export default function WineryBillsPage() {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-winery-bills', baseColumns, { page, pageSize });
|
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-winery-bills', baseColumns, { page, pageSize });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -365,7 +387,7 @@ export default function WineryBillsPage() {
|
|||||||
<Card size="small" style={{ marginBottom: 16 }}>
|
<Card size="small" style={{ marginBottom: 16 }}>
|
||||||
<Space size="large" wrap>
|
<Space size="large" wrap>
|
||||||
<Statistic title="账单数" value={summary.count} />
|
<Statistic title="账单数" value={summary.count} />
|
||||||
<Statistic title="酒单实付合计" value={summary.orderAmount ?? 0} prefix="¥" precision={2} />
|
<Statistic title="订单总额" value={summary.orderAmount ?? 0} prefix="¥" precision={2} />
|
||||||
<Statistic title="应付合计" value={summary.wineryAmount ?? 0} prefix="¥" precision={2} />
|
<Statistic title="应付合计" value={summary.wineryAmount ?? 0} prefix="¥" precision={2} />
|
||||||
</Space>
|
</Space>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -460,7 +482,10 @@ export default function WineryBillsPage() {
|
|||||||
<>
|
<>
|
||||||
<Descriptions column={1} size="small" bordered>
|
<Descriptions column={1} size="small" bordered>
|
||||||
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
||||||
<Descriptions.Item label="账单日">{String(detail.billDate).slice(0, 10)}</Descriptions.Item>
|
<Descriptions.Item label="出账日">{String(detail.billDate).slice(0, 10)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="账期">
|
||||||
|
{detail.periodStart} ~ {detail.periodEnd}
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="应付">¥{Number(detail.wineryAmount).toFixed(2)}</Descriptions.Item>
|
<Descriptions.Item label="应付">¥{Number(detail.wineryAmount).toFixed(2)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="状态">
|
<Descriptions.Item label="状态">
|
||||||
{displayWineryStatus(detail.status, detail.wineryAmount).label}
|
{displayWineryStatus(detail.status, detail.wineryAmount).label}
|
||||||
@@ -500,7 +525,20 @@ export default function WineryBillsPage() {
|
|||||||
pagination={false}
|
pagination={false}
|
||||||
dataSource={detail.items ?? []}
|
dataSource={detail.items ?? []}
|
||||||
columns={[
|
columns={[
|
||||||
{ title: '订单号', dataIndex: 'orderNo' },
|
{
|
||||||
|
title: '订单号',
|
||||||
|
dataIndex: 'orderNo',
|
||||||
|
render: (v: string) =>
|
||||||
|
v ? (
|
||||||
|
<AdminPrimaryLink
|
||||||
|
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||||
|
>
|
||||||
|
{v}
|
||||||
|
</AdminPrimaryLink>
|
||||||
|
) : (
|
||||||
|
'—'
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '配送',
|
title: '配送',
|
||||||
dataIndex: 'deliveryType',
|
dataIndex: 'deliveryType',
|
||||||
|
|||||||
@@ -25,7 +25,10 @@ export type StoreDraftForm = {
|
|||||||
/** 人均费用(选填) */
|
/** 人均费用(选填) */
|
||||||
avgPrice: string;
|
avgPrice: string;
|
||||||
categoryParentId: string;
|
categoryParentId: string;
|
||||||
|
/** @deprecated 使用 categoryIds */
|
||||||
categoryId: string;
|
categoryId: string;
|
||||||
|
/** 二级分类多选 */
|
||||||
|
categoryIds: string[];
|
||||||
intro: string;
|
intro: string;
|
||||||
/** 好客权益券使用规则 */
|
/** 好客权益券使用规则 */
|
||||||
benefitUsageRule: string;
|
benefitUsageRule: string;
|
||||||
@@ -68,6 +71,7 @@ export const defaultStoreForm = (): StoreDraftForm => ({
|
|||||||
avgPrice: '',
|
avgPrice: '',
|
||||||
categoryParentId: '',
|
categoryParentId: '',
|
||||||
categoryId: '',
|
categoryId: '',
|
||||||
|
categoryIds: [],
|
||||||
intro: '',
|
intro: '',
|
||||||
benefitUsageRule: '',
|
benefitUsageRule: '',
|
||||||
coverUrl: '',
|
coverUrl: '',
|
||||||
@@ -122,6 +126,20 @@ export function normalizeStoreDraftForm(raw: Partial<StoreDraftForm> | null | un
|
|||||||
openTime2: String(raw.openTime2 ?? base.openTime2),
|
openTime2: String(raw.openTime2 ?? base.openTime2),
|
||||||
closeTime2: String(raw.closeTime2 ?? base.closeTime2),
|
closeTime2: String(raw.closeTime2 ?? base.closeTime2),
|
||||||
avgPrice: String(raw.avgPrice ?? base.avgPrice),
|
avgPrice: String(raw.avgPrice ?? base.avgPrice),
|
||||||
|
categoryIds: (() => {
|
||||||
|
if (Array.isArray(raw.categoryIds) && raw.categoryIds.length) {
|
||||||
|
return raw.categoryIds.map(String).filter(Boolean);
|
||||||
|
}
|
||||||
|
const legacy = String(raw.categoryId ?? '').trim();
|
||||||
|
return legacy ? [legacy] : base.categoryIds;
|
||||||
|
})(),
|
||||||
|
categoryId: (() => {
|
||||||
|
const ids = Array.isArray(raw.categoryIds) && raw.categoryIds.length
|
||||||
|
? raw.categoryIds.map(String).filter(Boolean)
|
||||||
|
: [];
|
||||||
|
if (ids.length) return ids[0];
|
||||||
|
return String(raw.categoryId ?? base.categoryId);
|
||||||
|
})(),
|
||||||
envPhotoUrls: normalizeStringArray(raw.envPhotoUrls, MIN_ENV_PHOTO_COUNT),
|
envPhotoUrls: normalizeStringArray(raw.envPhotoUrls, MIN_ENV_PHOTO_COUNT),
|
||||||
// 兼容旧草稿:单个 contractUrl 迁移为数组
|
// 兼容旧草稿:单个 contractUrl 迁移为数组
|
||||||
contractUrls: (() => {
|
contractUrls: (() => {
|
||||||
@@ -201,7 +219,7 @@ export function validateStoreStep1(
|
|||||||
| 'openTime2'
|
| 'openTime2'
|
||||||
| 'closeTime2'
|
| 'closeTime2'
|
||||||
| 'avgPrice'
|
| 'avgPrice'
|
||||||
| 'categoryId'
|
| 'categoryIds'
|
||||||
| 'intro'
|
| 'intro'
|
||||||
| 'benefitUsageRule'
|
| 'benefitUsageRule'
|
||||||
>,
|
>,
|
||||||
@@ -233,7 +251,7 @@ export function validateStoreStep1(
|
|||||||
const n = Number(form.avgPrice);
|
const n = Number(form.avgPrice);
|
||||||
if (Number.isNaN(n) || n < 0) return '人均费用须为非负数字';
|
if (Number.isNaN(n) || n < 0) return '人均费用须为非负数字';
|
||||||
}
|
}
|
||||||
if (!form.categoryId.trim()) return '请选择店铺类型';
|
if (!form.categoryIds?.length) return '请至少选择一个店铺类型';
|
||||||
if (form.intro.trim()) {
|
if (form.intro.trim()) {
|
||||||
const len = form.intro.trim().length;
|
const len = form.intro.trim().length;
|
||||||
if (len < 2 || len > 500) return '门店简介须为 2~500 字';
|
if (len < 2 || len > 500) return '门店简介须为 2~500 字';
|
||||||
|
|||||||
@@ -206,9 +206,9 @@ export default function StoreCreatePage() {
|
|||||||
.then((list) => {
|
.then((list) => {
|
||||||
const tree = Array.isArray(list) ? list : [];
|
const tree = Array.isArray(list) ? list : [];
|
||||||
setCategoryTree(tree);
|
setCategoryTree(tree);
|
||||||
if (form.categoryId && !form.categoryParentId) {
|
if (form.categoryIds.length && !form.categoryParentId) {
|
||||||
const parent = tree.find((root) =>
|
const parent = tree.find((root) =>
|
||||||
(root.children ?? []).some((child) => child.id === form.categoryId),
|
(root.children ?? []).some((child) => form.categoryIds.includes(child.id)),
|
||||||
);
|
);
|
||||||
if (parent) patchForm({ categoryParentId: parent.id });
|
if (parent) patchForm({ categoryParentId: parent.id });
|
||||||
}
|
}
|
||||||
@@ -216,12 +216,6 @@ export default function StoreCreatePage() {
|
|||||||
.catch(() => setCategoryTree([]));
|
.catch(() => setCategoryTree([]));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const categoryChildren = useMemo(() => {
|
|
||||||
const parent = categoryTree.find((item) => item.id === form.categoryParentId);
|
|
||||||
return Array.isArray(parent?.children) ? parent!.children! : [];
|
|
||||||
}, [categoryTree, form.categoryParentId]);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
||||||
@@ -523,7 +517,8 @@ export default function StoreCreatePage() {
|
|||||||
|
|
||||||
...(form.avgPrice.trim() ? { avgPrice: Number(form.avgPrice) } : {}),
|
...(form.avgPrice.trim() ? { avgPrice: Number(form.avgPrice) } : {}),
|
||||||
|
|
||||||
categoryId: form.categoryId.trim(),
|
categoryIds: form.categoryIds,
|
||||||
|
categoryId: form.categoryIds[0] || form.categoryId.trim(),
|
||||||
|
|
||||||
intro: form.intro.trim() || undefined,
|
intro: form.intro.trim() || undefined,
|
||||||
benefitUsageRule: form.benefitUsageRule.trim() || undefined,
|
benefitUsageRule: form.benefitUsageRule.trim() || undefined,
|
||||||
@@ -690,56 +685,40 @@ export default function StoreCreatePage() {
|
|||||||
|
|
||||||
<div className="partner-field">
|
<div className="partner-field">
|
||||||
|
|
||||||
<label>店铺类型 <span className="text-primary">*</span></label>
|
<label>店铺类型 <span className="text-primary">*</span> <span className="label-md text-muted">(可多选)</span></label>
|
||||||
|
|
||||||
<div className="partner-input-row" style={{ gap: 8 }}>
|
|
||||||
|
|
||||||
<select
|
|
||||||
|
|
||||||
className="partner-field-input partner-field-input--block"
|
|
||||||
|
|
||||||
value={form.categoryParentId}
|
|
||||||
|
|
||||||
onChange={(e) => patchForm({ categoryParentId: e.target.value, categoryId: '' })}
|
|
||||||
|
|
||||||
aria-label="一级店铺类型"
|
|
||||||
|
|
||||||
>
|
|
||||||
|
|
||||||
<option value="">选择大类</option>
|
|
||||||
|
|
||||||
{categoryTree.map((item) => (
|
|
||||||
|
|
||||||
<option key={item.id} value={item.id}>{item.name}</option>
|
|
||||||
|
|
||||||
))}
|
|
||||||
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<select
|
|
||||||
|
|
||||||
className="partner-field-input partner-field-input--block"
|
|
||||||
|
|
||||||
value={form.categoryId}
|
|
||||||
|
|
||||||
onChange={(e) => patchForm({ categoryId: e.target.value })}
|
|
||||||
|
|
||||||
disabled={!form.categoryParentId}
|
|
||||||
|
|
||||||
aria-label="二级店铺类型"
|
|
||||||
|
|
||||||
>
|
|
||||||
|
|
||||||
<option value="">{form.categoryParentId ? '选择细类' : '请先选大类'}</option>
|
|
||||||
|
|
||||||
{categoryChildren.map((item) => (
|
|
||||||
|
|
||||||
<option key={item.id} value={item.id}>{item.name}</option>
|
|
||||||
|
|
||||||
))}
|
|
||||||
|
|
||||||
</select>
|
|
||||||
|
|
||||||
|
<div className="partner-category-multi">
|
||||||
|
{categoryTree.map((parent) => (
|
||||||
|
<div key={parent.id} className="partner-category-group">
|
||||||
|
<div className="partner-category-group-title">{parent.name}</div>
|
||||||
|
<div className="partner-category-options">
|
||||||
|
{(parent.children ?? []).map((child) => {
|
||||||
|
const checked = form.categoryIds.includes(child.id);
|
||||||
|
return (
|
||||||
|
<label key={child.id} className="partner-category-option">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
onChange={() => {
|
||||||
|
const next = checked
|
||||||
|
? form.categoryIds.filter((id) => id !== child.id)
|
||||||
|
: [...form.categoryIds, child.id];
|
||||||
|
patchForm({
|
||||||
|
categoryIds: next,
|
||||||
|
categoryId: next[0] ?? '',
|
||||||
|
categoryParentId: next.length
|
||||||
|
? parent.id
|
||||||
|
: form.categoryParentId,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span>{child.name}</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@dukang/mini-user",
|
"name": "@dukang/mini-user",
|
||||||
"version": "4.0.4",
|
"version": "4.0.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export function storeCategoryTags(
|
|||||||
tags?: unknown;
|
tags?: unknown;
|
||||||
categoryId?: string | null;
|
categoryId?: string | null;
|
||||||
category?: StoreCategoryLike | null;
|
category?: StoreCategoryLike | null;
|
||||||
|
categories?: StoreCategoryLike[] | null;
|
||||||
},
|
},
|
||||||
tree: StoreCategoryTreeNode[] = [],
|
tree: StoreCategoryTreeNode[] = [],
|
||||||
): string[] {
|
): string[] {
|
||||||
@@ -30,24 +31,125 @@ export function storeCategoryTags(
|
|||||||
: [];
|
: [];
|
||||||
if (fromJson.length) return fromJson;
|
if (fromJson.length) return fromJson;
|
||||||
|
|
||||||
const names: string[] = [];
|
const multi = Array.isArray(store.categories) ? store.categories : [];
|
||||||
const childName = String(store.category?.name || '').trim();
|
if (multi.length) {
|
||||||
const parentName = String(store.category?.parent?.name || '').trim();
|
return groupCategoryTags(multi, tree);
|
||||||
if (parentName) names.push(parentName);
|
}
|
||||||
if (childName && childName !== parentName) names.push(childName);
|
|
||||||
|
|
||||||
const storeCatId = String(store.categoryId || store.category?.id || '');
|
if (store.category || store.categoryId) {
|
||||||
const storeParentId = String(store.category?.parentId || '');
|
const grouped = groupCategoryTags(
|
||||||
for (const root of tree) {
|
store.category ? [store.category] : [],
|
||||||
if (root.id === storeParentId || root.id === storeCatId) {
|
tree,
|
||||||
if (root.name && !names.includes(root.name)) names.unshift(root.name);
|
store.categoryId,
|
||||||
}
|
);
|
||||||
for (const child of root.children ?? []) {
|
if (grouped.length) return grouped;
|
||||||
if (child.id === storeCatId) {
|
}
|
||||||
if (root.name && !names.includes(root.name)) names.unshift(root.name);
|
|
||||||
if (child.name && !names.includes(child.name)) names.push(child.name);
|
const storeCatId = String(store.categoryId || '');
|
||||||
|
if (storeCatId) {
|
||||||
|
for (const root of tree) {
|
||||||
|
for (const child of root.children ?? []) {
|
||||||
|
if (child.id === storeCatId) {
|
||||||
|
return [`${root.name}|${child.name}`];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return names;
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按大类分组:餐饮|火锅·江浙菜、娱乐|KTV */
|
||||||
|
function groupCategoryTags(
|
||||||
|
categories: StoreCategoryLike[],
|
||||||
|
tree: StoreCategoryTreeNode[] = [],
|
||||||
|
fallbackCategoryId?: string | null,
|
||||||
|
): string[] {
|
||||||
|
if (!categories.length && fallbackCategoryId) {
|
||||||
|
return groupCategoryTags([{ id: String(fallbackCategoryId) }], tree);
|
||||||
|
}
|
||||||
|
|
||||||
|
const groups = new Map<string, { parentName: string; children: string[] }>();
|
||||||
|
const order: string[] = [];
|
||||||
|
|
||||||
|
for (const cat of categories) {
|
||||||
|
const resolved = resolveCategoryParts(cat, tree);
|
||||||
|
if (!resolved) continue;
|
||||||
|
const { parentKey, parentName, childName } = resolved;
|
||||||
|
if (!groups.has(parentKey)) {
|
||||||
|
groups.set(parentKey, { parentName, children: [] });
|
||||||
|
order.push(parentKey);
|
||||||
|
}
|
||||||
|
const group = groups.get(parentKey)!;
|
||||||
|
if (childName && childName !== parentName && !group.children.includes(childName)) {
|
||||||
|
group.children.push(childName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return order
|
||||||
|
.map((key) => {
|
||||||
|
const group = groups.get(key)!;
|
||||||
|
if (group.parentName && group.children.length) {
|
||||||
|
return `${group.parentName}|${group.children.join('·')}`;
|
||||||
|
}
|
||||||
|
if (group.children.length) return group.children.join('·');
|
||||||
|
return group.parentName;
|
||||||
|
})
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveCategoryParts(
|
||||||
|
cat: StoreCategoryLike,
|
||||||
|
tree: StoreCategoryTreeNode[] = [],
|
||||||
|
): { parentKey: string; parentName: string; childName: string } | null {
|
||||||
|
const childName = String(cat.name || '').trim();
|
||||||
|
let parentName = String(cat.parent?.name || '').trim();
|
||||||
|
const catId = String(cat.id || '');
|
||||||
|
const parentId = String(cat.parentId || '');
|
||||||
|
|
||||||
|
if (!parentName && (parentId || catId)) {
|
||||||
|
for (const root of tree) {
|
||||||
|
if (parentId && root.id === parentId) {
|
||||||
|
parentName = root.name;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for (const child of root.children ?? []) {
|
||||||
|
if (catId && child.id === catId) {
|
||||||
|
parentName = root.name;
|
||||||
|
if (!childName) return { parentKey: root.id, parentName, childName: child.name };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!childName && !parentName) return null;
|
||||||
|
|
||||||
|
const parentKey = parentId || parentName || catId;
|
||||||
|
if (!parentName && catId) {
|
||||||
|
for (const root of tree) {
|
||||||
|
for (const child of root.children ?? []) {
|
||||||
|
if (child.id === catId) {
|
||||||
|
return { parentKey: root.id, parentName: root.name, childName: child.name };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
parentKey,
|
||||||
|
parentName: parentName || childName,
|
||||||
|
childName: childName || parentName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function storeLeafCategoryIds(store: {
|
||||||
|
categoryId?: string | null;
|
||||||
|
category?: StoreCategoryLike | null;
|
||||||
|
categories?: StoreCategoryLike[] | null;
|
||||||
|
}): string[] {
|
||||||
|
if (Array.isArray(store.categories) && store.categories.length) {
|
||||||
|
return store.categories.map((c) => String(c.id || '')).filter(Boolean);
|
||||||
|
}
|
||||||
|
const id = String(store.categoryId || store.category?.id || '');
|
||||||
|
return id ? [id] : [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ type StoresSession = {
|
|||||||
cache: StoresListCache | null;
|
cache: StoresListCache | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STORAGE_KEY = 'dukang_stores_session_v2';
|
const STORAGE_KEY = 'dukang_stores_session_v3';
|
||||||
|
|
||||||
let memory: StoresSession | null = null;
|
let memory: StoresSession | null = null;
|
||||||
|
|
||||||
|
|||||||
@@ -79,6 +79,12 @@ type Store = {
|
|||||||
parentId?: string | null;
|
parentId?: string | null;
|
||||||
parent?: { name?: string } | null;
|
parent?: { name?: string } | null;
|
||||||
} | null;
|
} | null;
|
||||||
|
categories?: {
|
||||||
|
id?: string;
|
||||||
|
name?: string;
|
||||||
|
parentId?: string | null;
|
||||||
|
parent?: { name?: string } | null;
|
||||||
|
}[] | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type RecentRedeem = {
|
type RecentRedeem = {
|
||||||
@@ -406,12 +412,15 @@ export default function StoreDetailPage() {
|
|||||||
|
|
||||||
<View className="store-detail-title-row">
|
<View className="store-detail-title-row">
|
||||||
<Text className="store-detail-name">{store.name}</Text>
|
<Text className="store-detail-name">{store.name}</Text>
|
||||||
{storeCategoryTags(store, categoryTree).map((tag) => (
|
|
||||||
<Text key={tag} className="store-detail-tag">
|
|
||||||
{tag}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
</View>
|
</View>
|
||||||
|
{(() => {
|
||||||
|
const categoryLabels = storeCategoryTags(store, categoryTree);
|
||||||
|
return categoryLabels.length ? (
|
||||||
|
<View className="store-detail-tags-row">
|
||||||
|
<Text className="store-detail-category-line">{categoryLabels.join('、')}</Text>
|
||||||
|
</View>
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
<View className="store-detail-rating-row">
|
<View className="store-detail-rating-row">
|
||||||
<View className="store-detail-stars">
|
<View className="store-detail-stars">
|
||||||
{[1, 2, 3, 4, 5].map((n) => (
|
{[1, 2, 3, 4, 5].map((n) => (
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ import {
|
|||||||
toWeappShareTimeline,
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import BenefitSloganBar from '../../components/BenefitSloganBar';
|
import BenefitSloganBar from '../../components/BenefitSloganBar';
|
||||||
import { storeCategoryTags, storeStarCount } from '../../lib/store-display';
|
import { storeCategoryTags, storeLeafCategoryIds, storeStarCount } from '../../lib/store-display';
|
||||||
import openBadgeImg from '../../assets/icons/store-open-badge.png';
|
import openBadgeImg from '../../assets/icons/store-open-badge.png';
|
||||||
|
|
||||||
type Store = {
|
type Store = {
|
||||||
@@ -66,6 +66,12 @@ type Store = {
|
|||||||
parentId?: string | null;
|
parentId?: string | null;
|
||||||
parent?: { name?: string } | null;
|
parent?: { name?: string } | null;
|
||||||
} | null;
|
} | null;
|
||||||
|
categories?: {
|
||||||
|
id?: string;
|
||||||
|
name?: string;
|
||||||
|
parentId?: string | null;
|
||||||
|
parent?: { name?: string } | null;
|
||||||
|
}[] | null;
|
||||||
tags?: unknown;
|
tags?: unknown;
|
||||||
rating?: number | string | null;
|
rating?: number | string | null;
|
||||||
latitude?: number | string | null;
|
latitude?: number | string | null;
|
||||||
@@ -288,14 +294,21 @@ export default function StoresPage() {
|
|||||||
|
|
||||||
function matchesCategory(store: Store): boolean {
|
function matchesCategory(store: Store): boolean {
|
||||||
if (!category.parentId) return true;
|
if (!category.parentId) return true;
|
||||||
const storeCatId = String(store.categoryId || store.category?.id || '');
|
const leafIds = storeLeafCategoryIds(store);
|
||||||
const storeParentId = String(store.category?.parentId || '');
|
const parentIds = new Set<string>();
|
||||||
if (category.childId) {
|
if (Array.isArray(store.categories)) {
|
||||||
return storeCatId === category.childId;
|
for (const cat of store.categories) {
|
||||||
|
if (cat.parentId) parentIds.add(String(cat.parentId));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (storeParentId && storeParentId === category.parentId) return true;
|
const legacyParent = String(store.category?.parentId || '');
|
||||||
|
if (legacyParent) parentIds.add(legacyParent);
|
||||||
|
if (category.childId) {
|
||||||
|
return leafIds.includes(category.childId);
|
||||||
|
}
|
||||||
|
if ([...parentIds].some((id) => id === category.parentId)) return true;
|
||||||
const siblings = childIdsByParent.get(category.parentId) ?? [];
|
const siblings = childIdsByParent.get(category.parentId) ?? [];
|
||||||
return siblings.includes(storeCatId);
|
return leafIds.some((id) => siblings.includes(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
@@ -461,14 +474,10 @@ export default function StoresPage() {
|
|||||||
<Text className="store-card-name">{s.name}</Text>
|
<Text className="store-card-name">{s.name}</Text>
|
||||||
</View>
|
</View>
|
||||||
{(() => {
|
{(() => {
|
||||||
const tags = storeCategoryTags(s, categoryTree);
|
const categoryLabels = storeCategoryTags(s, categoryTree);
|
||||||
return tags.length ? (
|
return categoryLabels.length ? (
|
||||||
<View className="store-card-tags">
|
<View className="store-card-category-wrap">
|
||||||
{tags.map((tag) => (
|
<Text className="store-card-category-text">{categoryLabels.join('、')}</Text>
|
||||||
<Text key={tag} className="store-card-tag">
|
|
||||||
{tag}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
</View>
|
</View>
|
||||||
) : null;
|
) : null;
|
||||||
})()}
|
})()}
|
||||||
|
|||||||
@@ -100,6 +100,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-title-row {
|
.store-detail-title-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-tags-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -107,6 +113,20 @@
|
|||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.store-detail-category-line {
|
||||||
|
display: inline-block;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: rgba(166, 29, 36, 0.1);
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 16px;
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
.store-detail-name {
|
.store-detail-name {
|
||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
|
|||||||
@@ -215,13 +215,32 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.store-card-category-wrap {
|
||||||
|
align-self: flex-start;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 0 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(166, 29, 36, 0.1);
|
||||||
|
box-sizing: border-box;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-card-category-text {
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 14px;
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
.store-card-tags {
|
.store-card-tags {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: nowrap;
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow: hidden;
|
margin-top: 2px;
|
||||||
|
margin-bottom: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-tag {
|
.store-card-tag {
|
||||||
|
|||||||
@@ -149,6 +149,7 @@ export const HQ_ADMIN_ROLE_VALUES = [
|
|||||||
'FINANCE',
|
'FINANCE',
|
||||||
'CUSTOMER_SERVICE',
|
'CUSTOMER_SERVICE',
|
||||||
'CITY_STORE_SERVICE',
|
'CITY_STORE_SERVICE',
|
||||||
|
'DEVELOPER',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type HqAdminRoleValue = (typeof HQ_ADMIN_ROLE_VALUES)[number];
|
export type HqAdminRoleValue = (typeof HQ_ADMIN_ROLE_VALUES)[number];
|
||||||
@@ -159,6 +160,7 @@ export const HQ_ADMIN_ROLES: { value: HqAdminRoleValue; label: string }[] = [
|
|||||||
{ value: 'FINANCE', label: '财务' },
|
{ value: 'FINANCE', label: '财务' },
|
||||||
{ value: 'CUSTOMER_SERVICE', label: '客服' },
|
{ value: 'CUSTOMER_SERVICE', label: '客服' },
|
||||||
{ value: 'CITY_STORE_SERVICE', label: '城市门店服务' },
|
{ value: 'CITY_STORE_SERVICE', label: '城市门店服务' },
|
||||||
|
{ value: 'DEVELOPER', label: '开发者' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const OPS_STORE_KEYS: HqPermissionKey[] = [
|
const OPS_STORE_KEYS: HqPermissionKey[] = [
|
||||||
@@ -170,6 +172,13 @@ const OPS_STORE_KEYS: HqPermissionKey[] = [
|
|||||||
'store_media',
|
'store_media',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** 开发者默认:除权限分配、HQ 账户外全部权限 */
|
||||||
|
function developerDefaultPermissions(): HqPermissionKey[] {
|
||||||
|
return HQ_PERMISSION_CATALOG.map((p) => p.key).filter(
|
||||||
|
(k) => k !== 'hq_permissions' && k !== 'hq_accounts',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<HqAdminRoleValue, HqPermissionKey[]> = {
|
export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<HqAdminRoleValue, HqPermissionKey[]> = {
|
||||||
SUPER_ADMIN: [...hqBasePermissionKeys(), ...HQ_DEBUG_PERMISSION_KEYS],
|
SUPER_ADMIN: [...hqBasePermissionKeys(), ...HQ_DEBUG_PERMISSION_KEYS],
|
||||||
OPS: [
|
OPS: [
|
||||||
@@ -228,4 +237,5 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<HqAdminRoleValue, HqPermissionK
|
|||||||
'store_ratings',
|
'store_ratings',
|
||||||
'store_categories',
|
'store_categories',
|
||||||
],
|
],
|
||||||
|
DEVELOPER: developerDefaultPermissions(),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -34,6 +34,14 @@ export interface UpdateAdminUserRequest {
|
|||||||
hqRemark: string;
|
hqRemark: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** HQ 当前账号修改登录名 / 密码(自助) */
|
||||||
|
export interface UpdateMyHqCredentialsRequest {
|
||||||
|
loginName?: string;
|
||||||
|
/** 修改密码时必填(账号尚未设置密码时可省略) */
|
||||||
|
oldPassword?: string;
|
||||||
|
newPassword?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AdminPageResult<T> {
|
export interface AdminPageResult<T> {
|
||||||
items: T[];
|
items: T[];
|
||||||
total: number;
|
total: number;
|
||||||
|
|||||||
@@ -139,6 +139,8 @@ export interface PartnerBillDto {
|
|||||||
redeemCommission: number;
|
redeemCommission: number;
|
||||||
totalAmount: number;
|
totalAmount: number;
|
||||||
status: PartnerBillStatus;
|
status: PartnerBillStatus;
|
||||||
|
/** 出账日 YYYY-MM-DD(周账=账期结束后下周一;历史月账=次月 1 日) */
|
||||||
|
billDate: string;
|
||||||
periodStart: string;
|
periodStart: string;
|
||||||
periodEnd: string;
|
periodEnd: string;
|
||||||
confirmedAt?: string | null;
|
confirmedAt?: string | null;
|
||||||
@@ -187,6 +189,10 @@ export interface StoreBillDto {
|
|||||||
storeId: string;
|
storeId: string;
|
||||||
/** 出账日 YYYY-MM-DD(T+1 窗口「昨日 00:00–今日 00:00」中的今天) */
|
/** 出账日 YYYY-MM-DD(T+1 窗口「昨日 00:00–今日 00:00」中的今天) */
|
||||||
billDate: string;
|
billDate: string;
|
||||||
|
/** 账期起 YYYY-MM-DD(含;T+1 = 出账日前一日) */
|
||||||
|
periodStart: string;
|
||||||
|
/** 账期止 YYYY-MM-DD(含;T+1 = 出账日前一日) */
|
||||||
|
periodEnd: string;
|
||||||
redeemCount: number;
|
redeemCount: number;
|
||||||
redeemAmount: number;
|
redeemAmount: number;
|
||||||
settlementRate: number;
|
settlementRate: number;
|
||||||
@@ -202,6 +208,10 @@ export interface WineryBillDto {
|
|||||||
billNo: string;
|
billNo: string;
|
||||||
/** 出账日 YYYY-MM-DD(北京时间;T+3 = 每 3 天一期,纳入上期 3 天完成订单) */
|
/** 出账日 YYYY-MM-DD(北京时间;T+3 = 每 3 天一期,纳入上期 3 天完成订单) */
|
||||||
billDate: string;
|
billDate: string;
|
||||||
|
/** 账期起 YYYY-MM-DD(含) */
|
||||||
|
periodStart: string;
|
||||||
|
/** 账期止 YYYY-MM-DD(含) */
|
||||||
|
periodEnd: string;
|
||||||
orderCount: number;
|
orderCount: number;
|
||||||
orderAmount: number;
|
orderAmount: number;
|
||||||
wineryRate: number;
|
wineryRate: number;
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- v4.0.11: HQ 角色新增「开发者」(DEVELOPER)
|
||||||
|
-- 默认权限见 packages/shared-types HQ_ROLE_DEFAULT_PERMISSIONS.DEVELOPER
|
||||||
|
-- (除 hq_permissions / hq_accounts 外全部;未写入 hq_role_permission 时走代码默认)
|
||||||
|
|
||||||
|
ALTER TABLE `hq_account`
|
||||||
|
MODIFY COLUMN `admin_role` ENUM(
|
||||||
|
'SUPER_ADMIN',
|
||||||
|
'OPS',
|
||||||
|
'FINANCE',
|
||||||
|
'CUSTOMER_SERVICE',
|
||||||
|
'CITY_STORE_SERVICE',
|
||||||
|
'DEVELOPER'
|
||||||
|
) NOT NULL DEFAULT 'OPS';
|
||||||
|
|
||||||
|
ALTER TABLE `hq_role_permission`
|
||||||
|
MODIFY COLUMN `admin_role` ENUM(
|
||||||
|
'SUPER_ADMIN',
|
||||||
|
'OPS',
|
||||||
|
'FINANCE',
|
||||||
|
'CUSTOMER_SERVICE',
|
||||||
|
'CITY_STORE_SERVICE',
|
||||||
|
'DEVELOPER'
|
||||||
|
) NOT NULL;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- 门店多分类关联表(v4.0.9+)
|
||||||
|
-- 执行:mysql ... < migrate-store-category-link.sql
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS store_category_link (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
store_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
category_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
priority INT NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uk_store_category_link (store_id, category_id),
|
||||||
|
KEY idx_store_category_link_category (category_id),
|
||||||
|
CONSTRAINT fk_store_category_link_store FOREIGN KEY (store_id) REFERENCES store_store(id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT fk_store_category_link_category FOREIGN KEY (category_id) REFERENCES common_store_category(id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
-- 从现有主分类回填
|
||||||
|
INSERT IGNORE INTO store_category_link (store_id, category_id, priority)
|
||||||
|
SELECT id, category_id, 0
|
||||||
|
FROM store_store
|
||||||
|
WHERE category_id IS NOT NULL;
|
||||||
@@ -268,6 +268,7 @@ enum HqAdminRole {
|
|||||||
FINANCE
|
FINANCE
|
||||||
CUSTOMER_SERVICE
|
CUSTOMER_SERVICE
|
||||||
CITY_STORE_SERVICE
|
CITY_STORE_SERVICE
|
||||||
|
DEVELOPER
|
||||||
}
|
}
|
||||||
|
|
||||||
enum HqPermissionEffect {
|
enum HqPermissionEffect {
|
||||||
@@ -1000,12 +1001,29 @@ model CommonStoreCategory {
|
|||||||
parent CommonStoreCategory? @relation("StoreCategoryTree", fields: [parentId], references: [id], onDelete: Restrict)
|
parent CommonStoreCategory? @relation("StoreCategoryTree", fields: [parentId], references: [id], onDelete: Restrict)
|
||||||
children CommonStoreCategory[] @relation("StoreCategoryTree")
|
children CommonStoreCategory[] @relation("StoreCategoryTree")
|
||||||
stores Store[]
|
stores Store[]
|
||||||
|
storeLinks StoreCategoryLink[]
|
||||||
|
|
||||||
@@index([parentId, sort])
|
@@index([parentId, sort])
|
||||||
@@index([status])
|
@@index([status])
|
||||||
@@map("common_store_category")
|
@@map("common_store_category")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 门店 ↔ 二级分类多对多;store.category_id 保留主分类(排序第一)
|
||||||
|
model StoreCategoryLink {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||||
|
categoryId BigInt @map("category_id") @db.UnsignedBigInt
|
||||||
|
priority Int @default(0)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
|
||||||
|
category CommonStoreCategory @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([storeId, categoryId])
|
||||||
|
@@index([categoryId])
|
||||||
|
@@map("store_category_link")
|
||||||
|
}
|
||||||
|
|
||||||
model CommonPromoCode {
|
model CommonPromoCode {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
code String @unique @db.VarChar(32)
|
code String @unique @db.VarChar(32)
|
||||||
@@ -1542,6 +1560,7 @@ model Store {
|
|||||||
packages StorePackage[]
|
packages StorePackage[]
|
||||||
packageChangeRequests StorePackageChangeRequest[]
|
packageChangeRequests StorePackageChangeRequest[]
|
||||||
infoChangeRequests StoreInfoChangeRequest[]
|
infoChangeRequests StoreInfoChangeRequest[]
|
||||||
|
categoryLinks StoreCategoryLink[]
|
||||||
|
|
||||||
@@index([cityId, status])
|
@@index([cityId, status])
|
||||||
@@index([partnerAccountId])
|
@@index([partnerAccountId])
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
export type ExportColumnDef<T> = {
|
||||||
|
key: string;
|
||||||
|
header: string;
|
||||||
|
value: (row: T) => string | number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 按请求的列 key 过滤导出列;未传则导出全部 */
|
||||||
|
export function pickExportColumns<T>(
|
||||||
|
defs: ExportColumnDef<T>[],
|
||||||
|
requestedKeys?: string[],
|
||||||
|
): ExportColumnDef<T>[] {
|
||||||
|
if (!requestedKeys?.length) return defs;
|
||||||
|
const byKey = new Map(defs.map((d) => [d.key, d]));
|
||||||
|
return requestedKeys.map((k) => byKey.get(k)).filter((d): d is ExportColumnDef<T> => !!d);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseExportColumnKeys(raw?: string): string[] | undefined {
|
||||||
|
if (!raw?.trim()) return undefined;
|
||||||
|
const keys = raw
|
||||||
|
.split(',')
|
||||||
|
.map((k) => k.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return keys.length ? keys : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCsvFromColumns<T>(
|
||||||
|
defs: ExportColumnDef<T>[],
|
||||||
|
rows: T[],
|
||||||
|
requestedKeys?: string[],
|
||||||
|
): { csv: string; count: number } {
|
||||||
|
const active = pickExportColumns(defs, requestedKeys);
|
||||||
|
if (!active.length) {
|
||||||
|
return { csv: '\uFEFF', count: 0 };
|
||||||
|
}
|
||||||
|
const header = active.map((d) => d.header).join(',');
|
||||||
|
const body = rows.map((row) =>
|
||||||
|
active
|
||||||
|
.map((d) => {
|
||||||
|
const v = d.value(row);
|
||||||
|
const s = v == null ? '' : String(v);
|
||||||
|
return s.includes(',') || s.includes('"') || s.includes('\n')
|
||||||
|
? `"${s.replace(/"/g, '""')}"`
|
||||||
|
: s;
|
||||||
|
})
|
||||||
|
.join(','),
|
||||||
|
);
|
||||||
|
return { csv: `\uFEFF${[header, ...body].join('\n')}`, count: rows.length };
|
||||||
|
}
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
import {
|
||||||
|
pickExportColumns,
|
||||||
|
type ExportColumnDef,
|
||||||
|
} from '../../common/export/column-export.util';
|
||||||
import {
|
import {
|
||||||
DEV_PLAN_TASK_STATUS_LABELS,
|
DEV_PLAN_TASK_STATUS_LABELS,
|
||||||
DEV_PLAN_TASK_TYPE_LABELS,
|
DEV_PLAN_TASK_TYPE_LABELS,
|
||||||
@@ -27,6 +31,7 @@ const EXPORT_HEADERS = [
|
|||||||
'状态',
|
'状态',
|
||||||
'内容',
|
'内容',
|
||||||
'关联工单',
|
'关联工单',
|
||||||
|
'关联版本',
|
||||||
'创建人',
|
'创建人',
|
||||||
'创建时间',
|
'创建时间',
|
||||||
'完成时间',
|
'完成时间',
|
||||||
@@ -39,6 +44,7 @@ export type DevPlanTaskExportRow = {
|
|||||||
status: string;
|
status: string;
|
||||||
content: string;
|
content: string;
|
||||||
supportTicketNo: string;
|
supportTicketNo: string;
|
||||||
|
versionNos: string;
|
||||||
creatorName: string;
|
creatorName: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
completedAt: string;
|
completedAt: string;
|
||||||
@@ -53,6 +59,7 @@ export function mapTaskToExportRow(task: {
|
|||||||
status: DevPlanTaskStatusDto;
|
status: DevPlanTaskStatusDto;
|
||||||
content: string;
|
content: string;
|
||||||
supportTicketNo?: string | null;
|
supportTicketNo?: string | null;
|
||||||
|
versionNos?: string | null;
|
||||||
creatorName?: string | null;
|
creatorName?: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
completedAt?: string | null;
|
completedAt?: string | null;
|
||||||
@@ -64,6 +71,7 @@ export function mapTaskToExportRow(task: {
|
|||||||
status: DEV_PLAN_TASK_STATUS_LABELS[task.status] ?? task.status,
|
status: DEV_PLAN_TASK_STATUS_LABELS[task.status] ?? task.status,
|
||||||
content: task.content,
|
content: task.content,
|
||||||
supportTicketNo: task.supportTicketNo ?? '',
|
supportTicketNo: task.supportTicketNo ?? '',
|
||||||
|
versionNos: task.versionNos ?? '',
|
||||||
creatorName: task.creatorName ?? '',
|
creatorName: task.creatorName ?? '',
|
||||||
createdAt: task.createdAt.slice(0, 19).replace('T', ' '),
|
createdAt: task.createdAt.slice(0, 19).replace('T', ' '),
|
||||||
completedAt: task.completedAt ? task.completedAt.slice(0, 19).replace('T', ' ') : '',
|
completedAt: task.completedAt ? task.completedAt.slice(0, 19).replace('T', ' ') : '',
|
||||||
@@ -71,20 +79,30 @@ export function mapTaskToExportRow(task: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function rowToCells(row: DevPlanTaskExportRow): string[] {
|
function devPlanExportColumnDefs(): ExportColumnDef<DevPlanTaskExportRow>[] {
|
||||||
return [
|
return [
|
||||||
row.taskNo,
|
{ key: 'taskNo', header: '任务编号', value: (r) => r.taskNo },
|
||||||
row.type,
|
{ key: 'type', header: '类型', value: (r) => r.type },
|
||||||
row.status,
|
{ key: 'status', header: '状态', value: (r) => r.status },
|
||||||
row.content,
|
{ key: 'content', header: '内容', value: (r) => r.content },
|
||||||
row.supportTicketNo,
|
{ key: 'supportTicketNo', header: '关联工单', value: (r) => r.supportTicketNo },
|
||||||
row.creatorName,
|
{ key: 'versions', header: '关联版本', value: (r) => r.versionNos },
|
||||||
row.createdAt,
|
{ key: 'creatorName', header: '创建人', value: (r) => r.creatorName },
|
||||||
row.completedAt,
|
{ key: 'createdAt', header: '创建时间', value: (r) => r.createdAt },
|
||||||
row.attachmentUrls.join(' '),
|
{ key: 'completedAt', header: '完成时间', value: (r) => r.completedAt },
|
||||||
|
{
|
||||||
|
key: 'attachmentUrls',
|
||||||
|
header: '附件',
|
||||||
|
value: (r) => r.attachmentUrls.join(' '),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function rowToCells(row: DevPlanTaskExportRow, columnKeys?: string[]): string[] {
|
||||||
|
const cols = pickExportColumns(devPlanExportColumnDefs(), columnKeys);
|
||||||
|
return cols.map((c) => String(c.value(row)));
|
||||||
|
}
|
||||||
|
|
||||||
function resolvePdfFontPath(): string {
|
function resolvePdfFontPath(): string {
|
||||||
const candidates = [
|
const candidates = [
|
||||||
process.env.EXPORT_PDF_FONT_PATH,
|
process.env.EXPORT_PDF_FONT_PATH,
|
||||||
@@ -187,15 +205,17 @@ export async function buildDevPlanDocx(rows: DevPlanTaskExportRow[]): Promise<Bu
|
|||||||
return Packer.toBuffer(doc);
|
return Packer.toBuffer(doc);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function buildDevPlanXlsx(rows: DevPlanTaskExportRow[]): Promise<Buffer> {
|
export async function buildDevPlanXlsx(rows: DevPlanTaskExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||||
|
const cols = pickExportColumns(devPlanExportColumnDefs(), columnKeys);
|
||||||
const workbook = new ExcelJS.Workbook();
|
const workbook = new ExcelJS.Workbook();
|
||||||
const sheet = workbook.addWorksheet('开发任务');
|
const sheet = workbook.addWorksheet('开发任务');
|
||||||
sheet.addRow([...EXPORT_HEADERS]);
|
sheet.addRow(cols.map((c) => c.header));
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
sheet.addRow(rowToCells(row));
|
sheet.addRow(cols.map((c) => c.value(row)));
|
||||||
}
|
}
|
||||||
sheet.columns.forEach((col, i) => {
|
sheet.columns.forEach((col, i) => {
|
||||||
col.width = i === 3 || i === 8 ? 40 : 16;
|
const header = cols[i]?.header ?? '';
|
||||||
|
col.width = header === '内容' || header === '附件' ? 40 : 16;
|
||||||
});
|
});
|
||||||
const buffer = await workbook.xlsx.writeBuffer();
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
return Buffer.from(buffer);
|
return Buffer.from(buffer);
|
||||||
|
|||||||
@@ -107,11 +107,13 @@ export class AdminDevPlanController {
|
|||||||
@Get('versions')
|
@Get('versions')
|
||||||
listVersions(
|
listVersions(
|
||||||
@Query('status') status?: string,
|
@Query('status') status?: string,
|
||||||
|
@Query('keyword') keyword?: string,
|
||||||
@Query('page') page?: string,
|
@Query('page') page?: string,
|
||||||
@Query('pageSize') pageSize?: string,
|
@Query('pageSize') pageSize?: string,
|
||||||
) {
|
) {
|
||||||
return this.service.listVersions({
|
return this.service.listVersions({
|
||||||
status,
|
status,
|
||||||
|
keyword,
|
||||||
page: page ? Number(page) : undefined,
|
page: page ? Number(page) : undefined,
|
||||||
pageSize: pageSize ? Number(pageSize) : undefined,
|
pageSize: pageSize ? Number(pageSize) : undefined,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -590,7 +590,7 @@ export class DevPlanService {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
async listVersions(query: { status?: string; page?: number; pageSize?: number }) {
|
async listVersions(query: { status?: string; keyword?: string; page?: number; pageSize?: number }) {
|
||||||
|
|
||||||
const page = query.page ?? 1;
|
const page = query.page ?? 1;
|
||||||
|
|
||||||
@@ -600,7 +600,13 @@ export class DevPlanService {
|
|||||||
|
|
||||||
if (query.status) where.status = query.status as DevPlanVersionStatus;
|
if (query.status) where.status = query.status as DevPlanVersionStatus;
|
||||||
|
|
||||||
|
if (query.keyword?.trim()) {
|
||||||
|
const kw = query.keyword.trim();
|
||||||
|
where.OR = [
|
||||||
|
{ versionNo: { contains: kw } },
|
||||||
|
{ content: { contains: kw } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
const [rows, total] = await Promise.all([
|
const [rows, total] = await Promise.all([
|
||||||
|
|
||||||
@@ -1329,6 +1335,7 @@ export class DevPlanService {
|
|||||||
status?: string;
|
status?: string;
|
||||||
type?: string;
|
type?: string;
|
||||||
keyword?: string;
|
keyword?: string;
|
||||||
|
columns?: string[];
|
||||||
}) {
|
}) {
|
||||||
let rows: Array<{
|
let rows: Array<{
|
||||||
id: bigint;
|
id: bigint;
|
||||||
@@ -1372,20 +1379,24 @@ export class DevPlanService {
|
|||||||
: Promise.resolve([]),
|
: Promise.resolve([]),
|
||||||
]);
|
]);
|
||||||
const ticketMap = new Map(tickets.map((t) => [String(t.id), t.ticketNo] as [string, string]));
|
const ticketMap = new Map(tickets.map((t) => [String(t.id), t.ticketNo] as [string, string]));
|
||||||
|
const taskIds = rows.map((r) => r.id);
|
||||||
|
const versionMap = await this.loadTaskVersionMap(taskIds);
|
||||||
|
|
||||||
const exportRows = rows.map((r) =>
|
const exportRows = rows.map((r) => {
|
||||||
mapTaskToExportRow({
|
const versions = versionMap.get(String(r.id)) ?? [];
|
||||||
|
return mapTaskToExportRow({
|
||||||
taskNo: r.taskNo,
|
taskNo: r.taskNo,
|
||||||
type: r.type,
|
type: r.type,
|
||||||
status: r.status,
|
status: r.status,
|
||||||
content: r.content,
|
content: r.content,
|
||||||
supportTicketNo: r.supportTicketId != null ? ticketMap.get(String(r.supportTicketId)) ?? null : null,
|
supportTicketNo: r.supportTicketId != null ? ticketMap.get(String(r.supportTicketId)) ?? null : null,
|
||||||
|
versionNos: versions.map((v) => v.versionNo).join('、') || null,
|
||||||
creatorName: names.get(String(r.creatorHqAccountId)) ?? null,
|
creatorName: names.get(String(r.creatorHqAccountId)) ?? null,
|
||||||
createdAt: r.createdAt.toISOString(),
|
createdAt: r.createdAt.toISOString(),
|
||||||
completedAt: r.completedAt?.toISOString() ?? null,
|
completedAt: r.completedAt?.toISOString() ?? null,
|
||||||
attachmentUrls: parseAttachmentUrls(r.attachmentUrls),
|
attachmentUrls: parseAttachmentUrls(r.attachmentUrls),
|
||||||
}),
|
});
|
||||||
);
|
});
|
||||||
|
|
||||||
let buffer: Buffer;
|
let buffer: Buffer;
|
||||||
switch (dto.format) {
|
switch (dto.format) {
|
||||||
@@ -1396,7 +1407,7 @@ export class DevPlanService {
|
|||||||
buffer = await buildDevPlanDocx(exportRows);
|
buffer = await buildDevPlanDocx(exportRows);
|
||||||
break;
|
break;
|
||||||
case 'xlsx':
|
case 'xlsx':
|
||||||
buffer = await buildDevPlanXlsx(exportRows);
|
buffer = await buildDevPlanXlsx(exportRows, dto.columns);
|
||||||
break;
|
break;
|
||||||
case 'pdf':
|
case 'pdf':
|
||||||
buffer = await buildDevPlanPdf(exportRows);
|
buffer = await buildDevPlanPdf(exportRows);
|
||||||
|
|||||||
@@ -221,6 +221,11 @@ export class DevPlanTaskExportDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
keyword?: string;
|
keyword?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
columns?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BatchReviewPreviewDto {
|
export class BatchReviewPreviewDto {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Body, Controller, Param, Put, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Param, Put, UseGuards } from '@nestjs/common';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { SaveHqListColumnPrefsDto } from './dto/auth.dto';
|
import { SaveHqListColumnPrefsDto, UpdateMyHqCredentialsDto } from './dto/auth.dto';
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||||
import { AuthUser } from '../../common/guards/jwt-auth.guard';
|
import { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
@@ -18,4 +18,9 @@ export class AdminMeController {
|
|||||||
) {
|
) {
|
||||||
return this.authService.updateMyListColumnPrefs(user.actorType, user.actorId, listKey, dto);
|
return this.authService.updateMyListColumnPrefs(user.actorType, user.actorId, listKey, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Put('credentials')
|
||||||
|
updateCredentials(@CurrentUser() user: AuthUser, @Body() dto: UpdateMyHqCredentialsDto) {
|
||||||
|
return this.authService.updateMyHqCredentials(user.actorType, user.actorId, dto);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import type { SmsActorRef } from '../../integrations/sms/sms.interface';
|
|||||||
import { SmsCodeStore } from '../../integrations/sms/sms-code.store';
|
import { SmsCodeStore } from '../../integrations/sms/sms-code.store';
|
||||||
import type { IWechatProvider } from '../../integrations/wechat/wechat.interface';
|
import type { IWechatProvider } from '../../integrations/wechat/wechat.interface';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { verifyPassword } from '../../common/crypto/password.util';
|
import { verifyPassword, hashPassword } from '../../common/crypto/password.util';
|
||||||
import { AnalyticsService } from '../analytics/analytics.service';
|
import { AnalyticsService } from '../analytics/analytics.service';
|
||||||
import { UserAddressService } from './user-address.service';
|
import { UserAddressService } from './user-address.service';
|
||||||
import { ResourceService } from '../common/resource.service';
|
import { ResourceService } from '../common/resource.service';
|
||||||
@@ -1287,6 +1287,50 @@ export class AuthService {
|
|||||||
return { listColumnPrefs: parseListColumnPrefs(updated.listColumnPrefs) };
|
return { listColumnPrefs: parseListColumnPrefs(updated.listColumnPrefs) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateMyHqCredentials(
|
||||||
|
actorType: string,
|
||||||
|
actorId: bigint,
|
||||||
|
dto: { loginName?: string; oldPassword?: string; newPassword?: string },
|
||||||
|
) {
|
||||||
|
if (actorType !== 'HQ') throw new ForbiddenException('仅总部账号可修改');
|
||||||
|
const account = await this.prisma.hqAccount.findUnique({ where: { id: actorId } });
|
||||||
|
if (!account) throw new NotFoundException('账号不存在');
|
||||||
|
|
||||||
|
const data: { loginName?: string; passwordHash?: string } = {};
|
||||||
|
const nextLogin = dto.loginName?.trim();
|
||||||
|
if (nextLogin !== undefined) {
|
||||||
|
if (!nextLogin) throw new BadRequestException('用户名不能为空');
|
||||||
|
if (nextLogin !== account.loginName) {
|
||||||
|
const dup = await this.prisma.hqAccount.findUnique({ where: { loginName: nextLogin } });
|
||||||
|
if (dup && dup.id !== account.id) throw new BadRequestException('用户名已被占用');
|
||||||
|
data.loginName = nextLogin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.newPassword !== undefined) {
|
||||||
|
const pwd = dto.newPassword.trim();
|
||||||
|
if (pwd.length < 6) throw new BadRequestException('新密码至少 6 位');
|
||||||
|
if (account.passwordHash) {
|
||||||
|
if (!dto.oldPassword?.trim()) throw new BadRequestException('请输入当前密码');
|
||||||
|
if (!verifyPassword(dto.oldPassword.trim(), account.passwordHash)) {
|
||||||
|
throw new BadRequestException('当前密码不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.passwordHash = hashPassword(pwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Object.keys(data).length) {
|
||||||
|
throw new BadRequestException('请填写要修改的内容');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await this.prisma.hqAccount.update({
|
||||||
|
where: { id: actorId },
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
const { passwordHash: _ph, ...safe } = updated;
|
||||||
|
return serializeBigInt(safe);
|
||||||
|
}
|
||||||
|
|
||||||
wechatDisabled() {
|
wechatDisabled() {
|
||||||
throw new NotImplementedException('FEATURE_DISABLED');
|
throw new NotImplementedException('FEATURE_DISABLED');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,6 +130,22 @@ export class CheckPartnerPhoneDto {
|
|||||||
phone: string;
|
phone: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class UpdateMyHqCredentialsDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
loginName?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
oldPassword?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
newPassword?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class SaveHqListColumnPrefsDto {
|
export class SaveHqListColumnPrefsDto {
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
|
|||||||
@@ -3,20 +3,16 @@ import ExcelJS from 'exceljs';
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import PDFDocument from 'pdfkit';
|
import PDFDocument from 'pdfkit';
|
||||||
|
import {
|
||||||
|
pickExportColumns,
|
||||||
|
type ExportColumnDef,
|
||||||
|
} from '../../common/export/column-export.util';
|
||||||
|
|
||||||
const EXPORT_HEADERS = [
|
const DELIVERY_TYPE_LABELS: Record<string, string> = {
|
||||||
'订单号',
|
LOCAL: '同城',
|
||||||
'下单时间',
|
CROSS_CITY: '跨城',
|
||||||
'状态',
|
ON_SITE_PICKUP: '现场提货',
|
||||||
'商品',
|
};
|
||||||
'规格',
|
|
||||||
'数量',
|
|
||||||
'实付',
|
|
||||||
'好客权益',
|
|
||||||
'收货人',
|
|
||||||
'手机',
|
|
||||||
'收货地址',
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export type OrderExportRow = {
|
export type OrderExportRow = {
|
||||||
orderNo: string;
|
orderNo: string;
|
||||||
@@ -25,7 +21,9 @@ export type OrderExportRow = {
|
|||||||
productName: string;
|
productName: string;
|
||||||
productSpec: string;
|
productSpec: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
|
deliveryType: string;
|
||||||
payAmount: number;
|
payAmount: number;
|
||||||
|
logisticsFee: string;
|
||||||
benefitBrief: string;
|
benefitBrief: string;
|
||||||
receiverName: string;
|
receiverName: string;
|
||||||
receiverPhone: string;
|
receiverPhone: string;
|
||||||
@@ -95,7 +93,9 @@ export function mapOrderToExportRow(order: {
|
|||||||
productName: order.productName,
|
productName: order.productName,
|
||||||
productSpec: order.productSpec,
|
productSpec: order.productSpec,
|
||||||
quantity: order.quantity,
|
quantity: order.quantity,
|
||||||
|
deliveryType: DELIVERY_TYPE_LABELS[order.deliveryType ?? ''] || order.deliveryType || '',
|
||||||
payAmount: Number(order.payAmount),
|
payAmount: Number(order.payAmount),
|
||||||
|
logisticsFee: '',
|
||||||
benefitBrief: formatBenefitBrief(order),
|
benefitBrief: formatBenefitBrief(order),
|
||||||
receiverName: order.receiverName,
|
receiverName: order.receiverName,
|
||||||
receiverPhone: order.receiverPhone,
|
receiverPhone: order.receiverPhone,
|
||||||
@@ -103,22 +103,49 @@ export function mapOrderToExportRow(order: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function rowToCells(row: OrderExportRow): string[] {
|
function orderExportColumnDefs(): ExportColumnDef<OrderExportRow>[] {
|
||||||
return [
|
return [
|
||||||
row.orderNo,
|
{ key: '订单号', header: '订单号', value: (r) => r.orderNo },
|
||||||
row.createdAt,
|
{ key: '下单时间', header: '下单时间', value: (r) => r.createdAt },
|
||||||
row.status,
|
{ key: '状态', header: '状态', value: (r) => r.status },
|
||||||
row.productName,
|
{ key: '商品', header: '商品', value: (r) => r.productName },
|
||||||
row.productSpec,
|
{ key: '规格', header: '规格', value: (r) => r.productSpec },
|
||||||
String(row.quantity),
|
{ key: '数量', header: '数量', value: (r) => r.quantity },
|
||||||
row.payAmount.toFixed(2),
|
{ key: '配送方式', header: '配送方式', value: (r) => r.deliveryType },
|
||||||
row.benefitBrief,
|
{ key: '实付', header: '实付', value: (r) => r.payAmount.toFixed(2) },
|
||||||
row.receiverName,
|
{ key: '运费', header: '运费', value: (r) => r.logisticsFee },
|
||||||
row.receiverPhone,
|
{ key: '好客权益', header: '好客权益', value: (r) => r.benefitBrief },
|
||||||
row.address,
|
{ key: '收货人', header: '收货人', value: (r) => r.receiverName },
|
||||||
|
{ key: '电话', header: '电话', value: (r) => r.receiverPhone },
|
||||||
|
{ key: '地址', header: '地址', value: (r) => r.address },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ORDER_COLUMN_ALIASES: Record<string, string> = {
|
||||||
|
orderNo: '订单号',
|
||||||
|
createdAt: '下单时间',
|
||||||
|
status: '状态',
|
||||||
|
productName: '商品',
|
||||||
|
productSpec: '规格',
|
||||||
|
quantity: '数量',
|
||||||
|
deliveryType: '配送方式',
|
||||||
|
payAmount: '实付',
|
||||||
|
logisticsFee: '运费',
|
||||||
|
benefitBrief: '好客权益',
|
||||||
|
receiverName: '收货人',
|
||||||
|
receiverPhone: '电话',
|
||||||
|
phone: '电话',
|
||||||
|
receiverAddress: '地址',
|
||||||
|
address: '地址',
|
||||||
|
手机: '电话',
|
||||||
|
收货地址: '地址',
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeOrderColumns(columnKeys?: string[]): string[] | undefined {
|
||||||
|
if (!columnKeys?.length) return undefined;
|
||||||
|
return columnKeys.map((k) => ORDER_COLUMN_ALIASES[k] ?? k);
|
||||||
|
}
|
||||||
|
|
||||||
function resolvePdfFontPath(): string {
|
function resolvePdfFontPath(): string {
|
||||||
const candidates = [
|
const candidates = [
|
||||||
process.env.EXPORT_PDF_FONT_PATH,
|
process.env.EXPORT_PDF_FONT_PATH,
|
||||||
@@ -138,79 +165,42 @@ function resolvePdfFontPath(): string {
|
|||||||
throw new Error('未找到可用于 PDF 的中文字体,请将字体文件放到 server/dukang-api/assets/fonts/');
|
throw new Error('未找到可用于 PDF 的中文字体,请将字体文件放到 server/dukang-api/assets/fonts/');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function buildOrdersXlsx(rows: OrderExportRow[]): Promise<Buffer> {
|
export async function buildOrdersXlsx(rows: OrderExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||||
|
const cols = pickExportColumns(orderExportColumnDefs(), normalizeOrderColumns(columnKeys));
|
||||||
const workbook = new ExcelJS.Workbook();
|
const workbook = new ExcelJS.Workbook();
|
||||||
const sheet = workbook.addWorksheet('订单');
|
const sheet = workbook.addWorksheet('订单');
|
||||||
sheet.addRow([...EXPORT_HEADERS]);
|
sheet.addRow(cols.map((c) => c.header));
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
sheet.addRow(rowToCells(row));
|
sheet.addRow(cols.map((c) => c.value(row)));
|
||||||
}
|
}
|
||||||
sheet.columns.forEach((col) => {
|
sheet.columns.forEach((col) => {
|
||||||
col.width = 16;
|
col.width = 16;
|
||||||
});
|
});
|
||||||
sheet.getColumn(4).width = 22;
|
|
||||||
sheet.getColumn(8).width = 36;
|
|
||||||
sheet.getColumn(11).width = 36;
|
|
||||||
const buffer = await workbook.xlsx.writeBuffer();
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
return Buffer.from(buffer);
|
return Buffer.from(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function buildOrdersPdf(rows: OrderExportRow[]): Promise<Buffer> {
|
export async function buildOrdersPdf(rows: OrderExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||||
|
const cols = pickExportColumns(orderExportColumnDefs(), normalizeOrderColumns(columnKeys));
|
||||||
const fontPath = resolvePdfFontPath();
|
const fontPath = resolvePdfFontPath();
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const doc = new PDFDocument({
|
const doc = new PDFDocument({ size: 'A4', layout: 'landscape', margin: 24, bufferPages: true });
|
||||||
size: 'A4',
|
doc.on('data', (c) => chunks.push(c as Buffer));
|
||||||
layout: 'landscape',
|
|
||||||
margin: 24,
|
|
||||||
bufferPages: true,
|
|
||||||
});
|
|
||||||
doc.on('data', (chunk) => chunks.push(chunk as Buffer));
|
|
||||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||||
doc.on('error', reject);
|
doc.on('error', reject);
|
||||||
|
doc.font(fontPath);
|
||||||
doc.registerFont('zh', fontPath);
|
doc.fontSize(10).text(cols.map((c) => c.header).join(' | '));
|
||||||
doc.font('zh');
|
doc.moveDown(0.5);
|
||||||
|
|
||||||
const pageWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
|
|
||||||
const colWidths = [72, 78, 48, 88, 64, 32, 48, 110, 48, 72, 120];
|
|
||||||
const scale = pageWidth / colWidths.reduce((sum, w) => sum + w, 0);
|
|
||||||
const widths = colWidths.map((w) => w * scale);
|
|
||||||
const rowHeight = 28;
|
|
||||||
const fontSize = 7;
|
|
||||||
let y = doc.page.margins.top;
|
|
||||||
|
|
||||||
const drawRow = (cells: string[], isHeader = false) => {
|
|
||||||
let x = doc.page.margins.left;
|
|
||||||
const height = isHeader ? 24 : rowHeight;
|
|
||||||
if (y + height > doc.page.height - doc.page.margins.bottom) {
|
|
||||||
doc.addPage({ size: 'A4', layout: 'landscape', margin: 24 });
|
|
||||||
y = doc.page.margins.top;
|
|
||||||
}
|
|
||||||
doc.fontSize(isHeader ? 8 : fontSize);
|
|
||||||
cells.forEach((cell, index) => {
|
|
||||||
doc.rect(x, y, widths[index], height).stroke('#dddddd');
|
|
||||||
doc.text(cell || '', x + 2, y + 4, {
|
|
||||||
width: widths[index] - 4,
|
|
||||||
height: height - 6,
|
|
||||||
lineBreak: true,
|
|
||||||
});
|
|
||||||
x += widths[index];
|
|
||||||
});
|
|
||||||
y += height;
|
|
||||||
};
|
|
||||||
|
|
||||||
drawRow([...EXPORT_HEADERS], true);
|
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
drawRow(rowToCells(row));
|
doc.text(cols.map((c) => String(c.value(row))).join(' | '));
|
||||||
}
|
}
|
||||||
|
|
||||||
doc.end();
|
doc.end();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildExportFilename(format: 'xlsx' | 'pdf', count: number): string {
|
export function buildExportFilename(format: 'xlsx' | 'pdf', count: number): string {
|
||||||
const stamp = formatShanghaiDateTime(new Date()).slice(0, 10);
|
const stamp = new Date().toISOString().slice(0, 10);
|
||||||
return `订单导出_${stamp}_${count}条.${format}`;
|
return `订单导出_${stamp}_${count}.${format}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -156,7 +156,9 @@ export class AdminOrdersService {
|
|||||||
|
|
||||||
const rows = orders.map((order) => mapOrderToExportRow(order));
|
const rows = orders.map((order) => mapOrderToExportRow(order));
|
||||||
const buffer =
|
const buffer =
|
||||||
dto.format === 'pdf' ? await buildOrdersPdf(rows) : await buildOrdersXlsx(rows);
|
dto.format === 'pdf'
|
||||||
|
? await buildOrdersPdf(rows, dto.columns)
|
||||||
|
: await buildOrdersXlsx(rows, dto.columns);
|
||||||
const filename = buildExportFilename(dto.format, rows.length);
|
const filename = buildExportFilename(dto.format, rows.length);
|
||||||
const mimeType =
|
const mimeType =
|
||||||
dto.format === 'pdf'
|
dto.format === 'pdf'
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ import { contractMediaType, normalizeContractUrls } from '../../common/store-med
|
|||||||
import type { AdminStoreAccountsQueryDto, AdminStoreMediaQueryDto, AdminStoresQueryDto } from './dto/admin-query.dto';
|
import type { AdminStoreAccountsQueryDto, AdminStoreMediaQueryDto, AdminStoresQueryDto } from './dto/admin-query.dto';
|
||||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||||
import { StoreCategoryService } from '../store/store-category.service';
|
import { StoreCategoryService } from '../store/store-category.service';
|
||||||
|
import {
|
||||||
|
attachStoreCategories,
|
||||||
|
parseUniqueCategoryIds,
|
||||||
|
storeCategoryLinkInclude,
|
||||||
|
syncStoreCategoryLinks,
|
||||||
|
} from '../store/store-category-link.util';
|
||||||
import { AnalyticsService } from '../analytics/analytics.service';
|
import { AnalyticsService } from '../analytics/analytics.service';
|
||||||
import type {
|
import type {
|
||||||
CreateStoreAccountDto,
|
CreateStoreAccountDto,
|
||||||
@@ -123,6 +129,7 @@ export class AdminStoresService {
|
|||||||
cityRef: { select: { id: true, name: true, code: true } },
|
cityRef: { select: { id: true, name: true, code: true } },
|
||||||
partnerAccount: { select: { id: true, companyName: true, name: true, phone: true } },
|
partnerAccount: { select: { id: true, companyName: true, name: true, phone: true } },
|
||||||
category: { select: { id: true, name: true, parentId: true } },
|
category: { select: { id: true, name: true, parentId: true } },
|
||||||
|
...storeCategoryLinkInclude,
|
||||||
bindings: {
|
bindings: {
|
||||||
where: { storeAccount: { isPrimary: 1 } },
|
where: { storeAccount: { isPrimary: 1 } },
|
||||||
take: 1,
|
take: 1,
|
||||||
@@ -169,7 +176,7 @@ export class AdminStoresService {
|
|||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
items: items.map((s) => {
|
items: items.map((s) => {
|
||||||
const { visibilityPhones, ...rest } = s;
|
const { visibilityPhones, ...rest } = s;
|
||||||
return mapStoreCompat({
|
return mapStoreCompat(attachStoreCategories({
|
||||||
...rest,
|
...rest,
|
||||||
visibilityWhitelistEnabled: s.visibilityWhitelistEnabled,
|
visibilityWhitelistEnabled: s.visibilityWhitelistEnabled,
|
||||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||||
@@ -180,7 +187,7 @@ export class AdminStoresService {
|
|||||||
partner: s.partnerAccount,
|
partner: s.partnerAccount,
|
||||||
account: s.bindings[0]?.storeAccount ?? null,
|
account: s.bindings[0]?.storeAccount ?? null,
|
||||||
bindings: undefined,
|
bindings: undefined,
|
||||||
});
|
}));
|
||||||
}),
|
}),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
@@ -196,6 +203,7 @@ export class AdminStoresService {
|
|||||||
cityRef: true,
|
cityRef: true,
|
||||||
partnerAccount: true,
|
partnerAccount: true,
|
||||||
category: true,
|
category: true,
|
||||||
|
...storeCategoryLinkInclude,
|
||||||
bindings: {
|
bindings: {
|
||||||
where: { storeAccount: { isPrimary: 1 } },
|
where: { storeAccount: { isPrimary: 1 } },
|
||||||
take: 1,
|
take: 1,
|
||||||
@@ -219,7 +227,7 @@ export class AdminStoresService {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
const { visibilityPhones, ...rest } = store;
|
const { visibilityPhones, ...rest } = store;
|
||||||
return serializeBigInt(mapStoreCompat({
|
return serializeBigInt(mapStoreCompat(attachStoreCategories({
|
||||||
...rest,
|
...rest,
|
||||||
visibilityWhitelistEnabled: store.visibilityWhitelistEnabled,
|
visibilityWhitelistEnabled: store.visibilityWhitelistEnabled,
|
||||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||||
@@ -235,7 +243,7 @@ export class AdminStoresService {
|
|||||||
redeemCount: store._count.redeemRecords,
|
redeemCount: store._count.redeemRecords,
|
||||||
ratingCount: store._count.ratings,
|
ratingCount: store._count.ratings,
|
||||||
_count: undefined,
|
_count: undefined,
|
||||||
}));
|
})));
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateStoreStatus(id: bigint, dto: UpdateStoreStatusDto, actorId: bigint) {
|
async updateStoreStatus(id: bigint, dto: UpdateStoreStatusDto, actorId: bigint) {
|
||||||
@@ -430,11 +438,22 @@ export class AdminStoresService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let categoryId: bigint | undefined;
|
let categoryId: bigint | undefined;
|
||||||
if (dto.categoryId !== undefined) {
|
let categoryIds: bigint[] | undefined;
|
||||||
|
if (dto.categoryIds !== undefined) {
|
||||||
|
categoryIds = parseUniqueCategoryIds(dto.categoryIds);
|
||||||
|
if (!categoryIds.length) {
|
||||||
|
throw new BadRequestException('请选择门店分类');
|
||||||
|
}
|
||||||
|
for (const id of categoryIds) {
|
||||||
|
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||||
|
}
|
||||||
|
categoryId = categoryIds[0];
|
||||||
|
} else if (dto.categoryId !== undefined) {
|
||||||
if (!dto.categoryId?.trim()) {
|
if (!dto.categoryId?.trim()) {
|
||||||
throw new BadRequestException('请选择门店分类');
|
throw new BadRequestException('请选择门店分类');
|
||||||
}
|
}
|
||||||
categoryId = BigInt(dto.categoryId);
|
categoryId = BigInt(dto.categoryId);
|
||||||
|
categoryIds = [categoryId];
|
||||||
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,6 +680,10 @@ export class AdminStoresService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (categoryIds !== undefined) {
|
||||||
|
await syncStoreCategoryLinks(tx, id, categoryIds);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return this.detailStore(id, actorId);
|
return this.detailStore(id, actorId);
|
||||||
@@ -693,11 +716,20 @@ export class AdminStoresService {
|
|||||||
if (!city) throw new BadRequestException('开城城市不存在');
|
if (!city) throw new BadRequestException('开城城市不存在');
|
||||||
await this.partnerCityService.assertPartnerAccountBoundToCity(partnerAccountId, city.id);
|
await this.partnerCityService.assertPartnerAccountBoundToCity(partnerAccountId, city.id);
|
||||||
|
|
||||||
if (!dto.categoryId?.trim()) {
|
if (!dto.categoryId?.trim() && (!dto.categoryIds || !dto.categoryIds.length)) {
|
||||||
throw new BadRequestException('请选择门店分类');
|
throw new BadRequestException('请选择门店分类');
|
||||||
}
|
}
|
||||||
const categoryId = BigInt(dto.categoryId);
|
const categoryIds = parseUniqueCategoryIds(dto.categoryIds);
|
||||||
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
if (!categoryIds.length && dto.categoryId?.trim()) {
|
||||||
|
categoryIds.push(BigInt(dto.categoryId));
|
||||||
|
}
|
||||||
|
if (!categoryIds.length) {
|
||||||
|
throw new BadRequestException('请选择门店分类');
|
||||||
|
}
|
||||||
|
for (const id of categoryIds) {
|
||||||
|
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||||
|
}
|
||||||
|
const categoryId = categoryIds[0];
|
||||||
|
|
||||||
const latitude = dto.latitude != null ? Number(dto.latitude) : null;
|
const latitude = dto.latitude != null ? Number(dto.latitude) : null;
|
||||||
const longitude = dto.longitude != null ? Number(dto.longitude) : null;
|
const longitude = dto.longitude != null ? Number(dto.longitude) : null;
|
||||||
@@ -775,6 +807,8 @@ export class AdminStoresService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await syncStoreCategoryLinks(this.prisma, store.id, categoryIds);
|
||||||
|
|
||||||
if (dto.coverUrl) {
|
if (dto.coverUrl) {
|
||||||
const cover = await this.prisma.commonResource.create({
|
const cover = await this.prisma.commonResource.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -45,9 +45,15 @@ export class CreateStoreDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
contactPhone?: string;
|
contactPhone?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsNotEmpty()
|
categoryId?: string;
|
||||||
categoryId: string;
|
|
||||||
|
/** 多选二级分类;至少选一项 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
categoryIds?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -240,6 +246,12 @@ export class UpdateStoreDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
categoryId?: string;
|
categoryId?: string;
|
||||||
|
|
||||||
|
/** 多选二级分类;传此项时覆盖 categoryId */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
categoryIds?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
@Min(0)
|
@Min(0)
|
||||||
@@ -1152,7 +1164,7 @@ export class CreateHqAccountDto {
|
|||||||
name: string;
|
name: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE'])
|
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE', 'DEVELOPER'])
|
||||||
adminRole?: string;
|
adminRole?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@@ -1179,7 +1191,7 @@ export class UpdateHqAccountDto {
|
|||||||
name?: string;
|
name?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE'])
|
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE', 'DEVELOPER'])
|
||||||
adminRole?: string;
|
adminRole?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
|
|||||||
@@ -225,6 +225,12 @@ export class AdminOrdersExportDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
assocPartnerAccountId?: string;
|
assocPartnerAccountId?: string;
|
||||||
|
|
||||||
|
/** 按列表可见列导出(中文列名或英文 key) */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
columns?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
/** 概览页用户/订单 ECharts 聚合筛选 */
|
||||||
|
|||||||
@@ -300,6 +300,7 @@ export class AdminStoreBillController {
|
|||||||
storeId: query.storeId,
|
storeId: query.storeId,
|
||||||
dateFrom: query.dateFrom,
|
dateFrom: query.dateFrom,
|
||||||
dateTo: query.dateTo,
|
dateTo: query.dateTo,
|
||||||
|
columns: query.columns,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,6 +392,7 @@ export class AdminPartnerBillController {
|
|||||||
year: query.year ? Number(query.year) : undefined,
|
year: query.year ? Number(query.year) : undefined,
|
||||||
month: query.month ? Number(query.month) : undefined,
|
month: query.month ? Number(query.month) : undefined,
|
||||||
weekStartYmd: query.weekStartYmd,
|
weekStartYmd: query.weekStartYmd,
|
||||||
|
columns: query.columns,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -493,6 +495,7 @@ export class AdminWineryBillController {
|
|||||||
dateTo: query.dateTo,
|
dateTo: query.dateTo,
|
||||||
year: query.year ? Number(query.year) : undefined,
|
year: query.year ? Number(query.year) : undefined,
|
||||||
month: query.month ? Number(query.month) : undefined,
|
month: query.month ? Number(query.month) : undefined,
|
||||||
|
columns: query.columns,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -575,6 +578,7 @@ export class AdminLogisticsBillController {
|
|||||||
providerId: query.providerId,
|
providerId: query.providerId,
|
||||||
year: query.year ? Number(query.year) : undefined,
|
year: query.year ? Number(query.year) : undefined,
|
||||||
month: query.month ? Number(query.month) : undefined,
|
month: query.month ? Number(query.month) : undefined,
|
||||||
|
columns: query.columns,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
previousShanghaiWeek,
|
previousShanghaiWeek,
|
||||||
resolveSettlementRate,
|
resolveSettlementRate,
|
||||||
shanghaiBillPeriodYmds,
|
shanghaiBillPeriodYmds,
|
||||||
|
shanghaiCalendarDaysBetween,
|
||||||
shanghaiMonthLastInstant,
|
shanghaiMonthLastInstant,
|
||||||
shanghaiMonthRange,
|
shanghaiMonthRange,
|
||||||
shanghaiPeriodYmds,
|
shanghaiPeriodYmds,
|
||||||
@@ -40,6 +41,7 @@ import {
|
|||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { AlertService } from '../../common/alert/alert.service';
|
import { AlertService } from '../../common/alert/alert.service';
|
||||||
|
import { buildCsvFromColumns, parseExportColumnKeys, type ExportColumnDef } from '../../common/export/column-export.util';
|
||||||
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
import { AnalyticsService } from '../analytics/analytics.service';
|
import { AnalyticsService } from '../analytics/analytics.service';
|
||||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||||
@@ -88,6 +90,34 @@ function withShanghaiPeriod<T extends { periodStart: Date; periodEnd: Date }>(ro
|
|||||||
return { ...row, ...shanghaiBillPeriodYmds(row.periodStart, row.periodEnd) };
|
return { ...row, ...shanghaiBillPeriodYmds(row.periodStart, row.periodEnd) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 门店 T+1:账期 = 出账日前一日 */
|
||||||
|
function mapStoreBillDates(billDate: Date) {
|
||||||
|
const billDateYmd = shanghaiYmd(billDate);
|
||||||
|
const periodDay = shanghaiYmd(addShanghaiDays(parseShanghaiYmd(billDateYmd), -1));
|
||||||
|
return { billDate: billDateYmd, periodStart: periodDay, periodEnd: periodDay };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合伙人出账日:周账 = 账期周一 + 7 天(下周一);
|
||||||
|
* 历史月账 = 账期所在月次月 1 日。
|
||||||
|
*/
|
||||||
|
function partnerBillIssueYmd(periodStart: Date, periodEnd: Date): string {
|
||||||
|
const days = shanghaiCalendarDaysBetween(periodStart, periodEnd);
|
||||||
|
if (days >= 0 && days <= 8) {
|
||||||
|
return shanghaiYmd(addShanghaiDays(startOfShanghaiDay(periodStart), 7));
|
||||||
|
}
|
||||||
|
const [y, m] = shanghaiYmd(periodStart).split('-').map(Number);
|
||||||
|
return shanghaiYmd(shanghaiMonthRange(y, m).endExclusive);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withPartnerBillDates<T extends { periodStart: Date; periodEnd: Date }>(row: T) {
|
||||||
|
return {
|
||||||
|
...row,
|
||||||
|
...shanghaiBillPeriodYmds(row.periodStart, row.periodEnd),
|
||||||
|
billDate: partnerBillIssueYmd(row.periodStart, row.periodEnd),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function resolvePartnerWeekPeriod(weekStartYmd: string): {
|
function resolvePartnerWeekPeriod(weekStartYmd: string): {
|
||||||
periodStart: Date;
|
periodStart: Date;
|
||||||
periodEnd: Date;
|
periodEnd: Date;
|
||||||
@@ -1429,14 +1459,20 @@ export class SettlementService implements OnModuleInit {
|
|||||||
const payoutAmount = rows.reduce((s, r) => s + r.amount, 0);
|
const payoutAmount = rows.reduce((s, r) => s + r.amount, 0);
|
||||||
|
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
items: slice.map((r) => ({
|
items: slice.map((r) => {
|
||||||
...r,
|
const storeDates =
|
||||||
date: r.kind === 'T1_BILL' ? shanghaiYmd(r.date) : r.date,
|
r.kind === 'T1_BILL' ? mapStoreBillDates(r.date) : null;
|
||||||
bankAccount:
|
return {
|
||||||
r.kind === 'T1_BILL'
|
...r,
|
||||||
? bankMap.get(String(r.storeId)) ?? null
|
date: r.kind === 'T1_BILL' ? storeDates!.billDate : r.date,
|
||||||
: null,
|
periodStart: storeDates?.periodStart ?? null,
|
||||||
})),
|
periodEnd: storeDates?.periodEnd ?? null,
|
||||||
|
bankAccount:
|
||||||
|
r.kind === 'T1_BILL'
|
||||||
|
? bankMap.get(String(r.storeId)) ?? null
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -1487,7 +1523,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
items: items.map((b) => ({ ...b, billDate: shanghaiYmd(b.billDate) })),
|
items: items.map((b) => ({ ...b, ...mapStoreBillDates(b.billDate) })),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -1510,7 +1546,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
const storeAccount = await loadStorePrimaryBank(this.prisma, bill.storeId);
|
const storeAccount = await loadStorePrimaryBank(this.prisma, bill.storeId);
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
...bill,
|
...bill,
|
||||||
billDate: shanghaiYmd(bill.billDate),
|
...mapStoreBillDates(bill.billDate),
|
||||||
storeAccount,
|
storeAccount,
|
||||||
paymentProofUrls: parsePaymentProofUrls(bill.paymentProofUrls),
|
paymentProofUrls: parsePaymentProofUrls(bill.paymentProofUrls),
|
||||||
});
|
});
|
||||||
@@ -1568,6 +1604,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
storeId?: string;
|
storeId?: string;
|
||||||
dateFrom?: string;
|
dateFrom?: string;
|
||||||
dateTo?: string;
|
dateTo?: string;
|
||||||
|
columns?: string;
|
||||||
}) {
|
}) {
|
||||||
const where = this.buildStoreBillWhere(query);
|
const where = this.buildStoreBillWhere(query);
|
||||||
const bills = await this.prisma.storeBill.findMany({
|
const bills = await this.prisma.storeBill.findMany({
|
||||||
@@ -1579,44 +1616,70 @@ export class SettlementService implements OnModuleInit {
|
|||||||
this.prisma,
|
this.prisma,
|
||||||
bills.map((b) => b.storeId),
|
bills.map((b) => b.storeId),
|
||||||
);
|
);
|
||||||
const header = [
|
const columnKeys = parseExportColumnKeys(query.columns);
|
||||||
'账单号',
|
|
||||||
'出账日',
|
type Row = (typeof bills)[number] & { bank?: ReturnType<typeof bankMap.get> extends infer T ? T : never };
|
||||||
'门店',
|
const rows = bills.map((b) => ({ ...b, bank: bankMap.get(String(b.storeId)) }));
|
||||||
'城市',
|
|
||||||
'核销笔数',
|
const defs: ExportColumnDef<Row>[] = [
|
||||||
'核销金额',
|
{ key: '账单号', header: '账单号', value: (r) => r.billNo },
|
||||||
'结算比例',
|
{ key: '出账日', header: '出账日', value: (r) => shanghaiYmd(r.billDate) },
|
||||||
'应付金额',
|
{
|
||||||
'状态',
|
key: '账期',
|
||||||
'打款时间',
|
header: '账期',
|
||||||
'打款凭证',
|
value: (r) => {
|
||||||
'打款凭证照片',
|
const d = mapStoreBillDates(r.billDate);
|
||||||
'收款户名',
|
return `${d.periodStart} ~ ${d.periodEnd}`;
|
||||||
'收款账号',
|
},
|
||||||
'开户行',
|
},
|
||||||
].join(',');
|
{ key: '门店', header: '门店', value: (r) => r.store.name },
|
||||||
const rows = bills.map((b) => {
|
{ key: '登录手机', header: '登录手机', value: (r) => r.store.phone ?? '' },
|
||||||
const bank = bankMap.get(String(b.storeId));
|
{ key: '城市', header: '城市', value: (r) => r.store.cityName ?? '' },
|
||||||
return [
|
{ key: '收款户名', header: '收款户名', value: (r) => r.bank?.bankAccountName ?? '' },
|
||||||
csvEscape(b.billNo),
|
{ key: '收款账号', header: '收款账号', value: (r) => r.bank?.bankAccountNo ?? '' },
|
||||||
shanghaiYmd(b.billDate),
|
{ key: '笔数', header: '笔数', value: (r) => r.redeemCount },
|
||||||
csvEscape(b.store.name),
|
{ key: '应付金额', header: '应付金额', value: (r) => Number(r.payoutAmount) },
|
||||||
csvEscape(b.store.cityName ?? ''),
|
{ key: '核销金额', header: '核销金额', value: (r) => Number(r.redeemAmount) },
|
||||||
b.redeemCount,
|
{ key: '结算比例', header: '结算比例', value: (r) => Number(r.settlementRate) },
|
||||||
Number(b.redeemAmount),
|
{ key: '状态', header: '状态', value: (r) => r.status },
|
||||||
Number(b.settlementRate),
|
{
|
||||||
Number(b.payoutAmount),
|
key: '打款时间',
|
||||||
b.status,
|
header: '打款时间',
|
||||||
b.paidAt ? b.paidAt.toISOString().slice(0, 19).replace('T', ' ') : '',
|
value: (r) => (r.paidAt ? r.paidAt.toISOString().slice(0, 19).replace('T', ' ') : ''),
|
||||||
csvEscape(b.paymentRef ?? ''),
|
},
|
||||||
csvEscape(parsePaymentProofUrls(b.paymentProofUrls).join(' ')),
|
{ key: '打款凭证', header: '打款凭证', value: (r) => r.paymentRef ?? '' },
|
||||||
csvEscape(bank?.bankAccountName ?? ''),
|
{
|
||||||
csvEscape(bank?.bankAccountNo ?? ''),
|
key: '打款凭证照片',
|
||||||
csvEscape(bank?.bankBranch ?? ''),
|
header: '打款凭证照片',
|
||||||
].join(',');
|
value: (r) => parsePaymentProofUrls(r.paymentProofUrls).join(' '),
|
||||||
});
|
},
|
||||||
return { csv: `\uFEFF${[header, ...rows].join('\n')}`, count: bills.length };
|
{ key: '开户行', header: '开户行', value: (r) => r.bank?.bankBranch ?? '' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// 兼容旧英文 key
|
||||||
|
const aliases: Record<string, string> = {
|
||||||
|
billNo: '账单号',
|
||||||
|
date: '出账日',
|
||||||
|
billDate: '出账日',
|
||||||
|
period: '账期',
|
||||||
|
'store.name': '门店',
|
||||||
|
'store.phone': '登录手机',
|
||||||
|
'store.cityName': '城市',
|
||||||
|
bankAccountName: '收款户名',
|
||||||
|
bankAccountNo: '收款账号',
|
||||||
|
redeemCount: '笔数',
|
||||||
|
amount: '应付金额',
|
||||||
|
redeemAmount: '核销金额',
|
||||||
|
settlementRate: '结算比例',
|
||||||
|
status: '状态',
|
||||||
|
paidAt: '打款时间',
|
||||||
|
paymentRef: '打款凭证',
|
||||||
|
paymentProofUrls: '打款凭证照片',
|
||||||
|
bankBranch: '开户行',
|
||||||
|
};
|
||||||
|
const normalized = columnKeys?.map((k) => aliases[k] ?? k);
|
||||||
|
|
||||||
|
return buildCsvFromColumns(defs, rows, normalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildStoreBillWhere(query: {
|
private buildStoreBillWhere(query: {
|
||||||
@@ -1665,7 +1728,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
eventName: 'partner_bill_view',
|
eventName: 'partner_bill_view',
|
||||||
extraJson: { count: bills.length },
|
extraJson: { count: bills.length },
|
||||||
});
|
});
|
||||||
return serializeBigInt(bills.map(withShanghaiPeriod));
|
return serializeBigInt(bills.map(withPartnerBillDates));
|
||||||
}
|
}
|
||||||
|
|
||||||
getPartnerSettlementCycle(anchor = new Date()) {
|
getPartnerSettlementCycle(anchor = new Date()) {
|
||||||
@@ -1737,7 +1800,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
const { items, ...header } = bill;
|
const { items, ...header } = bill;
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
...withShanghaiPeriod(header),
|
...withPartnerBillDates(header),
|
||||||
partnerId: header.partnerAccountId.toString(),
|
partnerId: header.partnerAccountId.toString(),
|
||||||
...splitPartnerBillItems(items),
|
...splitPartnerBillItems(items),
|
||||||
});
|
});
|
||||||
@@ -1785,7 +1848,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const items = rawItems.map((b) => ({
|
const items = rawItems.map((b) => ({
|
||||||
...withShanghaiPeriod(b),
|
...withPartnerBillDates(b),
|
||||||
partner: b.partnerAccount,
|
partner: b.partnerAccount,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -1904,7 +1967,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
if (!bill) throw new NotFoundException('账单不存在');
|
if (!bill) throw new NotFoundException('账单不存在');
|
||||||
const { items, ...header } = bill;
|
const { items, ...header } = bill;
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
...withShanghaiPeriod(header),
|
...withPartnerBillDates(header),
|
||||||
partnerId: header.partnerAccountId.toString(),
|
partnerId: header.partnerAccountId.toString(),
|
||||||
...splitPartnerBillItems(items),
|
...splitPartnerBillItems(items),
|
||||||
});
|
});
|
||||||
@@ -2229,6 +2292,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
year?: number;
|
year?: number;
|
||||||
month?: number;
|
month?: number;
|
||||||
weekStartYmd?: string;
|
weekStartYmd?: string;
|
||||||
|
columns?: string;
|
||||||
}) {
|
}) {
|
||||||
const where = this.buildPartnerBillWhere(query);
|
const where = this.buildPartnerBillWhere(query);
|
||||||
const bills = await this.prisma.partnerBill.findMany({
|
const bills = await this.prisma.partnerBill.findMany({
|
||||||
@@ -2237,76 +2301,82 @@ export class SettlementService implements OnModuleInit {
|
|||||||
partnerAccount: {
|
partnerAccount: {
|
||||||
select: {
|
select: {
|
||||||
companyName: true,
|
companyName: true,
|
||||||
|
name: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
bankAccountName: true,
|
bankAccountName: true,
|
||||||
bankAccountNo: true,
|
bankAccountNo: true,
|
||||||
bankBranch: true,
|
bankBranch: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
items: { orderBy: { occurredAt: 'asc' } },
|
|
||||||
},
|
},
|
||||||
orderBy: { periodStart: 'desc' },
|
orderBy: { periodStart: 'desc' },
|
||||||
});
|
});
|
||||||
|
const columnKeys = parseExportColumnKeys(query.columns);
|
||||||
|
|
||||||
const header = [
|
type Row = (typeof bills)[number];
|
||||||
'账单号',
|
const defs: ExportColumnDef<Row>[] = [
|
||||||
'合伙人',
|
{ key: '账单号', header: '账单号', value: (r) => r.billNo },
|
||||||
'登录手机',
|
{
|
||||||
'账期起',
|
key: '合伙人',
|
||||||
'账期止',
|
header: '合伙人',
|
||||||
'酒单佣金',
|
value: (r) => {
|
||||||
'核销佣金',
|
const c = (r.partnerAccount.companyName || '').trim();
|
||||||
'合计应付',
|
const n = (r.partnerAccount.name || '').trim();
|
||||||
'状态',
|
if (c && n) return `${c}-${n}`;
|
||||||
'发送时间',
|
return c || n || r.partnerAccount.phone || '';
|
||||||
'确认时间',
|
},
|
||||||
'打款时间',
|
},
|
||||||
'打款凭证',
|
{
|
||||||
'收款户名',
|
key: '出账日',
|
||||||
'收款账号',
|
header: '出账日',
|
||||||
'开户行',
|
value: (r) => partnerBillIssueYmd(r.periodStart, r.periodEnd),
|
||||||
'驳回理由',
|
},
|
||||||
].join(',');
|
{
|
||||||
const rows = bills.map((b) =>
|
key: '账期',
|
||||||
[
|
header: '账期',
|
||||||
csvEscape(b.billNo),
|
value: (r) => {
|
||||||
csvEscape(b.partnerAccount.companyName ?? ''),
|
const p = shanghaiBillPeriodYmds(r.periodStart, r.periodEnd);
|
||||||
csvEscape(b.partnerAccount.phone ?? ''),
|
return `${p.periodStart} ~ ${p.periodEnd}`;
|
||||||
shanghaiBillPeriodYmds(b.periodStart, b.periodEnd).periodStart,
|
},
|
||||||
shanghaiBillPeriodYmds(b.periodStart, b.periodEnd).periodEnd,
|
},
|
||||||
Number(b.orderCommission),
|
{ key: '酒单佣金', header: '酒单佣金', value: (r) => Number(r.orderCommission) },
|
||||||
Number(b.redeemCommission),
|
{ key: '核销佣金', header: '核销佣金', value: (r) => Number(r.redeemCommission) },
|
||||||
Number(b.totalAmount),
|
{ key: '合计应付', header: '合计应付', value: (r) => Number(r.totalAmount) },
|
||||||
b.status,
|
{ key: '收款户名', header: '收款户名', value: (r) => r.partnerAccount.bankAccountName ?? '' },
|
||||||
b.sentAt ? shanghaiYmd(b.sentAt) : '',
|
{ key: '收款账号', header: '收款账号', value: (r) => r.partnerAccount.bankAccountNo ?? '' },
|
||||||
b.confirmedAt ? shanghaiYmd(b.confirmedAt) : '',
|
{ key: '状态', header: '状态', value: (r) => r.status },
|
||||||
b.paidAt ? shanghaiYmd(b.paidAt) : '',
|
{ key: '登录手机', header: '登录手机', value: (r) => r.partnerAccount.phone ?? '' },
|
||||||
csvEscape(b.paymentRef ?? ''),
|
{ key: '开户行', header: '开户行', value: (r) => r.partnerAccount.bankBranch ?? '' },
|
||||||
csvEscape(b.partnerAccount.bankAccountName ?? ''),
|
{
|
||||||
csvEscape(b.partnerAccount.bankAccountNo ?? ''),
|
key: '发送时间',
|
||||||
csvEscape(b.partnerAccount.bankBranch ?? ''),
|
header: '发送时间',
|
||||||
csvEscape(b.rejectReason ?? ''),
|
value: (r) => (r.sentAt ? shanghaiYmd(r.sentAt) : ''),
|
||||||
].join(','),
|
},
|
||||||
);
|
{
|
||||||
|
key: '确认时间',
|
||||||
|
header: '确认时间',
|
||||||
|
value: (r) => (r.confirmedAt ? shanghaiYmd(r.confirmedAt) : ''),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: '打款时间',
|
||||||
|
header: '打款时间',
|
||||||
|
value: (r) => (r.paidAt ? shanghaiYmd(r.paidAt) : ''),
|
||||||
|
},
|
||||||
|
{ key: '打款凭证', header: '打款凭证', value: (r) => r.paymentRef ?? '' },
|
||||||
|
{ key: '驳回理由', header: '驳回理由', value: (r) => r.rejectReason ?? '' },
|
||||||
|
];
|
||||||
|
|
||||||
const itemHeader = ['账单号', '类型', '单号', '标题', '备注', '基数', '费率', '佣金', '发生时间'].join(',');
|
const aliases: Record<string, string> = {
|
||||||
const itemRows = bills.flatMap((b) =>
|
billNo: '账单号',
|
||||||
b.items.map((it) =>
|
billDate: '出账日',
|
||||||
[
|
period: '账期',
|
||||||
csvEscape(b.billNo),
|
orderCommission: '酒单佣金',
|
||||||
it.kind === 'ORDER' ? '酒订单' : '核销',
|
redeemCommission: '核销佣金',
|
||||||
csvEscape(it.refNo),
|
totalAmount: '合计应付',
|
||||||
csvEscape(it.title ?? ''),
|
status: '状态',
|
||||||
csvEscape(it.extra ?? ''),
|
};
|
||||||
Number(it.baseAmount),
|
const normalized = columnKeys?.map((k) => aliases[k] ?? k);
|
||||||
Number(it.rate),
|
return buildCsvFromColumns(defs, bills, normalized);
|
||||||
Number(it.commission),
|
|
||||||
it.occurredAt.toISOString().slice(0, 19).replace('T', ' '),
|
|
||||||
].join(','),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const csv = ['账单汇总', header, ...rows, '', '酒订单/核销明细', itemHeader, ...itemRows].join('\n');
|
|
||||||
return { csv: `\uFEFF${csv}`, count: bills.length };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Winery bills ────────────────────────────────────
|
// ─── Winery bills ────────────────────────────────────
|
||||||
@@ -2673,7 +2743,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
items: items.map((b) => ({ ...b, billDate: shanghaiYmd(b.billDate) })),
|
items: items.map((b) => this.mapWineryBillForAdmin(b)),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -2681,6 +2751,33 @@ export class SettlementService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private mapWineryBillForAdmin(b: {
|
||||||
|
id: bigint;
|
||||||
|
billNo: string;
|
||||||
|
billDate: Date;
|
||||||
|
orderCount: number;
|
||||||
|
orderAmount: Prisma.Decimal | number;
|
||||||
|
wineryRate: Prisma.Decimal | number;
|
||||||
|
wineryAmount: Prisma.Decimal | number;
|
||||||
|
status: string;
|
||||||
|
paidAt?: Date | null;
|
||||||
|
paymentRef?: string | null;
|
||||||
|
}) {
|
||||||
|
const billDateYmd = shanghaiYmd(b.billDate);
|
||||||
|
const { start, end } = shanghaiWineryPeriodWindow(
|
||||||
|
parseShanghaiYmd(billDateYmd),
|
||||||
|
WINERY_SETTLEMENT_PERIOD_DAYS,
|
||||||
|
);
|
||||||
|
const periodStart = shanghaiYmd(start);
|
||||||
|
const periodEnd = shanghaiYmd(addShanghaiDays(end, -1));
|
||||||
|
return {
|
||||||
|
...b,
|
||||||
|
billDate: billDateYmd,
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async getAdminWineryBill(id: bigint) {
|
async getAdminWineryBill(id: bigint) {
|
||||||
const bill = await this.prisma.wineryBill.findUnique({
|
const bill = await this.prisma.wineryBill.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -2688,7 +2785,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
if (!bill) throw new NotFoundException('酒厂对账单不存在');
|
if (!bill) throw new NotFoundException('酒厂对账单不存在');
|
||||||
const wineryBank = await loadWineryBankConfig(this.prisma);
|
const wineryBank = await loadWineryBankConfig(this.prisma);
|
||||||
return serializeBigInt({ ...bill, billDate: shanghaiYmd(bill.billDate), wineryBank });
|
return serializeBigInt({ ...this.mapWineryBillForAdmin(bill), items: bill.items, wineryBank });
|
||||||
}
|
}
|
||||||
|
|
||||||
async confirmWineryBill(id: bigint, dto: { paymentRef?: string } = {}) {
|
async confirmWineryBill(id: bigint, dto: { paymentRef?: string } = {}) {
|
||||||
@@ -2728,87 +2825,87 @@ export class SettlementService implements OnModuleInit {
|
|||||||
dateTo?: string;
|
dateTo?: string;
|
||||||
year?: number;
|
year?: number;
|
||||||
month?: number;
|
month?: number;
|
||||||
|
columns?: string;
|
||||||
}) {
|
}) {
|
||||||
const where = this.buildWineryBillWhere(query);
|
const where = this.buildWineryBillWhere(query);
|
||||||
const bills = await this.prisma.wineryBill.findMany({
|
const bills = await this.prisma.wineryBill.findMany({
|
||||||
where,
|
where,
|
||||||
include: { items: true },
|
|
||||||
orderBy: { billDate: 'desc' },
|
orderBy: { billDate: 'desc' },
|
||||||
});
|
});
|
||||||
const wineryBank = await loadWineryBankConfig(this.prisma);
|
const wineryBank = await loadWineryBankConfig(this.prisma);
|
||||||
|
const columnKeys = parseExportColumnKeys(query.columns);
|
||||||
|
|
||||||
const header = [
|
|
||||||
'账单号',
|
|
||||||
'账单日',
|
|
||||||
'订单号',
|
|
||||||
'配送类型',
|
|
||||||
'实付金额',
|
|
||||||
'酒厂比例',
|
|
||||||
'应付',
|
|
||||||
'支付时间',
|
|
||||||
'账单状态',
|
|
||||||
'打款凭证',
|
|
||||||
'收款户名',
|
|
||||||
'开户银行',
|
|
||||||
'开户支行',
|
|
||||||
'收款账号',
|
|
||||||
].join(',');
|
|
||||||
const rows: string[] = [];
|
|
||||||
const statusLabel = (b: { status: string; wineryAmount: Prisma.Decimal | number }) => {
|
const statusLabel = (b: { status: string; wineryAmount: Prisma.Decimal | number }) => {
|
||||||
if (Number(b.wineryAmount) === 0) return '无需打款';
|
if (Number(b.wineryAmount) === 0) return '无需打款';
|
||||||
if (b.status === 'PAID') return '已打款';
|
if (b.status === 'PAID') return '已打款';
|
||||||
if (b.status === 'UNPAID') return '未打款';
|
if (b.status === 'UNPAID') return '未打款';
|
||||||
return b.status;
|
return b.status;
|
||||||
};
|
};
|
||||||
const bankCols = (b: { paymentRef?: string | null }) => [
|
|
||||||
csvEscape(b.paymentRef ?? ''),
|
type ExportRow = {
|
||||||
csvEscape(wineryBank.bankAccountName ?? ''),
|
billNo: string;
|
||||||
csvEscape(wineryBank.bankName ?? ''),
|
billDate: string;
|
||||||
csvEscape(wineryBank.bankBranch ?? ''),
|
periodStart: string;
|
||||||
csvEscape(wineryBank.bankAccountNo ?? ''),
|
periodEnd: string;
|
||||||
|
orderCount: number;
|
||||||
|
orderAmount: Prisma.Decimal | number;
|
||||||
|
wineryRate: Prisma.Decimal | number;
|
||||||
|
wineryAmount: Prisma.Decimal | number;
|
||||||
|
status: string;
|
||||||
|
paymentRef?: string | null;
|
||||||
|
paidAt?: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const rows: ExportRow[] = bills.map((b) => ({
|
||||||
|
...this.mapWineryBillForAdmin(b),
|
||||||
|
paymentRef: b.paymentRef,
|
||||||
|
paidAt: b.paidAt,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const defs: ExportColumnDef<ExportRow>[] = [
|
||||||
|
{ key: '账单号', header: '账单号', value: (r) => r.billNo },
|
||||||
|
{ key: '出账日', header: '出账日', value: (r) => r.billDate },
|
||||||
|
{
|
||||||
|
key: '账期',
|
||||||
|
header: '账期',
|
||||||
|
value: (r) => `${r.periodStart} ~ ${r.periodEnd}`,
|
||||||
|
},
|
||||||
|
{ key: '订单数', header: '订单数', value: (r) => r.orderCount },
|
||||||
|
{ key: '订单总额', header: '订单总额', value: (r) => Number(r.orderAmount) },
|
||||||
|
{ key: '酒厂比例', header: '酒厂比例', value: (r) => Number(r.wineryRate) },
|
||||||
|
{ key: '应付', header: '应付', value: (r) => Number(r.wineryAmount) },
|
||||||
|
{ key: '状态', header: '状态', value: (r) => statusLabel(r) },
|
||||||
|
{
|
||||||
|
key: '打款时间',
|
||||||
|
header: '打款时间',
|
||||||
|
value: (r) => (r.paidAt ? r.paidAt.toISOString().slice(0, 19).replace('T', ' ') : ''),
|
||||||
|
},
|
||||||
|
{ key: '打款凭证', header: '打款凭证', value: (r) => r.paymentRef ?? '' },
|
||||||
|
{ key: '收款户名', header: '收款户名', value: () => wineryBank.bankAccountName ?? '' },
|
||||||
|
{ key: '开户银行', header: '开户银行', value: () => wineryBank.bankName ?? '' },
|
||||||
|
{ key: '开户支行', header: '开户支行', value: () => wineryBank.bankBranch ?? '' },
|
||||||
|
{ key: '收款账号', header: '收款账号', value: () => wineryBank.bankAccountNo ?? '' },
|
||||||
];
|
];
|
||||||
for (const b of bills) {
|
|
||||||
if (b.items.length === 0) {
|
const aliases: Record<string, string> = {
|
||||||
rows.push(
|
billNo: '账单号',
|
||||||
[
|
billDate: '出账日',
|
||||||
csvEscape(b.billNo),
|
period: '账期',
|
||||||
shanghaiYmd(b.billDate),
|
orderCount: '订单数',
|
||||||
'',
|
orderAmount: '订单总额',
|
||||||
'',
|
wineryRate: '酒厂比例',
|
||||||
Number(b.orderAmount),
|
wineryAmount: '应付',
|
||||||
Number(b.wineryRate),
|
status: '状态',
|
||||||
Number(b.wineryAmount),
|
paidAt: '打款时间',
|
||||||
'',
|
paymentRef: '打款凭证',
|
||||||
statusLabel(b),
|
bankAccountName: '收款户名',
|
||||||
...bankCols(b),
|
bankName: '开户银行',
|
||||||
].join(','),
|
bankBranch: '开户支行',
|
||||||
);
|
bankAccountNo: '收款账号',
|
||||||
continue;
|
};
|
||||||
}
|
const normalized = columnKeys?.map((k) => aliases[k] ?? k);
|
||||||
for (const item of b.items) {
|
|
||||||
rows.push(
|
return buildCsvFromColumns(defs, rows, normalized);
|
||||||
[
|
|
||||||
csvEscape(b.billNo),
|
|
||||||
shanghaiYmd(b.billDate),
|
|
||||||
csvEscape(item.orderNo),
|
|
||||||
item.deliveryType === 'LOCAL'
|
|
||||||
? '同城'
|
|
||||||
: item.deliveryType === 'CROSS_CITY'
|
|
||||||
? '跨城'
|
|
||||||
: item.deliveryType === 'ON_SITE_PICKUP'
|
|
||||||
? '现场提货'
|
|
||||||
: item.deliveryType,
|
|
||||||
Number(item.payAmount),
|
|
||||||
Number(b.wineryRate),
|
|
||||||
Number(item.wineryAmount),
|
|
||||||
item.paidAt.toISOString().slice(0, 19).replace('T', ' '),
|
|
||||||
statusLabel(b),
|
|
||||||
...bankCols(b),
|
|
||||||
].join(','),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { csv: `\uFEFF${[header, ...rows].join('\n')}`, count: rows.length };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildWineryBillWhere(query: {
|
private buildWineryBillWhere(query: {
|
||||||
@@ -3362,6 +3459,7 @@ export class SettlementService implements OnModuleInit {
|
|||||||
providerId?: string;
|
providerId?: string;
|
||||||
year?: number;
|
year?: number;
|
||||||
month?: number;
|
month?: number;
|
||||||
|
columns?: string;
|
||||||
}) {
|
}) {
|
||||||
const where = this.buildLogisticsBillWhere(query);
|
const where = this.buildLogisticsBillWhere(query);
|
||||||
const bills = await this.prisma.logisticsBill.findMany({
|
const bills = await this.prisma.logisticsBill.findMany({
|
||||||
@@ -3377,78 +3475,73 @@ export class SettlementService implements OnModuleInit {
|
|||||||
bankAccountNo: true,
|
bankAccountNo: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
items: true,
|
|
||||||
},
|
},
|
||||||
orderBy: { periodStart: 'desc' },
|
orderBy: { periodStart: 'desc' },
|
||||||
});
|
});
|
||||||
|
const columnKeys = parseExportColumnKeys(query.columns);
|
||||||
|
|
||||||
const header = [
|
type Row = (typeof bills)[number];
|
||||||
'账单号',
|
const defs: ExportColumnDef<Row>[] = [
|
||||||
'承运商编码',
|
{ key: '账单号', header: '账单号', value: (r) => r.billNo },
|
||||||
'承运商名称',
|
{
|
||||||
'账期起',
|
key: '承运商',
|
||||||
'账期止',
|
header: '承运商',
|
||||||
'结算方式',
|
value: (r) => `${r.fulfillmentProvider.name} (${r.fulfillmentProvider.code})`,
|
||||||
'订单号',
|
},
|
||||||
'瓶数',
|
{
|
||||||
'物流费',
|
key: '账期',
|
||||||
'发货时间',
|
header: '账期',
|
||||||
'账单状态',
|
value: (r) => {
|
||||||
'打款凭证',
|
const p = shanghaiPeriodYmds(r.periodStart);
|
||||||
'收款户名',
|
return `${p.periodStart} ~ ${p.periodEnd}`;
|
||||||
'开户银行',
|
},
|
||||||
'开户支行',
|
},
|
||||||
'收款账号',
|
{
|
||||||
].join(',');
|
key: '结算方式',
|
||||||
const rows: string[] = [];
|
header: '结算方式',
|
||||||
for (const b of bills) {
|
value: (r) =>
|
||||||
const p = b.fulfillmentProvider;
|
LOGISTICS_SETTLEMENT_METHOD_LABELS[
|
||||||
const bankCols = [
|
r.settlementMethod as keyof typeof LOGISTICS_SETTLEMENT_METHOD_LABELS
|
||||||
csvEscape(b.paymentRef ?? ''),
|
] || r.settlementMethod,
|
||||||
csvEscape(p.bankAccountName ?? ''),
|
},
|
||||||
csvEscape(p.bankName ?? ''),
|
{ key: '订单数', header: '订单数', value: (r) => r.orderCount },
|
||||||
csvEscape(p.bankBranch ?? ''),
|
{ key: '瓶数', header: '瓶数', value: (r) => r.bottleCount },
|
||||||
csvEscape(p.bankAccountNo ?? ''),
|
{ key: '物流费', header: '物流费', value: (r) => Number(r.logisticsAmount) },
|
||||||
];
|
{
|
||||||
if (b.items.length === 0) {
|
key: '收款户名',
|
||||||
rows.push(
|
header: '收款户名',
|
||||||
[
|
value: (r) => r.fulfillmentProvider.bankAccountName ?? '',
|
||||||
csvEscape(b.billNo),
|
},
|
||||||
csvEscape(p.code),
|
{
|
||||||
csvEscape(p.name),
|
key: '收款账号',
|
||||||
shanghaiPeriodYmds(b.periodStart).periodStart,
|
header: '收款账号',
|
||||||
shanghaiPeriodYmds(b.periodStart).periodEnd,
|
value: (r) => r.fulfillmentProvider.bankAccountNo ?? '',
|
||||||
b.settlementMethod,
|
},
|
||||||
'',
|
{ key: '状态', header: '状态', value: (r) => r.status },
|
||||||
b.bottleCount,
|
{
|
||||||
Number(b.logisticsAmount),
|
key: '开户银行',
|
||||||
'',
|
header: '开户银行',
|
||||||
b.status,
|
value: (r) => r.fulfillmentProvider.bankName ?? '',
|
||||||
...bankCols,
|
},
|
||||||
].join(','),
|
{
|
||||||
);
|
key: '开户支行',
|
||||||
continue;
|
header: '开户支行',
|
||||||
}
|
value: (r) => r.fulfillmentProvider.bankBranch ?? '',
|
||||||
for (const item of b.items) {
|
},
|
||||||
rows.push(
|
{ key: '打款凭证', header: '打款凭证', value: (r) => r.paymentRef ?? '' },
|
||||||
[
|
];
|
||||||
csvEscape(b.billNo),
|
|
||||||
csvEscape(p.code),
|
const aliases: Record<string, string> = {
|
||||||
csvEscape(p.name),
|
billNo: '账单号',
|
||||||
shanghaiPeriodYmds(b.periodStart).periodStart,
|
period: '账期',
|
||||||
shanghaiPeriodYmds(b.periodStart).periodEnd,
|
settlementMethod: '结算方式',
|
||||||
b.settlementMethod,
|
orderCount: '订单数',
|
||||||
csvEscape(item.orderNo),
|
bottleCount: '瓶数',
|
||||||
item.quantity,
|
logisticsAmount: '物流费',
|
||||||
Number(item.logisticsAmount),
|
status: '状态',
|
||||||
item.shippedAt.toISOString().slice(0, 19).replace('T', ' '),
|
};
|
||||||
b.status,
|
const normalized = columnKeys?.map((k) => aliases[k] ?? k);
|
||||||
...bankCols,
|
return buildCsvFromColumns(defs, bills, normalized);
|
||||||
].join(','),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { csv: `\uFEFF${[header, ...rows].join('\n')}`, count: rows.length };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildLogisticsBillWhere(query: {
|
private buildLogisticsBillWhere(query: {
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import type { Prisma } from '@prisma/client';
|
||||||
|
|
||||||
|
export const storeCategoryLinkInclude = {
|
||||||
|
categoryLinks: {
|
||||||
|
include: {
|
||||||
|
category: { include: { parent: true } },
|
||||||
|
},
|
||||||
|
orderBy: [{ priority: 'asc' as const }, { id: 'asc' as const }],
|
||||||
|
},
|
||||||
|
} satisfies Prisma.StoreInclude;
|
||||||
|
|
||||||
|
export type StoreCategoryItem = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
parentId: string | null;
|
||||||
|
parent: { id: string; name: string } | null;
|
||||||
|
priority: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CategoryLinkRow = {
|
||||||
|
priority: number;
|
||||||
|
category: {
|
||||||
|
id: bigint;
|
||||||
|
name: string;
|
||||||
|
parentId: bigint | null;
|
||||||
|
parent?: { id: bigint; name: string } | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export function mapStoreCategoryLinks(links: CategoryLinkRow[] | undefined): StoreCategoryItem[] {
|
||||||
|
return (links ?? []).map((link) => ({
|
||||||
|
id: String(link.category.id),
|
||||||
|
name: link.category.name,
|
||||||
|
parentId: link.category.parentId != null ? String(link.category.parentId) : null,
|
||||||
|
parent: link.category.parent
|
||||||
|
? { id: String(link.category.parent.id), name: link.category.parent.name }
|
||||||
|
: null,
|
||||||
|
priority: link.priority,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attachStoreCategories<
|
||||||
|
T extends {
|
||||||
|
categoryId?: bigint | null;
|
||||||
|
category?: {
|
||||||
|
id: bigint;
|
||||||
|
name: string;
|
||||||
|
parentId?: bigint | null;
|
||||||
|
parent?: { id: bigint; name: string } | null;
|
||||||
|
} | null;
|
||||||
|
categoryLinks?: CategoryLinkRow[];
|
||||||
|
},
|
||||||
|
>(store: T) {
|
||||||
|
const { categoryLinks, ...rest } = store;
|
||||||
|
let categories = mapStoreCategoryLinks(categoryLinks);
|
||||||
|
if (!categories.length && store.category) {
|
||||||
|
categories = [
|
||||||
|
{
|
||||||
|
id: String(store.category.id),
|
||||||
|
name: store.category.name,
|
||||||
|
parentId: store.category.parentId != null ? String(store.category.parentId) : null,
|
||||||
|
parent: store.category.parent
|
||||||
|
? { id: String(store.category.parent.id), name: store.category.parent.name }
|
||||||
|
: null,
|
||||||
|
priority: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
const primary = categories[0] ?? null;
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
categories,
|
||||||
|
categoryId: primary?.id ?? (store.categoryId != null ? String(store.categoryId) : null),
|
||||||
|
category: primary
|
||||||
|
? {
|
||||||
|
id: primary.id,
|
||||||
|
name: primary.name,
|
||||||
|
parentId: primary.parentId,
|
||||||
|
parent: primary.parent,
|
||||||
|
}
|
||||||
|
: store.category
|
||||||
|
? {
|
||||||
|
id: String(store.category.id),
|
||||||
|
name: store.category.name,
|
||||||
|
parentId: store.category.parentId != null ? String(store.category.parentId) : null,
|
||||||
|
parent: store.category.parent
|
||||||
|
? { id: String(store.category.parent.id), name: store.category.parent.name }
|
||||||
|
: null,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncStoreCategoryLinks(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
storeId: bigint,
|
||||||
|
categoryIds: bigint[],
|
||||||
|
) {
|
||||||
|
const uniqueIds = [...new Set(categoryIds.map((id) => id.toString()))].map(BigInt);
|
||||||
|
await tx.storeCategoryLink.deleteMany({ where: { storeId } });
|
||||||
|
if (uniqueIds.length === 0) {
|
||||||
|
await tx.store.update({ where: { id: storeId }, data: { categoryId: null } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await tx.storeCategoryLink.createMany({
|
||||||
|
data: uniqueIds.map((categoryId, index) => ({
|
||||||
|
storeId,
|
||||||
|
categoryId,
|
||||||
|
priority: index,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
await tx.store.update({
|
||||||
|
where: { id: storeId },
|
||||||
|
data: { categoryId: uniqueIds[0] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseUniqueCategoryIds(raw: unknown): bigint[] {
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const ids: bigint[] = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const id = BigInt(String(item));
|
||||||
|
const key = id.toString();
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
ids.push(id);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
@@ -253,7 +253,11 @@ export class StoreCategoryService {
|
|||||||
if (childCount > 0) {
|
if (childCount > 0) {
|
||||||
throw new BadRequestException('请先删除或停用下级分类');
|
throw new BadRequestException('请先删除或停用下级分类');
|
||||||
}
|
}
|
||||||
const storeCount = await this.prisma.store.count({ where: { categoryId: id } });
|
const storeCount = await this.prisma.store.count({
|
||||||
|
where: {
|
||||||
|
OR: [{ categoryId: id }, { categoryLinks: { some: { categoryId: id } } }],
|
||||||
|
},
|
||||||
|
});
|
||||||
if (storeCount > 0) {
|
if (storeCount > 0) {
|
||||||
// 软停用,避免破坏已有门店关联
|
// 软停用,避免破坏已有门店关联
|
||||||
const row = await this.prisma.commonStoreCategory.update({
|
const row = await this.prisma.commonStoreCategory.update({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Body, Controller, Get, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
|
||||||
import { StoreService } from './store.service';
|
import { StoreService } from './store.service';
|
||||||
import { StoreCategoryService } from './store-category.service';
|
import { StoreCategoryService } from './store-category.service';
|
||||||
import { RedeemService } from '../redeem/redeem.service';
|
import { RedeemService } from '../redeem/redeem.service';
|
||||||
@@ -109,41 +109,51 @@ export class PartnerStoreController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
async detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
async detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||||
return this.storeService.partnerGetStore(user.actorId, BigInt(id));
|
return this.storeService.partnerGetStore(user.actorId, BigInt(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id/categories')
|
@Get(':id/categories')
|
||||||
async getCategories(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
async getCategories(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||||
return this.storeService.getStoreCategories(BigInt(id));
|
return this.storeService.partnerGetStoreCategories(user.actorId, BigInt(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(':id/categories')
|
@Post(':id/categories')
|
||||||
async assignCategory(
|
async assignCategory(
|
||||||
@CurrentUser() user: AuthUser,
|
@CurrentUser() user: AuthUser,
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() body: { categoryId: string; priority?: number },
|
@Body() body: { categoryId: string; priority?: number },
|
||||||
) {
|
) {
|
||||||
return this.storeService.assignCategoryToStore(BigInt(id), body.categoryId, body.priority);
|
return this.storeService.partnerAssignCategoryToStore(
|
||||||
}
|
user.actorId,
|
||||||
|
BigInt(id),
|
||||||
|
body.categoryId,
|
||||||
|
body.priority,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Delete(':id/categories/:categoryId')
|
@Delete(':id/categories/:categoryId')
|
||||||
async removeCategory(
|
async removeCategory(
|
||||||
@CurrentUser() user: AuthUser,
|
@CurrentUser() user: AuthUser,
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Param('categoryId') categoryId: string,
|
@Param('categoryId') categoryId: string,
|
||||||
) {
|
) {
|
||||||
return this.storeService.removeCategoryFromStore(BigInt(id), categoryId);
|
return this.storeService.partnerRemoveCategoryFromStore(user.actorId, BigInt(id), categoryId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put(':id/categories')
|
@Put(':id/categories')
|
||||||
async replaceCategories(
|
async replaceCategories(
|
||||||
@CurrentUser() user: AuthUser,
|
@CurrentUser() user: AuthUser,
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() body: { categoryIds: string[]; priorities?: Record<string, number> },
|
@Body() body: { categoryIds: string[]; priorities?: Record<string, number> },
|
||||||
) {
|
) {
|
||||||
return this.storeService.replaceStoreCategories(BigInt(id), body.categoryIds, body.priorities);
|
return this.storeService.partnerReplaceStoreCategories(
|
||||||
}
|
user.actorId,
|
||||||
|
BigInt(id),
|
||||||
|
body.categoryIds,
|
||||||
|
body.priorities,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
create(@CurrentUser() user: AuthUser, @Body() body: Record<string, unknown>) {
|
create(@CurrentUser() user: AuthUser, @Body() body: Record<string, unknown>) {
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ import { AnalyticsService } from '../analytics/analytics.service';
|
|||||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||||
import { AuthService } from '../iam/auth.service';
|
import { AuthService } from '../iam/auth.service';
|
||||||
import { StoreCategoryService } from './store-category.service';
|
import { StoreCategoryService } from './store-category.service';
|
||||||
|
import {
|
||||||
|
attachStoreCategories,
|
||||||
|
parseUniqueCategoryIds,
|
||||||
|
storeCategoryLinkInclude,
|
||||||
|
syncStoreCategoryLinks,
|
||||||
|
} from './store-category-link.util';
|
||||||
import { TencentLbsProvider } from '../../integrations/map/tencent-lbs.provider';
|
import { TencentLbsProvider } from '../../integrations/map/tencent-lbs.provider';
|
||||||
import {
|
import {
|
||||||
TestWhitelistService,
|
TestWhitelistService,
|
||||||
@@ -185,6 +191,7 @@ export class StoreService {
|
|||||||
where: where as never,
|
where: where as never,
|
||||||
include: {
|
include: {
|
||||||
category: { include: { parent: true } },
|
category: { include: { parent: true } },
|
||||||
|
...storeCategoryLinkInclude,
|
||||||
coverResource: true,
|
coverResource: true,
|
||||||
},
|
},
|
||||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||||
@@ -226,11 +233,11 @@ export class StoreService {
|
|||||||
const coords = await this.ensureStoreCoordinates(store);
|
const coords = await this.ensureStoreCoordinates(store);
|
||||||
const { visibilityWhitelistEnabled: _wl, ...rest } = store;
|
const { visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||||
const mapped = mapStoreCompat(
|
const mapped = mapStoreCompat(
|
||||||
{
|
attachStoreCategories({
|
||||||
...rest,
|
...rest,
|
||||||
latitude: coords?.latitude ?? store.latitude,
|
latitude: coords?.latitude ?? store.latitude,
|
||||||
longitude: coords?.longitude ?? store.longitude,
|
longitude: coords?.longitude ?? store.longitude,
|
||||||
},
|
}),
|
||||||
{ publicDial: true },
|
{ publicDial: true },
|
||||||
);
|
);
|
||||||
const distanceMeters =
|
const distanceMeters =
|
||||||
@@ -263,6 +270,7 @@ export class StoreService {
|
|||||||
where: { id, status: 'OPEN' },
|
where: { id, status: 'OPEN' },
|
||||||
include: {
|
include: {
|
||||||
category: { include: { parent: true } },
|
category: { include: { parent: true } },
|
||||||
|
...storeCategoryLinkInclude,
|
||||||
coverResource: true,
|
coverResource: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -287,7 +295,7 @@ export class StoreService {
|
|||||||
const { visibilityWhitelistEnabled: _wl, ...rest } = store;
|
const { visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||||
return serializeBigInt(
|
return serializeBigInt(
|
||||||
mapStoreCompat(
|
mapStoreCompat(
|
||||||
{
|
attachStoreCategories({
|
||||||
...rest,
|
...rest,
|
||||||
latitude: coords?.latitude ?? store.latitude,
|
latitude: coords?.latitude ?? store.latitude,
|
||||||
longitude: coords?.longitude ?? store.longitude,
|
longitude: coords?.longitude ?? store.longitude,
|
||||||
@@ -310,7 +318,7 @@ export class StoreService {
|
|||||||
sortOrder: p.sortOrder,
|
sortOrder: p.sortOrder,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
},
|
}),
|
||||||
{ publicDial: true },
|
{ publicDial: true },
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -332,17 +340,17 @@ export class StoreService {
|
|||||||
}
|
}
|
||||||
const stores = await this.prisma.store.findMany({
|
const stores = await this.prisma.store.findMany({
|
||||||
where,
|
where,
|
||||||
include: { category: true, coverResource: true },
|
include: { category: true, ...storeCategoryLinkInclude, coverResource: true },
|
||||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||||
});
|
});
|
||||||
return serializeBigInt(stores.map((s) => mapStoreCompat(s)));
|
return serializeBigInt(stores.map((s) => mapStoreCompat(attachStoreCategories(s))));
|
||||||
}
|
}
|
||||||
|
|
||||||
async partnerGetStore(partnerAccountId: bigint, storeId: bigint) {
|
async partnerGetStore(partnerAccountId: bigint, storeId: bigint) {
|
||||||
const { account, primaryId } = await this.resolvePartnerScope(partnerAccountId);
|
const { account, primaryId } = await this.resolvePartnerScope(partnerAccountId);
|
||||||
const store = await this.prisma.store.findFirst({
|
const store = await this.prisma.store.findFirst({
|
||||||
where: { id: storeId, partnerAccountId: primaryId },
|
where: { id: storeId, partnerAccountId: primaryId },
|
||||||
include: { category: true, coverResource: true },
|
include: { category: true, ...storeCategoryLinkInclude, coverResource: true },
|
||||||
});
|
});
|
||||||
if (!store) throw new NotFoundException('门店不存在');
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
if (this.isSubAccount(account)) {
|
if (this.isSubAccount(account)) {
|
||||||
@@ -350,7 +358,7 @@ export class StoreService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const media = await this.loadPartnerStoreMedia(storeId);
|
const media = await this.loadPartnerStoreMedia(storeId);
|
||||||
return serializeBigInt(mapStoreCompat({ ...store, media }));
|
return serializeBigInt(mapStoreCompat(attachStoreCategories({ ...store, media })));
|
||||||
}
|
}
|
||||||
|
|
||||||
async partnerListCities(partnerAccountId: bigint) {
|
async partnerListCities(partnerAccountId: bigint) {
|
||||||
@@ -444,11 +452,20 @@ export class StoreService {
|
|||||||
const bankAccountNo = body.bankAccountNo ? String(body.bankAccountNo) : null;
|
const bankAccountNo = body.bankAccountNo ? String(body.bankAccountNo) : null;
|
||||||
const bankBranch = body.bankBranch ? String(body.bankBranch) : null;
|
const bankBranch = body.bankBranch ? String(body.bankBranch) : null;
|
||||||
|
|
||||||
if (!body.categoryId) {
|
if (!body.categoryId && !Array.isArray(body.categoryIds)) {
|
||||||
throw new BadRequestException('请选择店铺类型');
|
throw new BadRequestException('请选择店铺类型');
|
||||||
}
|
}
|
||||||
const categoryId = parseBigIntParam(body.categoryId, '分类ID');
|
const categoryIds = parseUniqueCategoryIds(body.categoryIds);
|
||||||
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
if (!categoryIds.length && body.categoryId) {
|
||||||
|
categoryIds.push(parseBigIntParam(body.categoryId, '分类ID'));
|
||||||
|
}
|
||||||
|
if (!categoryIds.length) {
|
||||||
|
throw new BadRequestException('请选择店铺类型');
|
||||||
|
}
|
||||||
|
for (const id of categoryIds) {
|
||||||
|
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||||
|
}
|
||||||
|
const categoryId = categoryIds[0];
|
||||||
|
|
||||||
const openTime = body.openTime ? String(body.openTime).trim() : '10:00';
|
const openTime = body.openTime ? String(body.openTime).trim() : '10:00';
|
||||||
const closeTime = body.closeTime ? String(body.closeTime).trim() : '22:00';
|
const closeTime = body.closeTime ? String(body.closeTime).trim() : '22:00';
|
||||||
@@ -507,6 +524,8 @@ export class StoreService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await syncStoreCategoryLinks(this.prisma, store.id, categoryIds);
|
||||||
|
|
||||||
if (latitude == null || longitude == null) {
|
if (latitude == null || longitude == null) {
|
||||||
await this.ensureStoreCoordinates(store);
|
await this.ensureStoreCoordinates(store);
|
||||||
}
|
}
|
||||||
@@ -1515,4 +1534,138 @@ export class StoreService {
|
|||||||
});
|
});
|
||||||
if (!event) throw new ForbiddenException('无权查看该门店');
|
if (!event) throw new ForbiddenException('无权查看该门店');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getStoreCategories(storeId: bigint) {
|
||||||
|
const store = await this.prisma.store.findUnique({
|
||||||
|
where: { id: storeId },
|
||||||
|
include: {
|
||||||
|
category: { include: { parent: true } },
|
||||||
|
...storeCategoryLinkInclude,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
|
return serializeBigInt(attachStoreCategories(store).categories);
|
||||||
|
}
|
||||||
|
|
||||||
|
async partnerGetStoreCategories(partnerAccountId: bigint, storeId: bigint) {
|
||||||
|
await this.partnerGetStore(partnerAccountId, storeId);
|
||||||
|
return this.getStoreCategories(storeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async assignCategoryToStore(storeId: bigint, categoryIdRaw: string, priority?: number) {
|
||||||
|
const categoryId = parseBigIntParam(categoryIdRaw, '分类ID');
|
||||||
|
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
||||||
|
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||||
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
|
|
||||||
|
const existing = await this.prisma.storeCategoryLink.findUnique({
|
||||||
|
where: { storeId_categoryId: { storeId, categoryId } },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
if (priority != null) {
|
||||||
|
await this.prisma.storeCategoryLink.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: { priority },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this.getStoreCategories(storeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextPriority =
|
||||||
|
priority ??
|
||||||
|
((await this.prisma.storeCategoryLink.count({ where: { storeId } })) || 0);
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
await tx.storeCategoryLink.create({
|
||||||
|
data: { storeId, categoryId, priority: nextPriority },
|
||||||
|
});
|
||||||
|
if (!store.categoryId) {
|
||||||
|
await tx.store.update({ where: { id: storeId }, data: { categoryId } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return this.getStoreCategories(storeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async partnerAssignCategoryToStore(
|
||||||
|
partnerAccountId: bigint,
|
||||||
|
storeId: bigint,
|
||||||
|
categoryId: string,
|
||||||
|
priority?: number,
|
||||||
|
) {
|
||||||
|
await this.partnerGetStore(partnerAccountId, storeId);
|
||||||
|
return this.assignCategoryToStore(storeId, categoryId, priority);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeCategoryFromStore(storeId: bigint, categoryIdRaw: string) {
|
||||||
|
const categoryId = parseBigIntParam(categoryIdRaw, '分类ID');
|
||||||
|
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||||
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
|
|
||||||
|
const linkCount = await this.prisma.storeCategoryLink.count({ where: { storeId } });
|
||||||
|
const legacyOnly = linkCount === 0 && store.categoryId?.toString() === categoryId.toString();
|
||||||
|
if (linkCount <= 1 && !legacyOnly) {
|
||||||
|
throw new BadRequestException('门店至少保留一个分类');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
await tx.storeCategoryLink.deleteMany({ where: { storeId, categoryId } });
|
||||||
|
const remaining = await tx.storeCategoryLink.findMany({
|
||||||
|
where: { storeId },
|
||||||
|
orderBy: [{ priority: 'asc' }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
const nextPrimary = remaining[0]?.categoryId ?? null;
|
||||||
|
await tx.store.update({
|
||||||
|
where: { id: storeId },
|
||||||
|
data: { categoryId: nextPrimary },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return this.getStoreCategories(storeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async partnerRemoveCategoryFromStore(
|
||||||
|
partnerAccountId: bigint,
|
||||||
|
storeId: bigint,
|
||||||
|
categoryId: string,
|
||||||
|
) {
|
||||||
|
await this.partnerGetStore(partnerAccountId, storeId);
|
||||||
|
return this.removeCategoryFromStore(storeId, categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async replaceStoreCategories(
|
||||||
|
storeId: bigint,
|
||||||
|
categoryIdsRaw: string[],
|
||||||
|
priorities?: Record<string, number>,
|
||||||
|
) {
|
||||||
|
if (!categoryIdsRaw?.length) {
|
||||||
|
throw new BadRequestException('请至少选择一个门店分类');
|
||||||
|
}
|
||||||
|
const parsed = parseUniqueCategoryIds(categoryIdsRaw);
|
||||||
|
if (!parsed.length) {
|
||||||
|
throw new BadRequestException('请至少选择一个门店分类');
|
||||||
|
}
|
||||||
|
for (const id of parsed) {
|
||||||
|
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||||
|
}
|
||||||
|
const sorted = [...parsed].sort((a, b) => {
|
||||||
|
const pa = priorities?.[a.toString()] ?? 0;
|
||||||
|
const pb = priorities?.[b.toString()] ?? 0;
|
||||||
|
if (pa !== pb) return pa - pb;
|
||||||
|
return Number(a - b);
|
||||||
|
});
|
||||||
|
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||||
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
await syncStoreCategoryLinks(tx, storeId, sorted);
|
||||||
|
});
|
||||||
|
return this.getStoreCategories(storeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async partnerReplaceStoreCategories(
|
||||||
|
partnerAccountId: bigint,
|
||||||
|
storeId: bigint,
|
||||||
|
categoryIds: string[],
|
||||||
|
priorities?: Record<string, number>,
|
||||||
|
) {
|
||||||
|
await this.partnerGetStore(partnerAccountId, storeId);
|
||||||
|
return this.replaceStoreCategories(storeId, categoryIds, priorities);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user