Compare commits
6 Commits
2dbe665bdc
...
4d76ee6d0e
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d76ee6d0e | |||
| bdc9dbde8d | |||
| 3fc2f23e10 | |||
| 09e732bfa3 | |||
| 50ba6e9c56 | |||
| 6a23e79f4c |
@@ -29,4 +29,5 @@ chore(shared-types): add OrderStatus enum
|
||||
## Agent 行为
|
||||
|
||||
- **仅用户明确要求时** 才执行 git commit / push
|
||||
- 不 amend 已推送的 commit,不 force push main/master
|
||||
- 不 amend 已推送的 commit,不 force push main/master/dev
|
||||
- 发版:`dev`→测试(staging),`main`→生产;用户只说「发布」默认发测试(见 dukang-release skill)
|
||||
|
||||
@@ -1,89 +1,89 @@
|
||||
---
|
||||
name: dukang-release
|
||||
description: >-
|
||||
杜康好客生产发布流程:dev_jacy 提交合并到 dev,并用 deploy.sh 发版。
|
||||
Use when the user says 发布、上传、deploy、上线、发版, or @杜康发布 / @dukang-release.
|
||||
杜康好客发布流程:dev→测试(staging),main→生产;同机双栈。
|
||||
Use when the user says 发布、上传、deploy、上线、发版、发测试、发生产,
|
||||
or @杜康发布 / @dukang-release.
|
||||
---
|
||||
|
||||
# 杜康发布
|
||||
|
||||
将已完成改动发到生产(`aliyun-smarthr`)。**仅用户明确要求发布时执行。**
|
||||
同机双栈:`/opt/dukang-staging`(测试)与 `/opt/dukang`(生产)。**仅用户明确要求发布时执行。**
|
||||
|
||||
## 分支约定
|
||||
## 分支与环境
|
||||
|
||||
| 分支 | 用途 |
|
||||
|------|------|
|
||||
| `dev_jacy` | 日常开发 / 提交 |
|
||||
| `dev` | **发布分支**(服务器拉这个) |
|
||||
| 分支 | 环境 | 目录 | 端口 | 域名 |
|
||||
|------|------|------|------|------|
|
||||
| `dev_jacy` | 日常开发 | 本机 | — | — |
|
||||
| `dev` | **staging 测试** | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||
| `main` | **production 生产** | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||
|
||||
默认:`dev_jacy` → merge → `dev` → 部署。勿 force push `main`/`dev`。
|
||||
默认:`dev_jacy` → merge → `dev` → **发测试**。
|
||||
生产:`dev` 验收通过 → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
||||
|
||||
用户只说「发布」且未指明生产时 → **发测试(staging)**。
|
||||
用户说「发生产 / 上线生产」→ 用 `deploy-prod.sh`。
|
||||
|
||||
## 标准流程(Windows)
|
||||
|
||||
PowerShell 下 **分支名必须加引号**(否则 `checkout` 与 `dev` 会被粘成 `checkoutdev`)。
|
||||
PowerShell 下 **分支名必须加引号**。
|
||||
|
||||
### 1. 提交(在 `dev_jacy`)
|
||||
|
||||
```powershell
|
||||
git status -sb
|
||||
git add <files>
|
||||
git commit -m @"
|
||||
fix(scope): summary
|
||||
|
||||
Optional body.
|
||||
"@
|
||||
```
|
||||
|
||||
- Conventional Commits;不提交 `.env` / `dist` / `node_modules`
|
||||
- 用户未要求 commit 时不要擅自提交
|
||||
|
||||
### 2. 推送并合并到 `dev`
|
||||
### A. 发测试(日常)
|
||||
|
||||
```powershell
|
||||
# 1. 在 dev_jacy 提交(用户要求时)
|
||||
git push -u origin HEAD
|
||||
git checkout "dev"
|
||||
git pull origin "dev"
|
||||
git merge "dev_jacy" -m "merge(dev_jacy): <简述>"
|
||||
git push origin "dev"
|
||||
git checkout "dev_jacy"
|
||||
|
||||
# 2. 发 staging
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy-staging.sh" -- --skip-db
|
||||
```
|
||||
|
||||
### 3. 远程发版
|
||||
|
||||
本机无 WSL bash 时用 **Git Bash**:
|
||||
### B. 发生产(验收后)
|
||||
|
||||
```powershell
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy.sh" --branch "dev" -- --skip-db
|
||||
git checkout "main"
|
||||
git pull origin "main"
|
||||
git merge "dev" -m "merge(dev): <简述>"
|
||||
git push origin "main"
|
||||
git checkout "dev_jacy"
|
||||
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy-prod.sh" -- --skip-db
|
||||
```
|
||||
|
||||
- 默认加 `--skip-db`(无迁移时)
|
||||
- 有 Prisma 迁移时去掉 `--skip-db`,按用户确认是否 `--seed` / `--accept-data-loss`
|
||||
- `deploy/deploy.env` 提供 `DEPLOY_HOST` 等(勿提交密钥)
|
||||
- 有 Prisma 迁移:先在 **staging** 跑通(可 `--seed` / `--accept-data-loss`),再生产去掉 `--skip-db`
|
||||
- Staging 微信:正式号 + 全 Mock(`.env.staging`)
|
||||
- `deploy/deploy.env` 提供 `DEPLOY_HOST`、`STAGING_APP_ROOT`、`PROD_APP_ROOT`(勿提交密钥)
|
||||
|
||||
### 4. 等待完成
|
||||
### 首次启用 Staging
|
||||
|
||||
后台跑部署时轮询终端输出,成功标志:
|
||||
服务器一次性:`bash deploy/bootstrap-staging.sh`(见脚本说明)→ 配 `.env.staging` → DNS `*-test` → nginx → `deploy-staging.sh -- --seed`
|
||||
|
||||
### 同步环境变量
|
||||
|
||||
```powershell
|
||||
bash deploy/sync-api-env.sh staging
|
||||
bash deploy/sync-api-env.sh production
|
||||
```
|
||||
|
||||
## 等待完成
|
||||
|
||||
- 出现 `发版完成`
|
||||
- `exit_code: 0`
|
||||
- `mini-user(h5): 200`(或对应前端 200)
|
||||
- `mini-user(h5): 200` / `api: 200`
|
||||
|
||||
说明:API 健康检查短暂 `FAIL`/`000` 多为重启中,以 `发版完成` + `exit_code: 0` 为准。
|
||||
## 回复用户
|
||||
|
||||
### 5. 回复用户
|
||||
|
||||
一句说明:已合并 commit、发版结果、建议微信强刷验证。
|
||||
|
||||
## 常用变体
|
||||
|
||||
| 场景 | 做法 |
|
||||
|------|------|
|
||||
| 仅部署已推送的 `dev` | 跳过 commit/merge,直接跑 `deploy.sh --branch "dev" -- --skip-db` |
|
||||
| 检查服务器 | `deploy.sh --branch "dev" --check` |
|
||||
| 含 DB | `deploy.sh --branch "dev" --`(无 skip-db)或按用户给 seed 参数 |
|
||||
说明:环境(测试/生产)、commit、建议硬刷验证。测试后台有橙色「测试环境」条。
|
||||
|
||||
## 禁止
|
||||
|
||||
- 不 amend 已推送 commit;不 force push `main`/`master`/`dev`
|
||||
- 不把 `.env` / 私钥打进仓库
|
||||
- 用户只说「修好」未说发布时 → **只改代码,不发版**
|
||||
- 不 amend 已推送 commit;不 force push `main`/`dev`
|
||||
- 不把 `.env*` 私钥打进仓库
|
||||
- **禁止**再用 `dev` 直发生产
|
||||
- 用户只说「修好」未说发布 → 只改代码,不发版
|
||||
|
||||
@@ -8,7 +8,13 @@ server/dukang-api/.env
|
||||
server/dukang-api/.env.development
|
||||
server/dukang-api/.env.production
|
||||
server/dukang-api/.env.production.local
|
||||
server/dukang-api/.env.staging
|
||||
server/dukang-api/.env.staging.local
|
||||
deploy/deploy.env
|
||||
deploy/.staging-mysql.pass
|
||||
deploy/_ops-*.log
|
||||
deploy/_ops-*.sh
|
||||
|
||||
.DS_Store
|
||||
coverage/
|
||||
*.tsbuildinfo
|
||||
|
||||
@@ -137,6 +137,19 @@ C 端门店仅 status=OPEN
|
||||
订单 Tab:待付款 | 已付款 | 已完成
|
||||
```
|
||||
|
||||
## 环境与发版
|
||||
|
||||
| 环境 | 分支 | 目录 | 端口 | 域名 |
|
||||
|------|------|------|------|------|
|
||||
| local | `dev_jacy` | 本机 Docker 6016/6017 | API `:3000` | — |
|
||||
| **staging 测试** | `dev` | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||
| **production 生产** | `main` | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||
|
||||
- 日常发布 → `deploy/deploy-staging.sh`(`dev`)
|
||||
- 生产发布 → `deploy/deploy-prod.sh`(`main`,验收后)
|
||||
- Staging:正式微信 + 全 Mock;配置见 `.env.staging.example`
|
||||
- 详情:`@dukang-release` / `.cursor/skills/dukang-release/SKILL.md`
|
||||
|
||||
## 提交与 PR
|
||||
|
||||
- Conventional Commits:`feat(trade):`、`fix(redeem):`;scope = 端或模块
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -13,6 +13,8 @@
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"antd": "^5.22.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
QRCode,
|
||||
Radio,
|
||||
Select,
|
||||
Space,
|
||||
@@ -18,6 +19,8 @@ import type {
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
} from '@dukang/shared-types';
|
||||
import ChinaRegionCascader from './ChinaRegionCascader';
|
||||
import { parseRegionCodes } from '../lib/china-region';
|
||||
@@ -29,6 +32,13 @@ type ProxyOrderModalProps = {
|
||||
onSuccess: (order: { id: string; orderNo: string }) => void;
|
||||
};
|
||||
|
||||
type PayStatus = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payStatus: string;
|
||||
};
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
@@ -49,8 +59,22 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [payLoading, setPayLoading] = useState(false);
|
||||
const [mockConfirming, setMockConfirming] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setLoadingOptions(true);
|
||||
@@ -64,8 +88,8 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !productId || quantity < 1) {
|
||||
setPreview(null);
|
||||
if (!open || !productId || quantity < 1 || step !== 'form') {
|
||||
if (step === 'form') setPreview(null);
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -85,9 +109,12 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
.finally(() => setPreviewLoading(false));
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [open, productId, quantity, deliveryMode, region?.city, region?.district]);
|
||||
}, [open, productId, quantity, deliveryMode, region?.city, region?.district, step]);
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
function resetForm() {
|
||||
stopPoll();
|
||||
setPhone('');
|
||||
setReceiverName('');
|
||||
setRegionCodes([]);
|
||||
@@ -98,6 +125,11 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
setAutoReceive(false);
|
||||
setPreview(null);
|
||||
setProductId(options?.products[0]?.id);
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
setCodeUrl(null);
|
||||
setPayLoading(false);
|
||||
setMockConfirming(false);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -120,6 +152,23 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
return null;
|
||||
}
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<PayStatus>(`/admin/proxy-orders/${orderId}/pay-status`)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
message.success(`支付成功:${st.orderNo}`);
|
||||
const payload = { id: st.id, orderNo: st.orderNo };
|
||||
resetForm();
|
||||
onSuccess(payload);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const err = validateForm();
|
||||
if (err) {
|
||||
@@ -143,17 +192,46 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<{ id: string; orderNo: string }>('/admin/proxy-orders', {
|
||||
const order = await request<ProxyOrderCreateResponse>('/admin/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
message.success(`代下单成功:${order.orderNo}`);
|
||||
resetForm();
|
||||
onSuccess(order);
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setPayLoading(true);
|
||||
const pay = await request<ProxyOrderPayResponse>(`/admin/proxy-orders/${order.id}/pay`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: 'NATIVE' }),
|
||||
});
|
||||
setCodeUrl(pay.codeUrl ?? null);
|
||||
startPoll(order.id);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '下单失败');
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setPayLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMockConfirm() {
|
||||
if (!created) return;
|
||||
setMockConfirming(true);
|
||||
try {
|
||||
const st = await request<PayStatus>(`/admin/proxy-orders/${created.id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
});
|
||||
stopPoll();
|
||||
message.success(`支付成功:${st.orderNo}`);
|
||||
const payload = { id: st.id, orderNo: st.orderNo };
|
||||
resetForm();
|
||||
onSuccess(payload);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '模拟支付失败');
|
||||
} finally {
|
||||
setMockConfirming(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,138 +244,178 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="代下单"
|
||||
title={step === 'pay' ? '代下单 · 待支付' : '代下单'}
|
||||
open={open}
|
||||
onCancel={handleClose}
|
||||
width={640}
|
||||
destroyOnClose
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={handleClose}>取消</Button>
|
||||
<Button type="primary" loading={submitting || loadingOptions} onClick={() => void submit()}>
|
||||
确认代下单
|
||||
</Button>
|
||||
</Space>
|
||||
step === 'pay' ? (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>关闭</Button>
|
||||
<Button type="primary" loading={mockConfirming} onClick={() => void handleMockConfirm()}>
|
||||
模拟支付成功
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>取消</Button>
|
||||
<Button type="primary" loading={submitting || loadingOptions} onClick={() => void submit()}>
|
||||
提交并收款
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="线下已收款:提交后订单直接完成并发放好客权益"
|
||||
/>
|
||||
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="用户手机号" required>
|
||||
<Input
|
||||
placeholder="11 位手机号"
|
||||
value={phone}
|
||||
maxLength={11}
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
{step === 'pay' && created ? (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16, textAlign: 'left' }}
|
||||
message={`订单 ${created.orderNo} 待支付 ¥${fmtMoney(created.payAmount)},请扫码支付`}
|
||||
description={
|
||||
created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付完成后将进入现场提货闭环'
|
||||
: '支付完成后将进入待发货,由总部履约发货'
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="酒品" required>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
loading={loadingOptions}
|
||||
placeholder="选择商品"
|
||||
value={productId}
|
||||
onChange={setProductId}
|
||||
options={(options?.products ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.name} · ${p.spec} · ¥${fmtMoney(p.price)}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="数量" required>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={quantity}
|
||||
onChange={(v) => setQuantity(Math.max(1, Number(v) || 1))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{(options?.promoCodes.length ?? 0) > 0 ? (
|
||||
<Form.Item label="绑定推广码(选填)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不绑定"
|
||||
value={promoCodeId}
|
||||
onChange={setPromoCodeId}
|
||||
options={(options?.promoCodes ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.code} · ${p.name}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
placeholder="默认:用户+手机尾号"
|
||||
value={receiverName}
|
||||
maxLength={32}
|
||||
onChange={(e) => setReceiverName(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="省市区" required>
|
||||
<ChinaRegionCascader value={regionCodes} onChange={setRegionCodes} />
|
||||
</Form.Item>
|
||||
<Form.Item label="详细地址" required>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="街道门牌等"
|
||||
value={addressDetail}
|
||||
maxLength={256}
|
||||
onChange={(e) => setAddressDetail(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Checkbox checked={autoReceive} onChange={(e) => setAutoReceive(e.target.checked)}>
|
||||
同意自动收货(配送到址必选)
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div style={{ background: '#fafafa', borderRadius: 8, padding: 12 }}>
|
||||
<Typography.Text type="secondary">费用预览</Typography.Text>
|
||||
{previewLoading ? (
|
||||
<div>计算中…</div>
|
||||
) : preview ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', marginTop: 8 }}>
|
||||
<div>履约:{deliveryLabel}</div>
|
||||
<div>商品金额:¥{fmtMoney(preview.productAmount)}</div>
|
||||
<div>实付:¥{fmtMoney(preview.payAmount)}</div>
|
||||
<div>好客权益:¥{fmtMoney(preview.benefitAmount)}</div>
|
||||
{payLoading && !codeUrl ? (
|
||||
<Typography.Text type="secondary">正在生成收款码…</Typography.Text>
|
||||
) : codeUrl ? (
|
||||
<Space direction="vertical" size={12} align="center">
|
||||
<QRCode value={codeUrl} size={200} />
|
||||
<Typography.Text type="secondary">请使用微信扫一扫完成支付(本地可用下方模拟支付)</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, wordBreak: 'break-all' }}>
|
||||
{codeUrl}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Typography.Text type="secondary">请完善商品与数量</Typography.Text>
|
||||
</div>
|
||||
<Typography.Text type="danger">收款码生成失败,请关闭后重试</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="提交后生成微信收款码,支付成功后发放好客权益;配送单进入待发货"
|
||||
/>
|
||||
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="用户手机号" required>
|
||||
<Input
|
||||
placeholder="11 位手机号"
|
||||
value={phone}
|
||||
maxLength={11}
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="酒品" required>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
loading={loadingOptions}
|
||||
placeholder="选择商品"
|
||||
value={productId}
|
||||
onChange={setProductId}
|
||||
options={(options?.products ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.name} · ${p.spec} · ¥${fmtMoney(p.price)}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="数量" required>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={quantity}
|
||||
onChange={(v) => setQuantity(Math.max(1, Number(v) || 1))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{(options?.promoCodes.length ?? 0) > 0 ? (
|
||||
<Form.Item label="绑定推广码(选填)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不绑定"
|
||||
value={promoCodeId}
|
||||
onChange={setPromoCodeId}
|
||||
options={(options?.promoCodes ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.code} · ${p.name}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
placeholder="默认:用户+手机尾号"
|
||||
value={receiverName}
|
||||
maxLength={32}
|
||||
onChange={(e) => setReceiverName(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="省市区" required>
|
||||
<ChinaRegionCascader value={regionCodes} onChange={setRegionCodes} />
|
||||
</Form.Item>
|
||||
<Form.Item label="详细地址" required>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="街道门牌等"
|
||||
value={addressDetail}
|
||||
maxLength={256}
|
||||
onChange={(e) => setAddressDetail(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Checkbox checked={autoReceive} onChange={(e) => setAutoReceive(e.target.checked)}>
|
||||
同意自动收货(配送到址必选)
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div style={{ background: '#fafafa', borderRadius: 8, padding: 12 }}>
|
||||
<Typography.Text type="secondary">费用预览</Typography.Text>
|
||||
{previewLoading ? (
|
||||
<div>计算中…</div>
|
||||
) : preview ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', marginTop: 8 }}>
|
||||
<div>履约:{deliveryLabel}</div>
|
||||
<div>商品金额:¥{fmtMoney(preview.productAmount)}</div>
|
||||
<div>实付:¥{fmtMoney(preview.payAmount)}</div>
|
||||
<div>好客权益:¥{fmtMoney(preview.benefitAmount)}</div>
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Typography.Text type="secondary">请完善商品与数量</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -204,6 +204,8 @@ function filterMenuItems(items: MenuProps['items'], permissionKeys: string[]): M
|
||||
.filter(Boolean) as MenuProps['items'];
|
||||
}
|
||||
|
||||
const IS_STAGING = import.meta.env.VITE_APP_ENV === 'staging';
|
||||
|
||||
export default function AdminLayout() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -239,16 +241,35 @@ export default function AdminLayout() {
|
||||
|
||||
return (
|
||||
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
|
||||
{IS_STAGING ? (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
zIndex: 1100,
|
||||
background: '#d48806',
|
||||
color: '#fff',
|
||||
textAlign: 'center',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
lineHeight: '28px',
|
||||
}}
|
||||
>
|
||||
测试环境 · staging · 数据与生产隔离 · Mock 开启
|
||||
</div>
|
||||
) : null}
|
||||
<Sider
|
||||
breakpoint="lg"
|
||||
collapsedWidth={64}
|
||||
theme="dark"
|
||||
width={220}
|
||||
style={{ height: '100vh', overflow: 'hidden' }}
|
||||
style={{ height: '100vh', overflow: 'hidden', marginTop: IS_STAGING ? 28 : 0 }}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: IS_STAGING ? 'calc(100vh - 28px)' : '100vh' }}>
|
||||
<div style={{ flexShrink: 0, padding: '16px', color: '#fff', fontWeight: 600 }}>
|
||||
杜康 HQ
|
||||
杜康 HQ{IS_STAGING ? ' · 测试' : ''}
|
||||
</div>
|
||||
<div className="admin-sider-menu-scroll" style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
|
||||
<Menu
|
||||
@@ -264,7 +285,15 @@ export default function AdminLayout() {
|
||||
</div>
|
||||
</div>
|
||||
</Sider>
|
||||
<Layout style={{ height: '100vh', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
|
||||
<Layout
|
||||
style={{
|
||||
height: IS_STAGING ? 'calc(100vh - 28px)' : '100vh',
|
||||
marginTop: IS_STAGING ? 28 : 0,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Header
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
|
||||
@@ -88,6 +88,51 @@ export type DashboardStats = {
|
||||
ordersByStatus: Array<{ status: string; count: number }>;
|
||||
};
|
||||
|
||||
export type DashboardAnalytics = {
|
||||
summary: {
|
||||
users: number;
|
||||
orders: number;
|
||||
payingUsers: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
byDate: Array<{
|
||||
date: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
byCity: Array<{
|
||||
cityId: string;
|
||||
cityName: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
byPromo: Array<{
|
||||
promoCodeId: string | null;
|
||||
code: string;
|
||||
name: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
}>;
|
||||
byPartner: Array<{
|
||||
partnerAccountId: string;
|
||||
companyName: string;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
export type SystemVersion = {
|
||||
id: string;
|
||||
gitTag: string | null;
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Button, Card, Col, Descriptions, Modal, Row, Space, Statistic, Table, Typography, message,
|
||||
Button, Card, Col, DatePicker, Descriptions, Form, Modal, Row, Select, Space, Statistic, Table, Typography, message,
|
||||
} from 'antd';
|
||||
import { CloudUploadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import {
|
||||
request,
|
||||
type DashboardAnalytics,
|
||||
type DashboardStats,
|
||||
type DeployTriggerResult,
|
||||
type HqProfile,
|
||||
type Paginated,
|
||||
type SystemVersion,
|
||||
} from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
@@ -31,6 +36,26 @@ const DEPLOYED_BY_LABELS: Record<string, string> = {
|
||||
admin: 'Admin 发布',
|
||||
};
|
||||
|
||||
type CityOption = { id: string; name: string; code: string };
|
||||
type PromoOption = { id: string; code: string; name: string };
|
||||
|
||||
type AnalyticsFilters = {
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
};
|
||||
|
||||
function buildAnalyticsQs(f: AnalyticsFilters) {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('dateFrom', f.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('dateTo', f.range[1].format('YYYY-MM-DD'));
|
||||
if (f.cityId) qs.set('cityId', f.cityId);
|
||||
if (f.promoCodeId) qs.set('promoCodeId', f.promoCodeId);
|
||||
if (f.partnerAccountId) qs.set('partnerAccountId', f.partnerAccountId);
|
||||
return qs.toString();
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||
const [version, setVersion] = useState<SystemVersion | null>(null);
|
||||
@@ -40,6 +65,21 @@ export default function DashboardPage() {
|
||||
const [deploying, setDeploying] = useState(false);
|
||||
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
||||
|
||||
const [filterForm] = Form.useForm<{
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}>();
|
||||
const [filters, setFilters] = useState<AnalyticsFilters>({
|
||||
range: [dayjs().subtract(29, 'day'), dayjs()],
|
||||
});
|
||||
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
|
||||
const [analyticsLoading, setAnalyticsLoading] = useState(true);
|
||||
const [cities, setCities] = useState<CityOption[]>([]);
|
||||
const [promos, setPromos] = useState<PromoOption[]>([]);
|
||||
const [partners, setPartners] = useState<Array<{ id: string; companyName?: string | null; name: string }>>([]);
|
||||
|
||||
const loadVersion = useCallback(() => {
|
||||
setVersionLoading(true);
|
||||
return request<SystemVersion | null>('/admin/dashboard/version')
|
||||
@@ -48,6 +88,17 @@ export default function DashboardPage() {
|
||||
.finally(() => setVersionLoading(false));
|
||||
}, []);
|
||||
|
||||
const loadAnalytics = useCallback((f: AnalyticsFilters) => {
|
||||
setAnalyticsLoading(true);
|
||||
return request<DashboardAnalytics>(`/admin/dashboard/analytics?${buildAnalyticsQs(f)}`)
|
||||
.then(setAnalytics)
|
||||
.catch((e) => {
|
||||
message.error(e instanceof Error ? e.message : '加载统计失败');
|
||||
setAnalytics(null);
|
||||
})
|
||||
.finally(() => setAnalyticsLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
request<DashboardStats>('/admin/dashboard/stats')
|
||||
.then(setStats)
|
||||
@@ -64,8 +115,64 @@ export default function DashboardPage() {
|
||||
.catch(() => {
|
||||
setVersionLoading(false);
|
||||
});
|
||||
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setCities(res.items ?? []))
|
||||
.catch(() => setCities([]));
|
||||
void request<Paginated<PromoOption>>(`/admin/promo-codes?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setPromos(res.items ?? []))
|
||||
.catch(() => setPromos([]));
|
||||
void request<Paginated<{ id: string; companyName?: string | null; name: string }>>(
|
||||
`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`,
|
||||
)
|
||||
.then((res) => setPartners(res.items ?? []))
|
||||
.catch(() => setPartners([]));
|
||||
}, [loadVersion]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadAnalytics(filters);
|
||||
}, [filters, loadAnalytics]);
|
||||
|
||||
function applyFilters(values: {
|
||||
range?: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}) {
|
||||
const next: AnalyticsFilters = {
|
||||
range: values.range ?? filters.range,
|
||||
cityId: values.cityId || undefined,
|
||||
promoCodeId: values.promoCodeId || undefined,
|
||||
partnerAccountId: values.partnerAccountId || undefined,
|
||||
};
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setCityFilter(cityId: string) {
|
||||
const next = { ...filters, cityId: cityId === filters.cityId ? undefined : cityId };
|
||||
filterForm.setFieldsValue({ cityId: next.cityId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setPromoFilter(promoCodeId: string) {
|
||||
const key = promoCodeId === 'null' || promoCodeId === '' ? 'none' : promoCodeId;
|
||||
const next = {
|
||||
...filters,
|
||||
promoCodeId: key === filters.promoCodeId ? undefined : key,
|
||||
};
|
||||
filterForm.setFieldsValue({ promoCodeId: next.promoCodeId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setPartnerFilter(partnerAccountId: string) {
|
||||
const next = {
|
||||
...filters,
|
||||
partnerAccountId:
|
||||
partnerAccountId === filters.partnerAccountId ? undefined : partnerAccountId,
|
||||
};
|
||||
filterForm.setFieldsValue({ partnerAccountId: next.partnerAccountId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function handleDeploy() {
|
||||
Modal.confirm({
|
||||
title: '确认发布更新?',
|
||||
@@ -89,6 +196,176 @@ export default function DashboardPage() {
|
||||
|
||||
const shortSha = version?.commitId ? version.commitId.slice(0, 7) : '—';
|
||||
|
||||
const ordersDrillQs = useMemo(() => {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('createdFrom', filters.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('createdTo', filters.range[1].format('YYYY-MM-DD'));
|
||||
if (filters.cityId && filters.cityId !== 'none') qs.set('cityId', filters.cityId);
|
||||
return qs.toString();
|
||||
}, [filters]);
|
||||
|
||||
const byDateOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byDate ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增用户', '订单数'] },
|
||||
grid: { left: 40, right: 20, top: 40, bottom: 40 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '新增用户', type: 'line', smooth: true, data: rows.map((r) => r.users) },
|
||||
{ name: '订单数', type: 'line', smooth: true, data: rows.map((r) => r.orders) },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byPromoOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPromo ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 64 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.name || r.code),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByDateOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byDate ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增合伙人', '新签门店', '核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 48, bottom: 40 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '数量', minInterval: 1 },
|
||||
{ type: 'value', name: '金额', minInterval: 1 },
|
||||
],
|
||||
series: [
|
||||
{ name: '新增合伙人', type: 'line', smooth: true, data: rows.map((r) => r.partners) },
|
||||
{ name: '新签门店', type: 'line', smooth: true, data: rows.map((r) => r.stores) },
|
||||
{ name: '核销笔数', type: 'line', smooth: true, data: rows.map((r) => r.redeems) },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['合伙人', '门店', '核销笔数'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '合伙人', type: 'bar', data: rows.map((r) => r.partners), barMaxWidth: 28 },
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByPartnerOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPartner ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['门店', '核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 64 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.companyName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '数量', minInterval: 1 },
|
||||
{ type: 'value', name: '金额' },
|
||||
],
|
||||
series: [
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const redeemByCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '笔数', minInterval: 1 },
|
||||
{ type: 'value', name: '金额' },
|
||||
],
|
||||
series: [
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 36 },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4}>数据概览</Typography.Title>
|
||||
@@ -176,6 +453,237 @@ export default function DashboardPage() {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
title="数据统计筛选"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
size="small"
|
||||
onClick={() => void loadAnalytics(filters)}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Form
|
||||
form={filterForm}
|
||||
layout="inline"
|
||||
initialValues={{ range: filters.range }}
|
||||
onFinish={applyFilters}
|
||||
>
|
||||
<Form.Item name="range" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
|
||||
<DatePicker.RangePicker allowClear={false} />
|
||||
</Form.Item>
|
||||
<Form.Item name="cityId" label="城市">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部开城"
|
||||
style={{ width: 160 }}
|
||||
options={[
|
||||
{ value: 'none', label: '未选城' },
|
||||
...cities.map((c) => ({ value: c.id, label: c.name })),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="promoCodeId" label="推广码">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部来源"
|
||||
style={{ width: 200 }}
|
||||
options={[
|
||||
{ value: 'none', label: '自然量 / 无推广码' },
|
||||
...promos.map((p) => ({ value: p.id, label: `${p.name}(${p.code})` })),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="partnerAccountId" label="合伙人">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部合伙人"
|
||||
style={{ width: 200 }}
|
||||
options={partners.map((p) => ({
|
||||
value: p.id,
|
||||
label: p.companyName || p.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="用户 / 订单统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to={`/orders?${ordersDrillQs}`}>查看订单</Link>
|
||||
<Link to="/users">查看用户</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间新增用户" value={analytics?.summary.users ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间订单数" value={analytics?.summary.orders ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间付费用户" value={analytics?.summary.payingUsers ?? 0} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24}>
|
||||
<Card type="inner" title="按日趋势" loading={analyticsLoading} size="small">
|
||||
<ReactECharts option={byDateOption} style={{ height: 320 }} notMerge />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={byCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按推广码(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={byPromoOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byPromo ?? []).find(
|
||||
(r) => (r.name || r.code) === params.name,
|
||||
);
|
||||
if (row) setPromoFilter(row.promoCodeId ?? 'none');
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="合伙人 / 门店 / 核销统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to="/city-partners">查看合伙人</Link>
|
||||
<Link to="/stores">查看门店</Link>
|
||||
<Link to="/redeem-records">查看核销</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新增合伙人" value={analytics?.summary.partners ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新签门店" value={analytics?.summary.stores ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销笔数" value={analytics?.summary.redeems ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销金额" value={analytics?.summary.redeemAmount ?? 0} precision={2} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24}>
|
||||
<Card type="inner" title="按日趋势(合伙人 / 门店 / 核销)" loading={analyticsLoading} size="small">
|
||||
<ReactECharts option={opsByDateOption} style={{ height: 320 }} notMerge />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={opsByCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市核销金额"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={redeemByCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按合伙人(门店 / 核销,点击联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={opsByPartnerOption}
|
||||
style={{ height: 320 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byPartner ?? []).find(
|
||||
(r) => r.companyName === params.name,
|
||||
);
|
||||
if (row) setPartnerFilter(row.partnerAccountId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card
|
||||
|
||||
@@ -9,15 +9,17 @@
|
||||
"lint": "echo ok"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/weixin-sdk": "workspace:*",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getPartnerProfile } from '../lib/api';
|
||||
import { getPartnerProfile, hasPartnerWxSession } from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getPartnerProfile();
|
||||
if (profile && hasPartnerWxSession() && profile.hasWechat) {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,10 @@ export function clearAuth(options?: { keepProfile?: boolean }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
export function isLoggedIn() {
|
||||
return !!localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
PENDING_SHIP: '待发货',
|
||||
OUT_WAREHOUSE: '已出库',
|
||||
SHIPPING: '配送中',
|
||||
PENDING_RECEIVE: '待收货',
|
||||
COMPLETED: '已完成',
|
||||
CANCELLED: '已取消',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
const PAY_LABELS: Record<string, string> = {
|
||||
UNPAID: '未支付',
|
||||
PAYING: '支付中',
|
||||
PAID: '已付款',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
export function proxyOrderStatusLabel(status?: string | null) {
|
||||
if (!status) return '—';
|
||||
return STATUS_LABELS[status] || status;
|
||||
}
|
||||
|
||||
export function proxyOrderPayLabel(payStatus?: string | null) {
|
||||
if (!payStatus) return '—';
|
||||
return PAY_LABELS[payStatus] || payStatus;
|
||||
}
|
||||
|
||||
export function proxyOrderStatusColor(status?: string | null) {
|
||||
if (status === 'PENDING_PAY') return 'var(--color-warning, #d48806)';
|
||||
if (status === 'COMPLETED') return 'var(--color-success-green)';
|
||||
if (status === 'CANCELLED' || status === 'REFUNDED') return 'var(--color-text-muted, #999)';
|
||||
return 'var(--color-primary, #8b1e1e)';
|
||||
}
|
||||
@@ -1,14 +1,24 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { WECHAT_INAPP_REQUIRED_MSG } from '@dukang/weixin-sdk';
|
||||
import {
|
||||
getLastPhone,
|
||||
getPartnerProfile,
|
||||
hasPartnerWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type PartnerSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
import {
|
||||
bindPartnerWechatAfterSmsLogin,
|
||||
fetchClientConfig,
|
||||
loginPartnerWithWechat,
|
||||
} from '../lib/wechat-auth';
|
||||
import { toastError } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
const REMEMBER_PHONE_KEY = 'partner_remember_phone';
|
||||
const REMEMBER_FLAG_KEY = 'partner_remember_account';
|
||||
@@ -39,6 +49,11 @@ function AgreementCheckbox({
|
||||
);
|
||||
}
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function loadRememberedPhone(): { phone: string; remember: boolean } {
|
||||
try {
|
||||
const remember = localStorage.getItem(REMEMBER_FLAG_KEY) === '1';
|
||||
@@ -60,9 +75,19 @@ function formatPartnerError(e: unknown): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession, refresh, account } = usePartnerSession();
|
||||
const [params] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getPartnerProfile();
|
||||
const remembered = loadRememberedPhone();
|
||||
const [phone, setPhone] = useState(remembered.phone || getLastPhone());
|
||||
@@ -70,13 +95,27 @@ export default function LoginPage() {
|
||||
const [rememberAccount, setRememberAccount] = useState(remembered.remember);
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
const quickName = savedProfile?.name ?? '城市合伙人';
|
||||
const quickCompany = savedProfile?.companyName ?? '';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先勾选并同意用户协议');
|
||||
const tip = '请先勾选并同意用户协议';
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
agreementRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
return false;
|
||||
}
|
||||
@@ -140,6 +179,11 @@ export default function LoginPage() {
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
persistRememberAccount(phone);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindPartnerWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
await finishLoginNavigate();
|
||||
} catch (e) {
|
||||
setMsg(formatPartnerError(e));
|
||||
@@ -148,6 +192,119 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg(WECHAT_INAPP_REQUIRED_MSG);
|
||||
toastError(WECHAT_INAPP_REQUIRED_MSG);
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
// 直接发起 OAuth;未绑定账号由后端返回「请先短信登录」提示
|
||||
const session = await loginPartnerWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
await finishLoginNavigate();
|
||||
return;
|
||||
}
|
||||
if (session === null) {
|
||||
const tip = '微信授权暂未开启,请使用验证码登录';
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
}
|
||||
// session === undefined:已跳转微信授权页
|
||||
} catch (e) {
|
||||
const tip = formatWechatError(e);
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick =
|
||||
wxAuthorize &&
|
||||
isWechatEnv() &&
|
||||
hasPartnerWxSession() &&
|
||||
!!savedProfile &&
|
||||
savedProfile.hasWechat === true;
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page partner-auth-page--quick">
|
||||
<header className="partner-auth-brand">
|
||||
<div className="partner-quick-avatar" style={{ width: 120, height: 120, margin: '0 auto 16px' }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 48 }}>wine_bar</span>
|
||||
</div>
|
||||
<h1 className="partner-auth-title" style={{ fontSize: 20 }}>杜康好客</h1>
|
||||
<p className="partner-auth-subtitle" style={{ fontSize: 12, letterSpacing: '0.2em', textTransform: 'uppercase' }}>城市合伙人端</p>
|
||||
</header>
|
||||
|
||||
<section className="partner-glass-card">
|
||||
<div className="partner-quick-badge">已识别账号</div>
|
||||
<div className="partner-quick-avatar">
|
||||
<span className="material-symbols-outlined">person</span>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<h2 className="headline-md">
|
||||
{quickName}
|
||||
{quickCompany ? (
|
||||
<span className="text-muted body-md" style={{ fontWeight: 400 }}> ({quickCompany})</span>
|
||||
) : null}
|
||||
</h2>
|
||||
<p className="text-muted body-md" style={{ letterSpacing: '0.1em', marginTop: 4 }}>
|
||||
{quickPhone ? maskPhone(quickPhone) : '暂无已保存账号'}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<nav style={{ width: '100%', maxWidth: 384, marginTop: 16 }}>
|
||||
{msg && <p className="partner-auth-msg" style={{ color: 'var(--color-error, #d33)', fontSize: 13, textAlign: 'center', marginBottom: 12 }}>{msg}</p>}
|
||||
<AgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
inputRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center', marginTop: 12, marginBottom: 12 }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="partner-btn-primary" style={{ display: 'block', textAlign: 'center', textDecoration: 'none', marginTop: 12 }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<Link to="/login" className="partner-btn-ghost" style={{ display: 'block', marginTop: 12 }}>切换账号</Link>
|
||||
</nav>
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
<span className="label-md" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
|
||||
{canWechatQuick ? '微信验证 · 7 天内免登录' : 'Secured by Dukang Heritage'}
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page">
|
||||
<div className="partner-auth-brand">
|
||||
@@ -214,12 +371,34 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="partner-auth-divider"><span>其他登录方式</span></div>
|
||||
<button type="button" className="partner-btn-wechat" onClick={() => void wechatLogin()} disabled={wxLoading}>
|
||||
<svg viewBox="0 0 24 24" fill="#07C160" aria-hidden>
|
||||
<path d="M8.25 4.5C4.52 4.5 1.5 7.04 1.5 10.17c0 1.78.98 3.37 2.5 4.48l-.63 1.88 2.19-1.09c.84.24 1.74.38 2.69.38.25 0 .5 0 .75-.03-.16-.53-.25-1.09-.25-1.66 0-3.13 3.02-5.67 6.75-5.67.57 0 1.13.06 1.66.17C15.17 6.13 12 4.5 8.25 4.5zm10.5 6.33c-3.11 0-5.62 2.12-5.62 4.73 0 2.61 2.51 4.73 5.62 4.73.79 0 1.54-.14 2.24-.38l1.83.91-.53-1.57c1.27-.92 2.08-2.25 2.08-3.73 0-2.61-2.51-4.73-5.62-4.73z" />
|
||||
</svg>
|
||||
<span>{wxLoading ? '跳转授权中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
{msg && (
|
||||
<p className="partner-auth-msg" style={{ color: 'var(--color-error, #d33)', fontSize: 13, textAlign: 'center' }}>
|
||||
{msg}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center' }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
请在微信内打开;首次请先用验证码登录,成功后将自动关联微信,之后可一键登录
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{hasPartnerWxSession() && savedProfile?.hasWechat && (
|
||||
<Link to="/login?quick=1" className="partner-link">微信快捷登录</Link>
|
||||
)}
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
|
||||
@@ -3,6 +3,12 @@ import { useNavigate, useParams } from 'react-router-dom';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import type { PartnerProxyOrderListItem } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderPayLabel,
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
@@ -21,14 +27,30 @@ function deliveryLabel(order: PartnerProxyOrderListItem) {
|
||||
if (t === 'ON_SITE_PICKUP') return '现场提货';
|
||||
if (t === 'CROSS_CITY') return '跨城配送';
|
||||
if (t === 'LOCAL') return '同城配送';
|
||||
return '线下代下单';
|
||||
return '代下单';
|
||||
}
|
||||
|
||||
type TrackNode = {
|
||||
time?: string;
|
||||
status?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
type TrackResult = {
|
||||
nodes?: TrackNode[];
|
||||
trackingNo?: string | null;
|
||||
provider?: string | null;
|
||||
manualQueryUrl?: string | null;
|
||||
};
|
||||
|
||||
export default function ProxyOrderDetailPage() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [order, setOrder] = useState<PartnerProxyOrderListItem | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [track, setTrack] = useState<TrackResult | null>(null);
|
||||
const [trackError, setTrackError] = useState('');
|
||||
const [paying, setPaying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = '代下单详情';
|
||||
@@ -41,7 +63,42 @@ export default function ProxyOrderDetailPage() {
|
||||
.catch((e) => setError(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !order) return;
|
||||
const dt = String(order.deliveryType || '').toUpperCase();
|
||||
if (dt === 'ON_SITE_PICKUP' || order.payStatus !== 'PAID') {
|
||||
setTrack(null);
|
||||
return;
|
||||
}
|
||||
void request<TrackResult>('PARTNER_H5', `/partner/proxy-orders/${id}/track`, { silent: true })
|
||||
.then(setTrack)
|
||||
.catch((e) => setTrackError(e instanceof Error ? e.message : '物流暂不可用'));
|
||||
}, [id, order]);
|
||||
|
||||
async function continuePay() {
|
||||
if (!id) return;
|
||||
setPaying(true);
|
||||
try {
|
||||
await request('PARTNER_H5', `/partner/proxy-orders/${id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
silent: true,
|
||||
});
|
||||
toastSuccess('支付成功');
|
||||
const refreshed = await request<PartnerProxyOrderListItem>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${id}`,
|
||||
);
|
||||
setOrder(refreshed);
|
||||
} catch (e) {
|
||||
toastError(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const img = order?.imageResource?.url || '';
|
||||
const isOnSite = String(order?.deliveryType || '').toUpperCase() === 'ON_SITE_PICKUP';
|
||||
|
||||
return (
|
||||
<div className="page-no-tab partner-orders-page">
|
||||
@@ -60,8 +117,11 @@ export default function ProxyOrderDetailPage() {
|
||||
<div className="partner-order-card" style={{ pointerEvents: 'none' }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {order.orderNo}</span>
|
||||
<span className="label-md" style={{ color: 'var(--color-success-green)', fontWeight: 600 }}>
|
||||
已完成
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(order.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(order.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
@@ -99,7 +159,7 @@ export default function ProxyOrderDetailPage() {
|
||||
<p className="body-md">姓名:{order.receiverName || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>手机:{order.receiverPhone || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
地址:{order.receiverAddress || (String(order.deliveryType).toUpperCase() === 'ON_SITE_PICKUP' ? '现场提货' : '—')}
|
||||
地址:{order.receiverAddress || (isOnSite ? '现场提货' : '—')}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -107,9 +167,64 @@ export default function ProxyOrderDetailPage() {
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>订单信息</h3>
|
||||
<p className="body-md">配送方式:{deliveryLabel(order)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>下单时间:{fmtTime(order.createdAt)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>支付状态:已付款(线下)</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>订单状态:已完成并发放权益</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
支付状态:{proxyOrderPayLabel(order.payStatus)}
|
||||
</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
订单状态:{proxyOrderStatusLabel(order.status)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{order.payStatus === 'UNPAID' || order.status === 'PENDING_PAY' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={paying}
|
||||
onClick={() => void continuePay()}
|
||||
>
|
||||
{paying ? '处理中…' : '继续支付(模拟)'}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{!isOnSite && order.payStatus === 'PAID' ? (
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>物流信息</h3>
|
||||
{trackError ? (
|
||||
<p className="label-md text-muted">{trackError}</p>
|
||||
) : !track ? (
|
||||
<p className="label-md text-muted">加载物流…</p>
|
||||
) : (
|
||||
<>
|
||||
{track.trackingNo ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
运单号:{track.trackingNo}
|
||||
{track.provider ? `(${track.provider})` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
{track.manualQueryUrl ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
<a href={track.manualQueryUrl} target="_blank" rel="noreferrer">
|
||||
查看物流官网
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
{(track.nodes ?? []).length === 0 ? (
|
||||
<p className="label-md text-muted">暂无物流轨迹(待总部发货后更新)</p>
|
||||
) : (
|
||||
<ul style={{ paddingLeft: 18, margin: 0 }}>
|
||||
{(track.nodes ?? []).map((n, i) => (
|
||||
<li key={`${n.time}-${i}`} className="body-md" style={{ marginBottom: 8 }}>
|
||||
<div className="label-md text-muted">{fmtTime(n.time)}</div>
|
||||
<div>{n.description || n.status || '—'}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,10 @@ import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import type { PartnerProxyOrderListItem, PartnerProxyOrderListResponse } from '@dukang/shared-types';
|
||||
import { isLoggedIn, request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
@@ -98,8 +102,11 @@ export default function ProxyOrderListPage() {
|
||||
<Link key={orderId} to={`/center/proxy-orders/${orderId}`} className="partner-order-card" style={{ marginBottom: 12 }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {o.orderNo}</span>
|
||||
<span className="label-md" style={{ color: 'var(--color-success-green)', fontWeight: 600 }}>
|
||||
已完成
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(o.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(o.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import QRCode from 'qrcode';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
||||
import ChinaRegionPicker from '../components/ChinaRegionPicker';
|
||||
import { request } from '../lib/api';
|
||||
import { getToken, request } from '../lib/api';
|
||||
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
||||
import {
|
||||
clearProxyOrderDraft,
|
||||
@@ -11,11 +13,16 @@ import {
|
||||
type ProxyOrderDraft,
|
||||
} from '../lib/proxyOrderDraft';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { fetchPartnerProfile, partnerHasWechatBinding } from '../lib/wechat-auth';
|
||||
import type {
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderCreateRequest,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
ProxyPayMethod,
|
||||
} from '@dukang/shared-types';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
@@ -57,10 +64,34 @@ export default function ProxyOrderPage() {
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [payMethod, setPayMethod] = useState<ProxyPayMethod>('NATIVE');
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
const [paying, setPaying] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
const regionLabel = region ? formatRegionLabel(region) : '';
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!codeUrl) {
|
||||
setQrDataUrl(null);
|
||||
return;
|
||||
}
|
||||
void QRCode.toDataURL(codeUrl, { width: 220, margin: 1 }).then(setQrDataUrl).catch(() => setQrDataUrl(null));
|
||||
}, [codeUrl]);
|
||||
|
||||
function persistDraft(overrides?: Partial<ProxyOrderDraft>) {
|
||||
saveProxyOrderDraft({
|
||||
phone,
|
||||
@@ -157,6 +188,82 @@ export default function ProxyOrderPage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<{ payStatus: string; orderNo: string }>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay-status`,
|
||||
{ silent: true },
|
||||
)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
toastSuccess(`支付成功:${st.orderNo}`);
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function startPay(orderId: string, method: ProxyPayMethod) {
|
||||
setPaying(true);
|
||||
setMsg('');
|
||||
try {
|
||||
if (method === 'JSAPI') {
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开合伙人端以使用微信代付');
|
||||
}
|
||||
const profile = await fetchPartnerProfile();
|
||||
if (!partnerHasWechatBinding(profile)) {
|
||||
throw new Error('请先绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const pay = await request<ProxyOrderPayResponse>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: method }),
|
||||
silent: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (pay.mode === 'mock') {
|
||||
toastSuccess('支付成功');
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'native' && pay.codeUrl) {
|
||||
setCodeUrl(pay.codeUrl);
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'jsapi' && pay.prepay) {
|
||||
await invokeWechatPay(pay.prepay, {
|
||||
apiBase: '/api/v1',
|
||||
clientApp: 'PARTNER_H5',
|
||||
getAccessToken: getToken,
|
||||
platform: 'wechat-h5',
|
||||
});
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('支付发起失败');
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
setMsg('');
|
||||
const err = validateForm();
|
||||
@@ -181,14 +288,16 @@ export default function ProxyOrderPage() {
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<{ id: string; orderNo: string }>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
const order = await request<ProxyOrderCreateResponse>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
silent: true,
|
||||
});
|
||||
toastSuccess(`代下单成功:${order.orderNo}`);
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${order.id}`);
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setCodeUrl(null);
|
||||
await startPay(order.id, payMethod);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '下单失败');
|
||||
} finally {
|
||||
@@ -196,6 +305,25 @@ export default function ProxyOrderPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMockConfirm() {
|
||||
if (!created) return;
|
||||
setPaying(true);
|
||||
try {
|
||||
await request('PARTNER_H5', `/partner/proxy-orders/${created.id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
silent: true,
|
||||
});
|
||||
stopPoll();
|
||||
toastSuccess('支付成功');
|
||||
navigate(`/center/proxy-orders/${created.id}`, { replace: true });
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '模拟支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const deliveryLabel =
|
||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||
@@ -206,10 +334,97 @@ export default function ProxyOrderPage() {
|
||||
|
||||
return (
|
||||
<div className="page partner-proxy-order-page">
|
||||
<PageHeader title="代下单" onBack={() => navigate(-1)} />
|
||||
<PageHeader title={step === 'pay' ? '代下单支付' : '代下单'} onBack={() => navigate(-1)} />
|
||||
|
||||
<main className="partner-form-card" style={{ margin: '0 16px 24px' }}>
|
||||
{loadingOptions ? (
|
||||
{step === 'pay' && created ? (
|
||||
<>
|
||||
<p className="body-md">
|
||||
订单 {created.orderNo} · 应付 ¥{fmtMoney(created.payAmount)}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
{created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付成功后进入现场提货闭环'
|
||||
: '支付成功后进入待发货,由总部履约'}
|
||||
</p>
|
||||
|
||||
<section className="partner-form-section" style={{ marginTop: 16 }}>
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('NATIVE');
|
||||
void startPay(created.id, 'NATIVE');
|
||||
}}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('JSAPI');
|
||||
void startPay(created.id, 'JSAPI');
|
||||
}}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{payMethod === 'NATIVE' ? (
|
||||
<div style={{ textAlign: 'center', marginTop: 16 }}>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt="收款码" width={220} height={220} style={{ margin: '0 auto' }} />
|
||||
) : (
|
||||
<p className="label-md text-muted">{paying ? '生成收款码中…' : '暂无收款码'}</p>
|
||||
)}
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
请使用微信扫码支付
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={paying}
|
||||
onClick={() => void handleMockConfirm()}
|
||||
>
|
||||
{paying ? '处理中…' : '模拟支付成功'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<p className="label-md text-muted">将调起微信支付(本地 Mock 可能直接入账)</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 12 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay(created.id, 'JSAPI')}
|
||||
>
|
||||
{paying ? '支付中…' : '重新调起微信代付'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block"
|
||||
style={{ marginTop: 8 }}
|
||||
disabled={paying}
|
||||
onClick={() => void handleMockConfirm()}
|
||||
>
|
||||
模拟支付成功
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{msg ? (
|
||||
<p className="partner-form-error" role="alert" style={{ marginTop: 12 }}>
|
||||
{msg}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : loadingOptions ? (
|
||||
<p className="label-md text-muted">加载商品…</p>
|
||||
) : (
|
||||
<>
|
||||
@@ -350,11 +565,36 @@ export default function ProxyOrderPage() {
|
||||
checked={autoReceive}
|
||||
onChange={(e) => setAutoReceive(e.target.checked)}
|
||||
/>
|
||||
<span>同意自动收货(线下代下单提交后视为已送达并发放权益)</span>
|
||||
<span>同意自动收货(配送到址必选)</span>
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('NATIVE')}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('JSAPI')}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8, lineHeight: 1.5 }}>
|
||||
{payMethod === 'NATIVE'
|
||||
? '提交后展示商家收款码,客户或现场扫码支付'
|
||||
: '提交后在微信内由您代客户完成支付(需已绑定微信)'}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="partner-proxy-fee-card">
|
||||
<h3 className="headline-md">费用明细</h3>
|
||||
{previewLoading ? (
|
||||
@@ -398,15 +638,15 @@ export default function ProxyOrderPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
disabled={submitting || !preview}
|
||||
disabled={submitting || paying || !preview}
|
||||
onClick={() => void submit()}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
{submitting ? '提交中…' : '确认代下单'}
|
||||
{submitting || paying ? '处理中…' : '提交并支付'}
|
||||
</button>
|
||||
|
||||
<p className="label-md text-muted" style={{ marginTop: 12, lineHeight: 1.5 }}>
|
||||
确认线下已收款后提交:将自动创建/关联用户,订单标记为代下单并直接完成,同时发放对应权益。客户订单列表会显示您的姓名。
|
||||
提交后进入在线支付;支付成功后发放权益。配送单将进入待发货由总部履约,现场提货走自提闭环。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getStoreProfile, hasShopWxSession } from '../lib/api';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
|
||||
const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
|
||||
@@ -25,6 +26,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getStoreProfile();
|
||||
if (profile && hasShopWxSession() && location.pathname !== '/login') {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import {
|
||||
clearAuth,
|
||||
ensureSession,
|
||||
@@ -14,6 +16,12 @@ import {
|
||||
type ShopSessionPayload,
|
||||
type StoreSessionStore,
|
||||
} from '../lib/api';
|
||||
import {
|
||||
fetchClientConfig,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
type StoreSessionContextValue = {
|
||||
ready: boolean;
|
||||
@@ -26,6 +34,12 @@ type StoreSessionContextValue = {
|
||||
|
||||
const StoreSessionContext = createContext<StoreSessionContextValue | null>(null);
|
||||
|
||||
function deriveSelectStore(session: ShopSessionPayload, nextStore: StoreSessionStore | null) {
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
return stores.length > 1 && !storeId;
|
||||
}
|
||||
|
||||
export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [authenticated, setAuthenticated] = useState(false);
|
||||
@@ -43,9 +57,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
: null;
|
||||
setStore(nextStore);
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
setNeedsSelectStore(stores.length > 1 && !storeId);
|
||||
setNeedsSelectStore(deriveSelectStore(session, nextStore));
|
||||
}, []);
|
||||
|
||||
const resetSession = useCallback(() => {
|
||||
@@ -59,6 +71,23 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (isWechatEnv() && params.get('code')) {
|
||||
try {
|
||||
const config = await fetchClientConfig();
|
||||
if (isWxAuthorizeEnabled(config)) {
|
||||
const result = await handleShopWechatCallback();
|
||||
if (result && !cancelled) {
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) applySession(session);
|
||||
}
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
} catch {
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await ensureSession();
|
||||
if (cancelled) return;
|
||||
setAuthenticated(result.authenticated);
|
||||
@@ -73,7 +102,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [resetSession]);
|
||||
}, [applySession, resetSession]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ ready, authenticated, needsSelectStore, store, applySession, resetSession }),
|
||||
|
||||
@@ -1,14 +1,39 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import AppImage from '@dukang/shared-ui/AppImage';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
import {
|
||||
getLastPhone,
|
||||
getStoreProfile,
|
||||
hasShopWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type ShopSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { routeAfterShopLogin } from './SelectStorePage';
|
||||
import {
|
||||
bindShopWechatAfterSmsLogin,
|
||||
fetchClientConfig,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
loginShopWithWechat,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定门店账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function ShopAgreementCheckbox({
|
||||
agreed,
|
||||
@@ -43,14 +68,44 @@ function ShopAgreementCheckbox({
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession } = useStoreSession();
|
||||
const [params, setSearchParams] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getStoreProfile();
|
||||
const [phone, setPhone] = useState(getLastPhone());
|
||||
const [code, setCode] = useState('');
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||
void handleShopWechatCallback()
|
||||
.then((result) => {
|
||||
if (!result) return;
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) {
|
||||
applySession(session);
|
||||
stripOAuthParamsFromLocation();
|
||||
setSearchParams({}, { replace: true });
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
})
|
||||
.catch((e) => setMsg(formatWechatError(e)));
|
||||
}, [applySession, navigate, params, setSearchParams, wxAuthorize]);
|
||||
|
||||
const quickStoreName = savedProfile?.storeName ?? '门店管理中心';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先阅读并同意用户协议');
|
||||
@@ -95,6 +150,11 @@ export default function LoginPage() {
|
||||
});
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindShopWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
routeAfterShopLogin(data, navigate);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '登录失败');
|
||||
@@ -103,6 +163,103 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg('请在微信内打开以使用微信一键登录');
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
const session = await loginShopWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
} catch (e) {
|
||||
setMsg(formatWechatError(e));
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick = wxAuthorize && isWechatEnv() && hasShopWxSession() && !!savedProfile;
|
||||
|
||||
return (
|
||||
<div className="shop-quick-login-page">
|
||||
<header className="shop-quick-header">
|
||||
<AppImage src="/logo.png" alt="杜康好客" wrapperClassName="shop-quick-logo" fit="contain" />
|
||||
<h1 className="shop-quick-welcome">欢迎回来</h1>
|
||||
<div className="shop-quick-welcome-line" />
|
||||
</header>
|
||||
|
||||
<section className="shop-quick-store-card">
|
||||
<div className="shop-quick-store-inner">
|
||||
<div className="shop-quick-store-icon">
|
||||
<span className="material-symbols-outlined shop-fill-icon">storefront</span>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="shop-quick-store-name">{quickStoreName}</h2>
|
||||
<p className="shop-quick-store-phone">{maskPhone(quickPhone)}</p>
|
||||
</div>
|
||||
<span className="shop-quick-verified">
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 14 }}>verified_user</span>
|
||||
认证门店
|
||||
</span>
|
||||
<div className="shop-quick-switch">
|
||||
<Link to="/login">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>sync</span>
|
||||
切换账号
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="shop-quick-actions">
|
||||
{msg && <p className="shop-login-msg">{msg}</p>}
|
||||
<ShopAgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
labelRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shop-quick-login-btn shop-quick-login-btn--wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center' }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="shop-quick-login-btn" style={{ textAlign: 'center', textDecoration: 'none' }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<div className="shop-quick-secure">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 16 }}>lock</span>
|
||||
<span>{canWechatQuick ? '微信验证 · 7 天内免登录' : '加密环境安全登录中'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="shop-quick-footer">
|
||||
<p className="shop-login-footer-brand">SECURED BY DUKANG HERITAGE</p>
|
||||
<p style={{ fontSize: 10, fontFamily: 'var(--font-label)' }}>© 2024 杜康酒业门店管理系统</p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="shop-login-page">
|
||||
<header className="shop-login-hero">
|
||||
@@ -172,8 +329,29 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="shop-login-divider">
|
||||
<span className="shop-login-divider-line" />
|
||||
<span className="shop-login-divider-text">或者</span>
|
||||
<span className="shop-login-divider-line" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="shop-login-wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center', marginTop: 12 }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
手机号验证成功后,7 天内无需再次输入验证码;微信内登录将自动关联微信
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
@@ -183,6 +361,11 @@ export default function LoginPage() {
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ opacity: 0.3, fontSize: 20, color: 'var(--color-outline)' }}>
|
||||
security
|
||||
</span>
|
||||
{hasShopWxSession() && savedProfile && (
|
||||
<p style={{ marginTop: 16, textAlign: 'center' }}>
|
||||
<Link to="/login?quick=1" className="text-primary body-md">微信快捷登录</Link>
|
||||
</p>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在生产机上初始化 Staging 目录(同机双栈,一次性)
|
||||
# 用法(SSH 到服务器后):
|
||||
# APP_ROOT=/opt/dukang bash /opt/dukang/deploy/bootstrap-staging.sh
|
||||
# 或本机:
|
||||
# ssh root@host 'bash -s' < deploy/bootstrap-staging.sh
|
||||
set -euo pipefail
|
||||
|
||||
PROD_ROOT="${PROD_ROOT:-/opt/dukang}"
|
||||
STAGING_ROOT="${STAGING_ROOT:-/opt/dukang-staging}"
|
||||
GIT_REMOTE_URL="${GIT_REMOTE_URL:-}"
|
||||
GIT_BRANCH="${GIT_BRANCH:-dev}"
|
||||
|
||||
if [[ -d "$STAGING_ROOT/.git" ]]; then
|
||||
echo "==> 已存在 $STAGING_ROOT,跳过 clone"
|
||||
else
|
||||
if [[ -z "$GIT_REMOTE_URL" ]]; then
|
||||
if [[ -d "$PROD_ROOT/.git" ]]; then
|
||||
GIT_REMOTE_URL="$(git -C "$PROD_ROOT" remote get-url origin)"
|
||||
else
|
||||
echo "错误: 请设置 GIT_REMOTE_URL,或确保 $PROD_ROOT 为 git 仓库" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
echo "==> clone $GIT_REMOTE_URL → $STAGING_ROOT (branch $GIT_BRANCH)"
|
||||
git clone --branch "$GIT_BRANCH" "$GIT_REMOTE_URL" "$STAGING_ROOT"
|
||||
fi
|
||||
|
||||
mkdir -p "$STAGING_ROOT/server/dukang-api"
|
||||
if [[ ! -f "$STAGING_ROOT/server/dukang-api/.env.staging" ]]; then
|
||||
if [[ -f "$STAGING_ROOT/server/dukang-api/.env.staging.example" ]]; then
|
||||
cp "$STAGING_ROOT/server/dukang-api/.env.staging.example" \
|
||||
"$STAGING_ROOT/server/dukang-api/.env.staging"
|
||||
echo "==> 已生成 .env.staging(请编辑 DATABASE_URL / Redis / 微信后 sync 或本机改)"
|
||||
else
|
||||
echo "WARN: 无 .env.staging.example,请手动创建 .env.staging"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "==> 下一步:"
|
||||
echo " 1. 创建 RDS 库 dukang_staging,填好 $STAGING_ROOT/server/dukang-api/.env.staging"
|
||||
echo " 2. DNS: api-test/user-test/shop-test/partner-test/admin-test.dukanghaoke.com → 本机"
|
||||
echo " 3. 启用 nginx: ln -sf $STAGING_ROOT/deploy/nginx-dukang-staging.conf /etc/nginx/sites-enabled/"
|
||||
echo " nginx -t && systemctl reload nginx(证书需含 *-test SAN)"
|
||||
echo " 4. 本机发版: bash deploy/deploy-staging.sh -- --seed --accept-data-loss"
|
||||
echo "==> bootstrap 完成"
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# 发生产环境:分支默认 main → /opt/dukang(8090–8094)
|
||||
set -euo pipefail
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
echo "==> 即将发往 PRODUCTION(main → /opt/dukang)"
|
||||
exec bash "$SCRIPT_DIR/deploy.sh" --env production "$@"
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# 发测试环境:分支默认 dev → /opt/dukang-staging(8190–8194)
|
||||
set -euo pipefail
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
exec bash "$SCRIPT_DIR/deploy.sh" --env staging "$@"
|
||||
@@ -4,8 +4,14 @@ DEPLOY_USER=root
|
||||
DEPLOY_PORT=22
|
||||
# DEPLOY_SSH_KEY=~/.ssh/id_rsa
|
||||
|
||||
# 同机双栈目录
|
||||
PROD_APP_ROOT=/opt/dukang
|
||||
STAGING_APP_ROOT=/opt/dukang-staging
|
||||
# 兼容旧字段(未指定 --env 时可能用到)
|
||||
APP_ROOT=/opt/dukang
|
||||
|
||||
# 生产仓库(SSH)
|
||||
GIT_REPO_URL=git@git.yqidian.com:jacy/dukang.git
|
||||
GIT_REMOTE=origin
|
||||
GIT_BRANCH=dev
|
||||
# 默认分支已由 --env 决定:staging→dev,production→main
|
||||
# GIT_BRANCH=dev
|
||||
|
||||
+65
-20
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# 本地执行:SSH 到服务器拉代码并发布
|
||||
# 本地执行:SSH 到服务器拉代码并发布(支持 staging / production 同机双栈)
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
@@ -9,33 +9,35 @@ DEPLOY_HOST=""
|
||||
DEPLOY_USER="root"
|
||||
DEPLOY_PORT="22"
|
||||
DEPLOY_SSH_KEY=""
|
||||
APP_ROOT="/opt/dukang"
|
||||
APP_ROOT=""
|
||||
GIT_REMOTE="origin"
|
||||
GIT_BRANCH="dev"
|
||||
GIT_BRANCH=""
|
||||
DUKANG_DEPLOY_ENV=""
|
||||
|
||||
CHECK_ONLY=false
|
||||
RELEASE_ARGS=()
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
用法: deploy/deploy.sh [选项] [-- 远程 release 参数]
|
||||
用法: deploy/deploy.sh --env staging|production [选项] [-- 远程 release 参数]
|
||||
|
||||
环境配置: deploy/deploy.env(可复制 deploy.env.example)
|
||||
|
||||
选项:
|
||||
--env ENV staging(测试)| production(生产)【必填,或用 deploy-staging/prod.sh】
|
||||
--host HOST 服务器地址(覆盖 deploy.env)
|
||||
--user USER SSH 用户,默认 root
|
||||
--port PORT SSH 端口,默认 22
|
||||
--key PATH SSH 私钥路径
|
||||
--branch BRANCH 发布分支,默认 dev
|
||||
--branch BRANCH 发布分支(staging 默认 dev,production 默认 main)
|
||||
--check 仅 SSH 连接并查看 PM2 / 端口状态
|
||||
-h, --help 显示帮助
|
||||
|
||||
示例:
|
||||
./deploy/deploy.sh
|
||||
./deploy/deploy.sh --branch main
|
||||
./deploy/deploy.sh -- --skip-db
|
||||
./deploy/deploy.sh -- --seed --accept-data-loss
|
||||
./deploy/deploy-staging.sh -- --skip-db
|
||||
./deploy/deploy-prod.sh -- --skip-db
|
||||
./deploy/deploy.sh --env staging --branch dev -- --skip-db
|
||||
./deploy/deploy.sh --env production --branch main -- --skip-db
|
||||
EOF
|
||||
}
|
||||
|
||||
@@ -48,6 +50,7 @@ load_env() {
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--env) DUKANG_DEPLOY_ENV="$2"; shift 2 ;;
|
||||
--host) DEPLOY_HOST="$2"; shift 2 ;;
|
||||
--user) DEPLOY_USER="$2"; shift 2 ;;
|
||||
--port) DEPLOY_PORT="$2"; shift 2 ;;
|
||||
@@ -66,6 +69,46 @@ done
|
||||
|
||||
load_env
|
||||
|
||||
# 兼容旧调用:未传 --env 时,若 GIT_BRANCH=main 视为生产,否则 staging
|
||||
if [[ -z "$DUKANG_DEPLOY_ENV" ]]; then
|
||||
if [[ "${GIT_BRANCH:-}" == "main" || "${GIT_BRANCH:-}" == "master" ]]; then
|
||||
DUKANG_DEPLOY_ENV=production
|
||||
else
|
||||
DUKANG_DEPLOY_ENV=staging
|
||||
echo "WARN: 未指定 --env,默认按 staging 发测试环境。生产请用 --env production 或 deploy-prod.sh" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
case "$DUKANG_DEPLOY_ENV" in
|
||||
staging|stage|test) DUKANG_DEPLOY_ENV=staging ;;
|
||||
production|prod) DUKANG_DEPLOY_ENV=production ;;
|
||||
*)
|
||||
echo "错误: --env 须为 staging 或 production" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ "$DUKANG_DEPLOY_ENV" == "staging" ]]; then
|
||||
APP_ROOT="${STAGING_APP_ROOT:-${APP_ROOT:-/opt/dukang-staging}}"
|
||||
# 若 deploy.env 里 APP_ROOT 仍是生产路径,staging 强制用 STAGING_APP_ROOT 或默认
|
||||
if [[ -n "${STAGING_APP_ROOT:-}" ]]; then
|
||||
APP_ROOT="$STAGING_APP_ROOT"
|
||||
elif [[ "$APP_ROOT" == "/opt/dukang" ]]; then
|
||||
APP_ROOT="/opt/dukang-staging"
|
||||
fi
|
||||
GIT_BRANCH="${GIT_BRANCH:-dev}"
|
||||
PORT_GREP='819[0-4]'
|
||||
else
|
||||
APP_ROOT="${PROD_APP_ROOT:-${APP_ROOT:-/opt/dukang}}"
|
||||
if [[ -n "${PROD_APP_ROOT:-}" ]]; then
|
||||
APP_ROOT="$PROD_APP_ROOT"
|
||||
elif [[ "$APP_ROOT" == "/opt/dukang-staging" ]]; then
|
||||
APP_ROOT="/opt/dukang"
|
||||
fi
|
||||
GIT_BRANCH="${GIT_BRANCH:-main}"
|
||||
PORT_GREP='809[0-4]'
|
||||
fi
|
||||
|
||||
if [[ -z "$DEPLOY_HOST" ]]; then
|
||||
echo "错误: 未配置 DEPLOY_HOST。请创建 deploy/deploy.env 或使用 --host" >&2
|
||||
exit 1
|
||||
@@ -82,8 +125,8 @@ run_remote() {
|
||||
}
|
||||
|
||||
if [[ "$CHECK_ONLY" == true ]]; then
|
||||
echo "==> 检查 $TARGET"
|
||||
run_remote "pm2 list; ss -tlnp | grep -E '809[0-3]' || true"
|
||||
echo "==> 检查 $TARGET ($DUKANG_DEPLOY_ENV)"
|
||||
run_remote "pm2 list; ss -tlnp | grep -E '$PORT_GREP' || true"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -92,7 +135,7 @@ if [[ ${#RELEASE_ARGS[@]} -gt 0 ]]; then
|
||||
REMOTE_RELEASE_ARGS="${RELEASE_ARGS[*]}"
|
||||
fi
|
||||
|
||||
echo "==> 发布到 $TARGET ($GIT_BRANCH)"
|
||||
echo "==> 发布到 $TARGET env=$DUKANG_DEPLOY_ENV branch=$GIT_BRANCH root=$APP_ROOT"
|
||||
|
||||
run_remote bash -s <<EOF
|
||||
set -euo pipefail
|
||||
@@ -100,26 +143,28 @@ APP_ROOT="$APP_ROOT"
|
||||
GIT_REMOTE="$GIT_REMOTE"
|
||||
GIT_BRANCH="$GIT_BRANCH"
|
||||
RELEASE_ARGS="$REMOTE_RELEASE_ARGS"
|
||||
DUKANG_DEPLOY_ENV="$DUKANG_DEPLOY_ENV"
|
||||
export DEPLOY_TRIGGER=manual
|
||||
export APP_ROOT
|
||||
export DUKANG_DEPLOY_ENV
|
||||
|
||||
cd "\$APP_ROOT"
|
||||
|
||||
if [[ ! -d .git ]]; then
|
||||
echo "错误: \$APP_ROOT 不是 git 仓库" >&2
|
||||
echo "错误: \$APP_ROOT 不是 git 仓库。请先 clone 到该目录(staging 建议 /opt/dukang-staging)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> 拉取代码"
|
||||
git fetch "\$GIT_REMOTE"
|
||||
git checkout "\$GIT_BRANCH"
|
||||
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
|
||||
|
||||
if [[ -n "\$RELEASE_ARGS" ]]; then
|
||||
echo "==> 拉取代码"
|
||||
git fetch "\$GIT_REMOTE"
|
||||
git checkout "\$GIT_BRANCH"
|
||||
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
|
||||
bash deploy/remote-release.sh \$RELEASE_ARGS
|
||||
else
|
||||
echo "==> 拉取代码并发布(auto-release)"
|
||||
bash deploy/auto-release.sh
|
||||
bash deploy/remote-release.sh --skip-db
|
||||
fi
|
||||
EOF
|
||||
|
||||
echo "==> 本地发布命令已完成"
|
||||
echo "==> 本地发布命令已完成 ($DUKANG_DEPLOY_ENV)"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** PM2 ecosystem — 杜康好客生产部署 */
|
||||
const APP_ROOT = '/opt/dukang';
|
||||
const APP_ROOT = process.env.APP_ROOT || '/opt/dukang';
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
@@ -11,6 +11,7 @@ module.exports = {
|
||||
exec_mode: 'fork',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
APP_ENV: 'production',
|
||||
PORT: 8090,
|
||||
},
|
||||
},
|
||||
@@ -62,6 +63,7 @@ module.exports = {
|
||||
exec_mode: 'fork',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
APP_ENV: 'production',
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/** PM2 ecosystem — 杜康好客 Staging(同机双栈,端口 8190–8194) */
|
||||
const APP_ROOT = process.env.APP_ROOT || '/opt/dukang-staging';
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'dukang-stg-api',
|
||||
cwd: `${APP_ROOT}/server/dukang-api`,
|
||||
script: 'dist/main.js',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
APP_ENV: 'staging',
|
||||
PORT: 8190,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'dukang-stg-h5-user',
|
||||
cwd: `${APP_ROOT}/apps/mini-user`,
|
||||
script: 'npx',
|
||||
args: 'serve dist -l 8191 -c serve.json',
|
||||
interpreter: 'none',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
},
|
||||
{
|
||||
name: 'dukang-stg-h5-shop',
|
||||
cwd: `${APP_ROOT}/apps/h5-shop`,
|
||||
script: 'npx',
|
||||
args: 'serve -s dist -l 8192',
|
||||
interpreter: 'none',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
},
|
||||
{
|
||||
name: 'dukang-stg-h5-partner',
|
||||
cwd: `${APP_ROOT}/apps/h5-partner`,
|
||||
script: 'npx',
|
||||
args: 'serve -s dist -l 8193',
|
||||
interpreter: 'none',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
},
|
||||
{
|
||||
name: 'dukang-stg-admin-web',
|
||||
cwd: `${APP_ROOT}/apps/admin-web`,
|
||||
script: 'npx',
|
||||
args: 'serve -s dist -l 8194',
|
||||
interpreter: 'none',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,195 @@
|
||||
# 杜康好客 — Staging(测试)*-test.dukanghaoke.com → 8190–8194
|
||||
# 证书:可与生产共用 user.dukanghaoke.com 证书(SAN 含 *-test),或单独申请
|
||||
# 启用:ln -sf /opt/dukang-staging/deploy/nginx-dukang-staging.conf /etc/nginx/sites-enabled/
|
||||
# nginx -t && systemctl reload nginx
|
||||
|
||||
# HTTP → HTTPS
|
||||
server {
|
||||
listen 80;
|
||||
server_name user-test.dukanghaoke.com shop-test.dukanghaoke.com partner-test.dukanghaoke.com admin-test.dukanghaoke.com api-test.dukanghaoke.com;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
default_type "text/plain";
|
||||
}
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
# api-test.dukanghaoke.com → 8190
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name api-test.dukanghaoke.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/user.dukanghaoke.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/user.dukanghaoke.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
}
|
||||
}
|
||||
|
||||
# user-test.dukanghaoke.com → 8191
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name user-test.dukanghaoke.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/user.dukanghaoke.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/user.dukanghaoke.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8191;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
|
||||
# shop-test.dukanghaoke.com → 8192
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name shop-test.dukanghaoke.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/user.dukanghaoke.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/user.dukanghaoke.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8192;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
|
||||
# partner-test.dukanghaoke.com → 8193
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name partner-test.dukanghaoke.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/user.dukanghaoke.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/user.dukanghaoke.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8193;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
|
||||
# admin-test.dukanghaoke.com → 8194
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name admin-test.dukanghaoke.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/user.dukanghaoke.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/user.dukanghaoke.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8194;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ server {
|
||||
default_type "text/plain";
|
||||
}
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
@@ -53,6 +55,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
@@ -89,6 +93,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
@@ -125,6 +131,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# 微信 JS 安全域名校验文件(Staging)
|
||||
# 文件放在 /opt/dukang-staging/public/MP_verify_*.txt
|
||||
location ~ ^/MP_verify_.*\.txt$ {
|
||||
root /opt/dukang-staging/public;
|
||||
default_type text/plain;
|
||||
charset utf-8;
|
||||
access_log off;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# 微信 JS 安全域名校验文件(根目录直出,勿走 SPA)
|
||||
# 文件放在 /opt/dukang/public/MP_verify_*.txt
|
||||
location ~ ^/MP_verify_.*\.txt$ {
|
||||
root /opt/dukang/public;
|
||||
default_type text/plain;
|
||||
charset utf-8;
|
||||
access_log off;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
+66
-21
@@ -1,9 +1,50 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在服务器上执行:拉取后的常规发版(不覆盖 .env.production、默认不 seed)
|
||||
# 在服务器上执行:拉取后的常规发版(不覆盖 env 文件、默认不 seed)
|
||||
# 通过 DUKANG_DEPLOY_ENV=staging|production 区分同机双栈
|
||||
set -euo pipefail
|
||||
|
||||
APP_ROOT="${APP_ROOT:-/opt/dukang}"
|
||||
DUKANG_DEPLOY_ENV="${DUKANG_DEPLOY_ENV:-production}"
|
||||
case "$DUKANG_DEPLOY_ENV" in
|
||||
staging|stage|test) DUKANG_DEPLOY_ENV=staging ;;
|
||||
production|prod) DUKANG_DEPLOY_ENV=production ;;
|
||||
*)
|
||||
echo "错误: DUKANG_DEPLOY_ENV 须为 staging 或 production,当前=$DUKANG_DEPLOY_ENV" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ "$DUKANG_DEPLOY_ENV" == "staging" ]]; then
|
||||
APP_ROOT="${APP_ROOT:-/opt/dukang-staging}"
|
||||
ENV_FILE_NAME=".env.staging"
|
||||
ECOSYSTEM_FILE="ecosystem.staging.config.cjs"
|
||||
VITE_API_DEFAULT="https://api-test.dukanghaoke.com"
|
||||
API_PORT=8190
|
||||
USER_PORT=8191
|
||||
PORT_GREP='819[0-4]'
|
||||
PM2_API=dukang-stg-api
|
||||
PM2_USER=dukang-stg-h5-user
|
||||
PM2_SHOP=dukang-stg-h5-shop
|
||||
PM2_PARTNER=dukang-stg-h5-partner
|
||||
PM2_ADMIN=dukang-stg-admin-web
|
||||
else
|
||||
APP_ROOT="${APP_ROOT:-/opt/dukang}"
|
||||
ENV_FILE_NAME=".env.production"
|
||||
ECOSYSTEM_FILE="ecosystem.config.cjs"
|
||||
VITE_API_DEFAULT="https://api.dukanghaoke.com"
|
||||
API_PORT=8090
|
||||
USER_PORT=8091
|
||||
PORT_GREP='809[0-4]'
|
||||
PM2_API=dukang-api
|
||||
PM2_USER=dukang-h5-user
|
||||
PM2_SHOP=dukang-h5-shop
|
||||
PM2_PARTNER=dukang-h5-partner
|
||||
PM2_ADMIN=dukang-admin-web
|
||||
fi
|
||||
|
||||
DEPLOY_DIR="$APP_ROOT/deploy"
|
||||
export APP_ROOT
|
||||
export APP_ENV="$DUKANG_DEPLOY_ENV"
|
||||
export DUKANG_ENV_FILE="$ENV_FILE_NAME"
|
||||
|
||||
SKIP_BUILD=false
|
||||
SKIP_DB=false
|
||||
@@ -11,9 +52,11 @@ RUN_SEED=false
|
||||
DB_PUSH_ACCEPT_DATA_LOSS=false
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
cat <<EOF
|
||||
用法: remote-release.sh [选项]
|
||||
|
||||
环境: DUKANG_DEPLOY_ENV=${DUKANG_DEPLOY_ENV} APP_ROOT=${APP_ROOT} env=${ENV_FILE_NAME}
|
||||
|
||||
--skip-build 跳过 pnpm build(仅重启 PM2)
|
||||
--skip-db 跳过 Prisma generate / db push
|
||||
--seed 执行 prisma:seed(默认不执行)
|
||||
@@ -36,6 +79,8 @@ done
|
||||
|
||||
cd "$APP_ROOT"
|
||||
|
||||
echo "==> 发版环境: $DUKANG_DEPLOY_ENV ($APP_ROOT)"
|
||||
|
||||
echo "==> 1. 启用 pnpm"
|
||||
corepack enable 2>/dev/null || true
|
||||
corepack prepare pnpm@11.2.2 --activate 2>/dev/null || true
|
||||
@@ -47,15 +92,16 @@ export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=8192}"
|
||||
export TARO_H5_PUBLIC_PATH="${TARO_H5_PUBLIC_PATH:-/user/}"
|
||||
export TARO_H5_ROUTER_BASENAME="${TARO_H5_ROUTER_BASENAME:-/user}"
|
||||
# C 端 H5 编译期注入的 API origin(勿落到 localhost)
|
||||
export VITE_API_TARGET="${VITE_API_TARGET:-https://api.dukanghaoke.com}"
|
||||
export VITE_API_TARGET="${VITE_API_TARGET:-$VITE_API_DEFAULT}"
|
||||
export VITE_APP_ENV="$DUKANG_DEPLOY_ENV"
|
||||
pnpm approve-builds --all 2>/dev/null || true
|
||||
pnpm install --frozen-lockfile 2>/dev/null || pnpm install
|
||||
|
||||
if [[ "$SKIP_DB" == false ]]; then
|
||||
echo "==> 3. 数据库 schema 同步(构建前,读取 .env.production)"
|
||||
echo "==> 3. 数据库 schema 同步(构建前,读取 $ENV_FILE_NAME)"
|
||||
cd "$APP_ROOT/server/dukang-api"
|
||||
if [[ ! -f .env.production ]]; then
|
||||
echo "错误: 未找到 server/dukang-api/.env.production" >&2
|
||||
if [[ ! -f "$ENV_FILE_NAME" ]]; then
|
||||
echo "错误: 未找到 server/dukang-api/$ENV_FILE_NAME" >&2
|
||||
exit 1
|
||||
fi
|
||||
node scripts/with-api-env.cjs pnpm prisma:generate
|
||||
@@ -94,31 +140,30 @@ else
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "==> 5. 重启 PM2"
|
||||
if pm2 describe dukang-api &>/dev/null; then
|
||||
# delete+start 以确保 cwd 从 h5-user 切到 mini-user
|
||||
pm2 delete dukang-h5-user 2>/dev/null || true
|
||||
pm2 start "$DEPLOY_DIR/ecosystem.config.cjs" --only dukang-h5-user
|
||||
pm2 restart dukang-api dukang-h5-shop dukang-h5-partner dukang-admin-web 2>/dev/null \
|
||||
|| pm2 restart dukang-api dukang-h5-shop dukang-h5-partner
|
||||
echo "==> 5. 重启 PM2 ($ECOSYSTEM_FILE)"
|
||||
if pm2 describe "$PM2_API" &>/dev/null; then
|
||||
pm2 delete "$PM2_USER" 2>/dev/null || true
|
||||
pm2 start "$DEPLOY_DIR/$ECOSYSTEM_FILE" --only "$PM2_USER"
|
||||
pm2 restart "$PM2_API" "$PM2_SHOP" "$PM2_PARTNER" "$PM2_ADMIN" 2>/dev/null \
|
||||
|| pm2 restart "$PM2_API" "$PM2_SHOP" "$PM2_PARTNER"
|
||||
else
|
||||
pm2 start "$DEPLOY_DIR/ecosystem.config.cjs"
|
||||
pm2 start "$DEPLOY_DIR/$ECOSYSTEM_FILE"
|
||||
fi
|
||||
pm2 save
|
||||
|
||||
echo "==> 6. 健康检查"
|
||||
sleep 2
|
||||
pm2 list
|
||||
ss -tlnp | grep -E '809[0-4]' || true
|
||||
curl -sf -o /dev/null -w "mini-user(h5): %{http_code}\n" http://127.0.0.1:8091/ || echo "mini-user(h5): FAIL"
|
||||
curl -sf -o /dev/null -w "api: %{http_code}\n" http://127.0.0.1:8090/api/v1/health 2>/dev/null \
|
||||
|| curl -sf -o /dev/null -w "api: %{http_code}\n" http://127.0.0.1:8090/ \
|
||||
ss -tlnp | grep -E "$PORT_GREP" || true
|
||||
curl -sf -o /dev/null -w "mini-user(h5): %{http_code}\n" "http://127.0.0.1:${USER_PORT}/" || echo "mini-user(h5): FAIL"
|
||||
curl -sf -o /dev/null -w "api: %{http_code}\n" "http://127.0.0.1:${API_PORT}/api/v1/health" 2>/dev/null \
|
||||
|| curl -sf -o /dev/null -w "api: %{http_code}\n" "http://127.0.0.1:${API_PORT}/" \
|
||||
|| echo "api: FAIL"
|
||||
|
||||
echo "==> 7. 记录系统版本"
|
||||
cd "$APP_ROOT/server/dukang-api"
|
||||
APP_ROOT="$APP_ROOT" DEPLOY_TRIGGER="${DEPLOY_TRIGGER:-manual}" \
|
||||
APP_ROOT="$APP_ROOT" DEPLOY_TRIGGER="${DEPLOY_TRIGGER:-manual}" DUKANG_ENV_FILE="$ENV_FILE_NAME" \
|
||||
node scripts/with-api-env.cjs node scripts/record-system-version.cjs \
|
||||
|| echo "WARN: system_version 写入失败"
|
||||
|
||||
echo "==> 发版完成"
|
||||
echo "==> 发版完成 ($DUKANG_DEPLOY_ENV)"
|
||||
|
||||
+32
-10
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# 同步 API 生产环境变量到服务器 .env.production
|
||||
# 用法: deploy/sync-api-env.sh [production]
|
||||
# 同步 API 环境变量到服务器
|
||||
# 用法: deploy/sync-api-env.sh staging|production
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
@@ -12,16 +12,31 @@ DEPLOY_USER="root"
|
||||
DEPLOY_PORT="22"
|
||||
DEPLOY_SSH_KEY=""
|
||||
APP_ROOT="/opt/dukang"
|
||||
STAGING_APP_ROOT="/opt/dukang-staging"
|
||||
PROD_APP_ROOT="/opt/dukang"
|
||||
|
||||
TARGET="${1:-production}"
|
||||
TARGET="${1:-}"
|
||||
case "$TARGET" in
|
||||
production|prod) SRC_ENV="$REPO_ROOT/server/dukang-api/.env.production" ;;
|
||||
staging|stage|test)
|
||||
TARGET=staging
|
||||
SRC_ENV="$REPO_ROOT/server/dukang-api/.env.staging"
|
||||
REMOTE_NAME=".env.staging"
|
||||
PM2_NAME=dukang-stg-api
|
||||
HEALTH_PORT=8190
|
||||
;;
|
||||
production|prod)
|
||||
TARGET=production
|
||||
SRC_ENV="$REPO_ROOT/server/dukang-api/.env.production"
|
||||
REMOTE_NAME=".env.production"
|
||||
PM2_NAME=dukang-api
|
||||
HEALTH_PORT=8090
|
||||
;;
|
||||
development|dev)
|
||||
echo "错误: development 仅用于本地开发,请使用 .env / .env.development,不同步到服务器" >&2
|
||||
echo "错误: development 仅用于本地开发,请使用 .env,不同步到服务器" >&2
|
||||
exit 1
|
||||
;;
|
||||
*)
|
||||
echo "用法: $0 [production]" >&2
|
||||
echo "用法: $0 staging|production" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -31,8 +46,14 @@ if [[ -f "$ENV_FILE" ]]; then
|
||||
source "$ENV_FILE"
|
||||
fi
|
||||
|
||||
if [[ "$TARGET" == "staging" ]]; then
|
||||
APP_ROOT="${STAGING_APP_ROOT:-/opt/dukang-staging}"
|
||||
else
|
||||
APP_ROOT="${PROD_APP_ROOT:-/opt/dukang}"
|
||||
fi
|
||||
|
||||
if [[ ! -f "$SRC_ENV" ]]; then
|
||||
echo "错误: 未找到 $SRC_ENV(可从 .env.production.example 复制)" >&2
|
||||
echo "错误: 未找到 $SRC_ENV(可从 ${SRC_ENV}.example 复制)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -46,7 +67,8 @@ SCP_OPTS=(-o "StrictHostKeyChecking=accept-new" -P "$DEPLOY_PORT")
|
||||
[[ -n "$DEPLOY_SSH_KEY" ]] && SSH_OPTS+=(-i "$DEPLOY_SSH_KEY") && SCP_OPTS+=(-i "$DEPLOY_SSH_KEY")
|
||||
REMOTE="${DEPLOY_USER}@${DEPLOY_HOST}"
|
||||
|
||||
echo "==> 同步 production 环境到 $REMOTE:$APP_ROOT/server/dukang-api/.env.production"
|
||||
scp "${SCP_OPTS[@]}" "$SRC_ENV" "$REMOTE:$APP_ROOT/server/dukang-api/.env.production"
|
||||
ssh "${SSH_OPTS[@]}" "$REMOTE" "pm2 restart dukang-api && sleep 2 && curl -sf -o /dev/null -w 'api-health:%{http_code}\n' http://127.0.0.1:8090/api/v1/health"
|
||||
echo "==> 同步 $TARGET 环境到 $REMOTE:$APP_ROOT/server/dukang-api/$REMOTE_NAME"
|
||||
scp "${SCP_OPTS[@]}" "$SRC_ENV" "$REMOTE:$APP_ROOT/server/dukang-api/$REMOTE_NAME"
|
||||
ssh "${SSH_OPTS[@]}" "$REMOTE" \
|
||||
"pm2 restart $PM2_NAME && sleep 2 && curl -sf -o /dev/null -w 'api-health:%{http_code}\n' http://127.0.0.1:${HEALTH_PORT}/api/v1/health"
|
||||
echo "==> 完成"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { WechatJsapiPrepayParams } from './wechat';
|
||||
|
||||
export interface OrderDto {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
@@ -27,11 +29,41 @@ export interface OrderPreviewResult {
|
||||
deliveryType: 'LOCAL' | 'CROSS_CITY';
|
||||
}
|
||||
|
||||
export type ProxyPayMethod = 'NATIVE' | 'JSAPI';
|
||||
|
||||
export interface PayOrderResult {
|
||||
mode?: 'jsapi' | 'mock';
|
||||
mode?: 'jsapi' | 'mock' | 'native';
|
||||
orderId?: string;
|
||||
codeUrl?: string;
|
||||
prepay?: WechatJsapiPrepayParams;
|
||||
payExpireAt?: string | null;
|
||||
}
|
||||
|
||||
export type ProxyOrderPayRequest = {
|
||||
payMethod: ProxyPayMethod;
|
||||
};
|
||||
|
||||
export type ProxyOrderPayResponse = {
|
||||
mode: 'jsapi' | 'mock' | 'native';
|
||||
orderId: string;
|
||||
orderNo?: string;
|
||||
codeUrl?: string;
|
||||
prepay?: WechatJsapiPrepayParams;
|
||||
payExpireAt?: string | null;
|
||||
};
|
||||
|
||||
export type ProxyOrderCreateResponse = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payStatus: string;
|
||||
payAmount: number;
|
||||
benefitAmount: number;
|
||||
deliveryType: string;
|
||||
payExpireAt: string | null;
|
||||
proxyPartnerName?: string | null;
|
||||
};
|
||||
|
||||
export interface DeliveryDto {
|
||||
provider?: string;
|
||||
shippingAt?: string;
|
||||
@@ -127,7 +159,7 @@ export type PartnerProxyOrderListResponse = {
|
||||
pageSize: number;
|
||||
};
|
||||
|
||||
/** 总部代下单(线下完成发权益,无需短信验证) */
|
||||
/** 总部代下单(在线支付后发权益) */
|
||||
export type HqProxyOrderCreateRequest = {
|
||||
phone: string;
|
||||
deliveryMode: PartnerProxyDeliveryMode;
|
||||
|
||||
Generated
+50
@@ -35,6 +35,12 @@ importers:
|
||||
dayjs:
|
||||
specifier: ^1.11.13
|
||||
version: 1.11.21
|
||||
echarts:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
echarts-for-react:
|
||||
specifier: ^3.0.6
|
||||
version: 3.0.6(echarts@6.1.0)(react@18.3.1)
|
||||
element-china-area-data:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
@@ -78,6 +84,9 @@ importers:
|
||||
element-china-area-data:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
qrcode:
|
||||
specifier: ^1.5.4
|
||||
version: 1.5.4
|
||||
react:
|
||||
specifier: ^18.3.1
|
||||
version: 18.3.1
|
||||
@@ -88,6 +97,9 @@ importers:
|
||||
specifier: ^6.26.0
|
||||
version: 6.30.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
devDependencies:
|
||||
'@types/qrcode':
|
||||
specifier: ^1.5.6
|
||||
version: 1.5.6
|
||||
'@types/react':
|
||||
specifier: ^18.3.3
|
||||
version: 18.3.31
|
||||
@@ -3579,6 +3591,15 @@ packages:
|
||||
ecdsa-sig-formatter@1.0.11:
|
||||
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
|
||||
|
||||
echarts-for-react@3.0.6:
|
||||
resolution: {integrity: sha512-4zqLgTGWS3JvkQDXjzkR1k1CHRdpd6by0988TWMJgnvDytegWLbeP/VNZmMa+0VJx2eD7Y632bi2JquXDgiGJg==}
|
||||
peerDependencies:
|
||||
echarts: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0
|
||||
react: ^15.0.0 || >=16.0.0
|
||||
|
||||
echarts@6.1.0:
|
||||
resolution: {integrity: sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==}
|
||||
|
||||
ee-first@1.1.1:
|
||||
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
|
||||
|
||||
@@ -5835,6 +5856,9 @@ packages:
|
||||
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
size-sensor@1.0.3:
|
||||
resolution: {integrity: sha512-+k9mJ2/rQMiRmQUcjn+qznch260leIXY8r4FyYKKyRBO/s5UoeMAHGkCJyE1R/4wrIhTJONfyloY55SkE7ve3A==}
|
||||
|
||||
slash@3.0.0:
|
||||
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -6189,6 +6213,9 @@ packages:
|
||||
tslib@1.14.1:
|
||||
resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
|
||||
|
||||
tslib@2.3.0:
|
||||
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
@@ -6597,6 +6624,9 @@ packages:
|
||||
yup@1.7.1:
|
||||
resolution: {integrity: sha512-GKHFX2nXul2/4Dtfxhozv701jLQHdf6J34YDh2cEkpqoo8le5Mg6/LrdseVLrFarmFygZTlfIhHx/QKfb/QWXw==}
|
||||
|
||||
zrender@6.1.0:
|
||||
resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@alicloud/credentials@2.4.5':
|
||||
@@ -10333,6 +10363,18 @@ snapshots:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
echarts-for-react@3.0.6(echarts@6.1.0)(react@18.3.1):
|
||||
dependencies:
|
||||
echarts: 6.1.0
|
||||
fast-deep-equal: 3.1.3
|
||||
react: 18.3.1
|
||||
size-sensor: 1.0.3
|
||||
|
||||
echarts@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
zrender: 6.1.0
|
||||
|
||||
ee-first@1.1.1: {}
|
||||
|
||||
electron-to-chromium@1.5.380: {}
|
||||
@@ -12806,6 +12848,8 @@ snapshots:
|
||||
|
||||
signal-exit@4.1.0: {}
|
||||
|
||||
size-sensor@1.0.3: {}
|
||||
|
||||
slash@3.0.0: {}
|
||||
|
||||
slice-ansi@4.0.0:
|
||||
@@ -13170,6 +13214,8 @@ snapshots:
|
||||
|
||||
tslib@1.14.1: {}
|
||||
|
||||
tslib@2.3.0: {}
|
||||
|
||||
tslib@2.8.1: {}
|
||||
|
||||
tunnel-agent@0.6.0:
|
||||
@@ -13665,3 +13711,7 @@ snapshots:
|
||||
tiny-case: 1.0.3
|
||||
toposort: 2.0.2
|
||||
type-fest: 2.19.0
|
||||
|
||||
zrender@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
# 生产环境(真实第三方,关闭 Mock)
|
||||
# 用途:服务器 runtime 配置;bash deploy/sync-api-env.sh production 同步到远端 .env.production
|
||||
# 用途:服务器 /opt/dukang;bash deploy/sync-api-env.sh production
|
||||
# 本地开发请使用 .env(从 .env.example 复制),勿与生产混用
|
||||
# 测试环境请使用 .env.staging(从 .env.staging.example 复制)
|
||||
|
||||
APP_ENV=production
|
||||
NODE_ENV=production
|
||||
|
||||
# 生产:阿里云 RDS(密码中的 @ ! 需 URL 编码为 %40 %21)
|
||||
DATABASE_URL="mysql://dukangadmin:CHANGE_ME@rm-xxxxxxxx.mysql.rds.aliyuncs.com:3306/dukang_prod?charset=utf8mb4"
|
||||
REDIS_URL="redis://localhost:6379"
|
||||
REDIS_URL="redis://localhost:6379/0"
|
||||
JWT_SECRET="CHANGE_ME-strong-random-secret"
|
||||
JWT_EXPIRES_IN="7d"
|
||||
PORT=8090
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Staging / 测试环境(同机双栈,正式微信 AppId + 全 Mock)
|
||||
# 用途:服务器 /opt/dukang-staging;sync: bash deploy/sync-api-env.sh staging
|
||||
# 域名:api-test / user-test / shop-test / partner-test / admin-test.dukanghaoke.com
|
||||
# 本地开发请用 .env,勿与本文件混用
|
||||
|
||||
APP_ENV=staging
|
||||
NODE_ENV=production
|
||||
|
||||
# 独立库(与生产 dukang_prod 隔离;可同 RDS 实例)
|
||||
DATABASE_URL="mysql://dukangadmin:CHANGE_ME@rm-xxxxxxxx.mysql.rds.aliyuncs.com:3306/dukang_staging?charset=utf8mb4"
|
||||
# 建议用 Redis DB 1,与生产 DB 0 隔离
|
||||
REDIS_URL="redis://localhost:6379/1"
|
||||
JWT_SECRET="CHANGE_ME-staging-secret-different-from-prod"
|
||||
JWT_EXPIRES_IN="7d"
|
||||
PORT=8190
|
||||
|
||||
# 全 Mock:不发真实短信、不扣真实微信支付
|
||||
MOCK_SMS=true
|
||||
MOCK_PAY=true
|
||||
MOCK_DELIVERY_AUTO=true
|
||||
MOCK_WECHAT=true
|
||||
AUTO_APPROVE_STORE=true
|
||||
|
||||
ALIYUN_SMS_SIGN_NAME=
|
||||
ALIYUN_SMS_TEMPLATE_CODE=
|
||||
ALIYUN_SMS_TEMPLATE_CONFIRM_REDEEM=
|
||||
ALIYUN_SMS_TEMPLATE_PROXY_ORDER=
|
||||
ALIYUN_SMS_ACCESS_KEY_ID=
|
||||
ALIYUN_SMS_ACCESS_KEY_SECRET=
|
||||
|
||||
TRUST_PROXY=true
|
||||
|
||||
# C 端 H5(测试域)
|
||||
USER_H5_URL=https://user-test.dukanghaoke.com/user
|
||||
|
||||
# 正式号配置可与生产相同,但 Mock 打开后不走真实支付
|
||||
WX_APP_ID=
|
||||
WX_APP_SECRET=
|
||||
WX_MINI_APP_ID=
|
||||
WX_MINI_APP_SECRET=
|
||||
WX_MINI_PROMO_PAGE=pages/home/index
|
||||
# WX_MINI_ENV_VERSION=trial
|
||||
WX_MCH_ID=
|
||||
WX_MCH_SERIAL_NO=
|
||||
WX_MCH_PRIVATE_KEY=
|
||||
WX_API_V3_KEY=
|
||||
WX_PLATFORM_CERT=
|
||||
WX_PAY_NOTIFY_URL=https://api-test.dukanghaoke.com/api/v1/callbacks/wechat/pay
|
||||
WX_MINI_MSG_TOKEN=
|
||||
WX_MINI_MSG_AES_KEY=
|
||||
|
||||
WECOM_AIBOT_ENABLED=false
|
||||
|
||||
OSS_ACCESS_KEY_ID=
|
||||
OSS_ACCESS_KEY_SECRET=
|
||||
OSS_BUCKET=dukang-dev
|
||||
OSS_REGION=oss-cn-beijing
|
||||
OSS_CDN_BASE=https://dukang-dev.oss-cn-beijing.aliyuncs.com
|
||||
OSS_UPLOAD_PREFIX=staging/uploads
|
||||
OSS_UPLOAD_EXPIRE_SECONDS=900
|
||||
OSS_MAX_UPLOAD_BYTES=10485760
|
||||
|
||||
COURIER_PROVIDER=xiaofeixia
|
||||
XIAOFEIXIA_API_URL=https://beta.51xiaoju.cn/app/api/interface.do
|
||||
XIAOFEIXIA_MCH_ID=
|
||||
XIAOFEIXIA_API_KEY=
|
||||
XIAOFEIXIA_SIGN_TYPE=MD5
|
||||
@@ -13,6 +13,7 @@
|
||||
"prisma:validate": "prisma validate",
|
||||
"prisma:seed": "ts-node --transpile-only prisma/seed-v31.ts",
|
||||
"prisma:seed-finance": "ts-node --transpile-only prisma/seed-finance-mock.ts",
|
||||
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
||||
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
||||
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
||||
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
/**
|
||||
* 概览页统计 Mock(用户/订单/合伙人/门店/核销,幂等可重复跑)
|
||||
* 用法:cd server/dukang-api && pnpm prisma:seed-stats
|
||||
*/
|
||||
import { PrismaClient, type OrderStatus, type PayStatus } from '@prisma/client';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const USER_PREFIX = 'STAT';
|
||||
const ORDER_PREFIX = 'STAT';
|
||||
const COUPON_PREFIX = 'STATCPN';
|
||||
const REDEEM_PREFIX = 'STATRD';
|
||||
const STORE_NAME_PREFIX = 'STAT门店';
|
||||
const PARTNER_PHONE_PREFIX = '13788';
|
||||
|
||||
const PROMO_CODES = [
|
||||
{ code: 'STAT_A', name: '统计演示·品鉴会A', scene: 'EVENT' as const },
|
||||
{ code: 'STAT_B', name: '统计演示·线下提货B', scene: 'OFFLINE_PICKUP' as const },
|
||||
{ code: 'STAT_C', name: '统计演示·线上渠道C', scene: 'ONLINE_LINK' as const },
|
||||
];
|
||||
|
||||
const CITY_DEFS = [
|
||||
{ code: '410100', name: '郑州市', province: '河南省', district: '金水区' },
|
||||
{ code: '410300', name: '洛阳市', province: '河南省', district: '涧西区' },
|
||||
];
|
||||
|
||||
function startOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function qrcodeIdFor(code: string) {
|
||||
return createHash('sha256').update(`stats-mock:${code}`).digest('hex');
|
||||
}
|
||||
|
||||
function mulberry32(seed: number) {
|
||||
return () => {
|
||||
let t = (seed += 0x6d2b79f5);
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
console.log('Cleaning previous STAT* mock...');
|
||||
|
||||
const redeemIds = (
|
||||
await prisma.redeemRecord.findMany({
|
||||
where: { redeemNo: { startsWith: REDEEM_PREFIX } },
|
||||
select: { id: true },
|
||||
})
|
||||
).map((r) => r.id);
|
||||
if (redeemIds.length) {
|
||||
await prisma.redeemRecordAllocation.deleteMany({
|
||||
where: { redeemRecordId: { in: redeemIds } },
|
||||
});
|
||||
await prisma.storeRating.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await prisma.storePayout.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await prisma.redeemPendingRecord.deleteMany({
|
||||
where: { redeemRecordId: { in: redeemIds } },
|
||||
});
|
||||
await prisma.redeemRecord.deleteMany({ where: { id: { in: redeemIds } } });
|
||||
}
|
||||
|
||||
await prisma.benefitCoupon.deleteMany({
|
||||
where: { couponNo: { startsWith: COUPON_PREFIX } },
|
||||
});
|
||||
|
||||
const statOrders = await prisma.order.findMany({
|
||||
where: { orderNo: { startsWith: ORDER_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const orderIds = statOrders.map((o) => o.id);
|
||||
if (orderIds.length) {
|
||||
await prisma.benefitCoupon.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.orderDelivery.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.userInvoice.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.order.deleteMany({ where: { id: { in: orderIds } } });
|
||||
}
|
||||
|
||||
const statUsers = await prisma.user.findMany({
|
||||
where: { userNo: { startsWith: USER_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const userIds = statUsers.map((u) => u.id);
|
||||
if (userIds.length) {
|
||||
await prisma.userPromoAttribution.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.userCityPreference.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.userAddress.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.benefitCoupon.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.user.deleteMany({ where: { id: { in: userIds } } });
|
||||
}
|
||||
|
||||
await prisma.commonPromoCode.deleteMany({
|
||||
where: { code: { in: PROMO_CODES.map((p) => p.code) } },
|
||||
});
|
||||
|
||||
const statStores = await prisma.store.findMany({
|
||||
where: { name: { startsWith: STORE_NAME_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const storeIds = statStores.map((s) => s.id);
|
||||
if (storeIds.length) {
|
||||
await prisma.storeAccountStore.deleteMany({ where: { storeId: { in: storeIds } } });
|
||||
await prisma.storeBill.deleteMany({ where: { storeId: { in: storeIds } } });
|
||||
await prisma.store.deleteMany({ where: { id: { in: storeIds } } });
|
||||
}
|
||||
|
||||
const statPartners = await prisma.partnerAccount.findMany({
|
||||
where: { phone: { startsWith: PARTNER_PHONE_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const partnerIds = statPartners.map((p) => p.id);
|
||||
if (partnerIds.length) {
|
||||
await prisma.partnerBill.deleteMany({ where: { partnerAccountId: { in: partnerIds } } });
|
||||
await prisma.partnerAccount.deleteMany({
|
||||
where: { OR: [{ id: { in: partnerIds } }, { parentAccountId: { in: partnerIds } }] },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureCities() {
|
||||
const cities = [];
|
||||
for (const def of CITY_DEFS) {
|
||||
const city = await prisma.commonCity.upsert({
|
||||
where: { code: def.code },
|
||||
create: {
|
||||
code: def.code,
|
||||
name: def.name,
|
||||
province: def.province,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
update: {
|
||||
name: def.name,
|
||||
province: def.province,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
});
|
||||
cities.push({ ...city, district: def.district });
|
||||
}
|
||||
return cities;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Seeding stats mock (users/orders/partners/stores/redeems)...');
|
||||
await cleanup();
|
||||
|
||||
const cities = await ensureCities();
|
||||
const product = await prisma.commonProductItem.findFirst({
|
||||
orderBy: { id: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
barcode69: true,
|
||||
name: true,
|
||||
spec: true,
|
||||
price: true,
|
||||
},
|
||||
});
|
||||
if (!product) throw new Error('没有商品,请先 pnpm prisma:seed');
|
||||
|
||||
const category = await prisma.commonStoreCategory.findFirst({ orderBy: { id: 'asc' } });
|
||||
|
||||
const promos = [];
|
||||
for (const def of PROMO_CODES) {
|
||||
const promo = await prisma.commonPromoCode.create({
|
||||
data: {
|
||||
code: def.code,
|
||||
name: def.name,
|
||||
scene: def.scene,
|
||||
qrcodeId: qrcodeIdFor(def.code),
|
||||
status: 'ACTIVE',
|
||||
scanCount: 0,
|
||||
orderCount: 0,
|
||||
},
|
||||
});
|
||||
promos.push(promo);
|
||||
}
|
||||
|
||||
const rand = mulberry32(20260731);
|
||||
const today = startOfDay(new Date());
|
||||
|
||||
// ── 城市合伙人 + 门店(近 30 天分散创建) ──
|
||||
const createdPartners: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
city: (typeof cities)[0];
|
||||
}> = [];
|
||||
const createdStores: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
partnerAccountId: bigint;
|
||||
settlementRate: number;
|
||||
}> = [];
|
||||
|
||||
for (let i = 0; i < cities.length; i++) {
|
||||
const city = cities[i];
|
||||
// 每城 2 个主合伙人
|
||||
for (let j = 0; j < 2; j++) {
|
||||
const dayOffset = Math.floor(rand() * 28);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(9, 0, 0, 0);
|
||||
const phone = `${PARTNER_PHONE_PREFIX}${String(i * 10 + j + 1).padStart(5, '0')}`;
|
||||
const partner = await prisma.partnerAccount.create({
|
||||
data: {
|
||||
phone,
|
||||
name: `${city.name}统计合伙人${j + 1}`,
|
||||
companyName: `STAT${city.name}合伙人${j + 1}`,
|
||||
isPrimary: 1,
|
||||
status: 'ACTIVE',
|
||||
cityId: city.id,
|
||||
scopeType: 'CITY_WIDE',
|
||||
bindingStatus: 'ACTIVE',
|
||||
orderCommissionRate: 0,
|
||||
redeemCommissionRate: 0.03,
|
||||
bankAccountName: `${city.name}统计合伙人${j + 1}`,
|
||||
bankAccountNo: `622202${String(1000000000 + i * 10 + j)}`,
|
||||
bankBranch: `${city.name}工商银行`,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
createdPartners.push({ id: partner.id, cityId: city.id, city });
|
||||
|
||||
// 每位合伙人 3~5 家门店
|
||||
const storeN = 3 + Math.floor(rand() * 3);
|
||||
for (let k = 0; k < storeN; k++) {
|
||||
const sDay = Math.floor(rand() * Math.max(1, dayOffset + 1));
|
||||
const sCreated = new Date(today);
|
||||
sCreated.setDate(sCreated.getDate() - sDay);
|
||||
sCreated.setHours(11, Math.floor(rand() * 40), 0, 0);
|
||||
const rate = 0.6;
|
||||
const store = await prisma.store.create({
|
||||
data: {
|
||||
cityId: city.id,
|
||||
partnerAccountId: partner.id,
|
||||
categoryId: category?.id,
|
||||
name: `${STORE_NAME_PREFIX}-${city.name}-${j + 1}-${k + 1}`,
|
||||
phone: `1399${String(100000 + i * 100 + j * 10 + k).slice(-7)}`,
|
||||
province: city.province,
|
||||
cityName: city.name,
|
||||
district: city.district,
|
||||
address: `统计路${k + 1}号`,
|
||||
settlementRate: rate,
|
||||
status: 'OPEN',
|
||||
auditStatus: 'APPROVED',
|
||||
openTime: '10:00',
|
||||
closeTime: '22:00',
|
||||
createdAt: sCreated,
|
||||
updatedAt: sCreated,
|
||||
},
|
||||
});
|
||||
createdStores.push({
|
||||
id: store.id,
|
||||
cityId: city.id,
|
||||
partnerAccountId: partner.id,
|
||||
settlementRate: rate,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 用户 + 订单 ──
|
||||
const userCount = 100;
|
||||
const createdUsers: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
city: (typeof cities)[0];
|
||||
promoId: bigint | null;
|
||||
phone: string;
|
||||
}> = [];
|
||||
const paidOrders: Array<{
|
||||
id: bigint;
|
||||
userId: bigint;
|
||||
cityId: bigint;
|
||||
payAmount: number;
|
||||
productName: string;
|
||||
}> = [];
|
||||
|
||||
for (let i = 0; i < userCount; i++) {
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(8 + Math.floor(rand() * 12), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const city = cities[Math.floor(rand() * cities.length)];
|
||||
const promo = rand() < 0.7 ? promos[Math.floor(rand() * promos.length)] : null;
|
||||
const seq = String(i + 1).padStart(4, '0');
|
||||
const phone = `13888${String(10000 + i).slice(-5)}`;
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
userNo: `${USER_PREFIX}${seq}`,
|
||||
phone,
|
||||
phoneVerifiedAt: createdAt,
|
||||
nickname: `统计用户${seq}`,
|
||||
deviceKey: `stat-device-${seq}-${randomBytes(4).toString('hex')}`,
|
||||
sourceType: promo ? 'PROMO_CODE' : 'ORGANIC',
|
||||
sourceRefId: promo?.id ?? null,
|
||||
sourceLabel: promo?.name ?? null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
cityPreference: {
|
||||
create: {
|
||||
selectedCityCode: city.code,
|
||||
selectedDistrict: city.district,
|
||||
locateCityCode: city.code,
|
||||
locateDistrict: city.district,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
...(promo
|
||||
? {
|
||||
promoTouch: {
|
||||
create: {
|
||||
promoCodeId: promo.id,
|
||||
channelName: promo.name,
|
||||
firstTouchAt: createdAt,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
createdUsers.push({
|
||||
id: user.id,
|
||||
cityId: city.id,
|
||||
city,
|
||||
promoId: promo?.id ?? null,
|
||||
phone,
|
||||
});
|
||||
}
|
||||
|
||||
const statuses: Array<{ status: OrderStatus; payStatus: PayStatus }> = [
|
||||
{ status: 'COMPLETED', payStatus: 'PAID' },
|
||||
{ status: 'COMPLETED', payStatus: 'PAID' },
|
||||
{ status: 'PENDING_SHIP', payStatus: 'PAID' },
|
||||
{ status: 'SHIPPING', payStatus: 'PAID' },
|
||||
{ status: 'PENDING_PAY', payStatus: 'UNPAID' },
|
||||
{ status: 'CANCELLED', payStatus: 'UNPAID' },
|
||||
];
|
||||
|
||||
let orderCount = 0;
|
||||
const promoOrderInc = new Map<string, number>();
|
||||
|
||||
for (const u of createdUsers) {
|
||||
const n = 1 + Math.floor(rand() * 3);
|
||||
for (let j = 0; j < n; j++) {
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(10 + Math.floor(rand() * 10), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const qty = 2 + Math.floor(rand() * 3);
|
||||
const unit = Number(product.price);
|
||||
const listAmount = unit * qty;
|
||||
const st = statuses[Math.floor(rand() * statuses.length)];
|
||||
const paid = st.payStatus === 'PAID';
|
||||
orderCount += 1;
|
||||
const orderNo = `${ORDER_PREFIX}${String(orderCount).padStart(6, '0')}`;
|
||||
|
||||
const order = await prisma.order.create({
|
||||
data: {
|
||||
orderNo,
|
||||
userId: u.id,
|
||||
cityId: u.cityId,
|
||||
promoCodeId: u.promoId,
|
||||
channelSource: u.promoId ? 'STATS_MOCK' : null,
|
||||
status: st.status,
|
||||
payStatus: st.payStatus,
|
||||
deliveryType: 'LOCAL',
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
productName: product.name,
|
||||
productSpec: product.spec,
|
||||
quantity: qty,
|
||||
listUnitPrice: unit,
|
||||
listAmount,
|
||||
productAmount: listAmount,
|
||||
payAmount: listAmount,
|
||||
benefitAmount: listAmount,
|
||||
receiverName: `统计用户`,
|
||||
receiverPhone: u.phone,
|
||||
receiverAddress: `${u.city.name}${u.city.district}统计路1号`,
|
||||
receiverProvince: u.city.province,
|
||||
receiverCity: u.city.name,
|
||||
receiverDistrict: u.city.district,
|
||||
paidAt: paid ? createdAt : null,
|
||||
completedAt: st.status === 'COMPLETED' ? createdAt : null,
|
||||
cancelledAt: st.status === 'CANCELLED' ? createdAt : null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (paid) {
|
||||
paidOrders.push({
|
||||
id: order.id,
|
||||
userId: u.id,
|
||||
cityId: u.cityId,
|
||||
payAmount: listAmount,
|
||||
productName: product.name,
|
||||
});
|
||||
}
|
||||
|
||||
if (u.promoId) {
|
||||
const key = u.promoId.toString();
|
||||
promoOrderInc.set(key, (promoOrderInc.get(key) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, inc] of promoOrderInc) {
|
||||
await prisma.commonPromoCode.update({
|
||||
where: { id: BigInt(id) },
|
||||
data: { orderCount: { increment: inc }, scanCount: { increment: Math.floor(inc * 1.5) } },
|
||||
});
|
||||
}
|
||||
|
||||
// ── 权益券 + 核销(约 80 笔,分散近 30 天) ──
|
||||
const storesByCity = new Map<string, typeof createdStores>();
|
||||
for (const s of createdStores) {
|
||||
const key = s.cityId.toString();
|
||||
const list = storesByCity.get(key) ?? [];
|
||||
list.push(s);
|
||||
storesByCity.set(key, list);
|
||||
}
|
||||
|
||||
let redeemCount = 0;
|
||||
const redeemTarget = Math.min(80, paidOrders.length);
|
||||
for (let i = 0; i < redeemTarget; i++) {
|
||||
const order = paidOrders[i];
|
||||
const cityStores = storesByCity.get(order.cityId.toString()) ?? createdStores;
|
||||
if (!cityStores.length) continue;
|
||||
const store = cityStores[Math.floor(rand() * cityStores.length)];
|
||||
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(14 + Math.floor(rand() * 6), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const amount = Math.round((40 + rand() * 200) * 100) / 100;
|
||||
const settleAmount = Math.round(amount * store.settlementRate * 100) / 100;
|
||||
|
||||
const coupon = await prisma.benefitCoupon.create({
|
||||
data: {
|
||||
couponNo: `${COUPON_PREFIX}${String(i + 1).padStart(5, '0')}`,
|
||||
userId: order.userId,
|
||||
orderId: order.id,
|
||||
totalAmount: order.payAmount,
|
||||
usedAmount: amount,
|
||||
balance: Math.max(0, order.payAmount - amount),
|
||||
status: amount >= order.payAmount ? 'USED_UP' : 'ACTIVE',
|
||||
sourceProduct: order.productName,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
redeemCount += 1;
|
||||
await prisma.redeemRecord.create({
|
||||
data: {
|
||||
redeemNo: `${REDEEM_PREFIX}${String(redeemCount).padStart(5, '0')}`,
|
||||
userId: order.userId,
|
||||
couponId: coupon.id,
|
||||
storeId: store.id,
|
||||
amount,
|
||||
settleAmount,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Done: cities=${cities.length}, promos=${promos.length}, partners=${createdPartners.length}, ` +
|
||||
`stores=${createdStores.length}, users=${createdUsers.length}, orders=${orderCount}, redeems=${redeemCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const apiRoot = path.join(__dirname, '..');
|
||||
const prod = fs.readFileSync(path.join(apiRoot, '.env.production'), 'utf8');
|
||||
const map = new Map();
|
||||
for (const line of prod.split(/\r?\n/)) {
|
||||
const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
||||
if (m) map.set(m[1], m[2]);
|
||||
}
|
||||
|
||||
function unq(v) {
|
||||
if (!v) return '';
|
||||
if (
|
||||
(v.startsWith('"') && v.endsWith('"')) ||
|
||||
(v.startsWith("'") && v.endsWith("'"))
|
||||
) {
|
||||
return v.slice(1, -1);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function q(v) {
|
||||
return JSON.stringify(String(v ?? ''));
|
||||
}
|
||||
|
||||
const db = unq(map.get('DATABASE_URL') || '');
|
||||
if (!db.includes('dukang_prod')) {
|
||||
console.error('prod DATABASE_URL unexpected, refuse to rewrite');
|
||||
process.exit(1);
|
||||
}
|
||||
const stagingDb = db.replace('/dukang_prod', '/dukang_staging');
|
||||
const jwt = `${unq(map.get('JWT_SECRET') || 'prod')}-staging`;
|
||||
|
||||
const fixed = {
|
||||
APP_ENV: 'staging',
|
||||
NODE_ENV: 'production',
|
||||
DATABASE_URL: stagingDb,
|
||||
REDIS_URL: 'redis://localhost:6379/1',
|
||||
JWT_SECRET: jwt,
|
||||
JWT_EXPIRES_IN: unq(map.get('JWT_EXPIRES_IN') || '7d'),
|
||||
PORT: '8190',
|
||||
MOCK_SMS: 'true',
|
||||
MOCK_PAY: 'true',
|
||||
MOCK_DELIVERY_AUTO: 'true',
|
||||
MOCK_WECHAT: 'true',
|
||||
AUTO_APPROVE_STORE: 'true',
|
||||
TRUST_PROXY: 'true',
|
||||
USER_H5_URL: 'https://user-test.dukanghaoke.com/user',
|
||||
WX_PAY_NOTIFY_URL: 'https://api-test.dukanghaoke.com/api/v1/callbacks/wechat/pay',
|
||||
OSS_UPLOAD_PREFIX: 'staging/uploads',
|
||||
WECOM_AIBOT_ENABLED: 'false',
|
||||
};
|
||||
|
||||
const preferFromProd = [
|
||||
'ALIYUN_SMS_SIGN_NAME',
|
||||
'ALIYUN_SMS_TEMPLATE_CODE',
|
||||
'ALIYUN_SMS_TEMPLATE_CONFIRM_REDEEM',
|
||||
'ALIYUN_SMS_TEMPLATE_PROXY_ORDER',
|
||||
'ALIYUN_SMS_ACCESS_KEY_ID',
|
||||
'ALIYUN_SMS_ACCESS_KEY_SECRET',
|
||||
'WX_APP_ID',
|
||||
'WX_APP_SECRET',
|
||||
'WX_MINI_APP_ID',
|
||||
'WX_MINI_APP_SECRET',
|
||||
'WX_MINI_PROMO_PAGE',
|
||||
'WX_MCH_ID',
|
||||
'WX_MCH_SERIAL_NO',
|
||||
'WX_MCH_PRIVATE_KEY',
|
||||
'WX_API_V3_KEY',
|
||||
'WX_PLATFORM_CERT',
|
||||
'WX_MINI_MSG_TOKEN',
|
||||
'WX_MINI_MSG_AES_KEY',
|
||||
'OSS_ACCESS_KEY_ID',
|
||||
'OSS_ACCESS_KEY_SECRET',
|
||||
'OSS_BUCKET',
|
||||
'OSS_REGION',
|
||||
'OSS_CDN_BASE',
|
||||
'OSS_ENDPOINT',
|
||||
'OSS_UPLOAD_EXPIRE_SECONDS',
|
||||
'OSS_MAX_UPLOAD_BYTES',
|
||||
'COURIER_PROVIDER',
|
||||
'XIAOFEIXIA_API_URL',
|
||||
'XIAOFEIXIA_MCH_ID',
|
||||
'XIAOFEIXIA_API_KEY',
|
||||
'XIAOFEIXIA_SIGN_TYPE',
|
||||
'SHIP_FROM_NAME',
|
||||
'SHIP_FROM_MOBILE',
|
||||
'SHIP_FROM_ADDRESS',
|
||||
'SHIP_FROM_ADDRESS_DETAIL',
|
||||
'SHIP_FROM_LNG',
|
||||
'SHIP_FROM_LAT',
|
||||
'TENCENT_LBS_KEY',
|
||||
'TENCENT_LBS_SECRET_KEY',
|
||||
'DEPLOY_WEBHOOK_URL',
|
||||
'DEPLOY_WEBHOOK_SECRET',
|
||||
];
|
||||
|
||||
const out = [
|
||||
'# Generated from .env.production for staging (full Mock + *-test domains)',
|
||||
'# Do not commit. Sync: bash deploy/sync-api-env.sh staging',
|
||||
'',
|
||||
];
|
||||
|
||||
for (const [k, v] of Object.entries(fixed)) {
|
||||
out.push(`${k}=${q(v)}`);
|
||||
}
|
||||
out.push('');
|
||||
for (const k of preferFromProd) {
|
||||
if (map.has(k) && !(k in fixed)) {
|
||||
out.push(`${k}=${q(unq(map.get(k)))}`);
|
||||
}
|
||||
}
|
||||
|
||||
const skip = new Set([...Object.keys(fixed), ...preferFromProd]);
|
||||
for (const [k, raw] of map.entries()) {
|
||||
if (skip.has(k)) continue;
|
||||
out.push(`${k}=${q(unq(raw))}`);
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(apiRoot, '.env.staging'), `${out.join('\n')}\n`);
|
||||
const host = (stagingDb.match(/@([^/:]+)/) || [])[1] || '?';
|
||||
console.log(`ok db=dukang_staging host=${host} redis=/1 mocks=on`);
|
||||
@@ -0,0 +1,27 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const apiRoot = path.join(__dirname, '..');
|
||||
const prod = fs.readFileSync(path.join(apiRoot, '.env.production'), 'utf8');
|
||||
const m = prod.match(/^DATABASE_URL=(.*)$/m);
|
||||
if (!m) throw new Error('no prod DATABASE_URL');
|
||||
let url = m[1].trim();
|
||||
if (
|
||||
(url.startsWith('"') && url.endsWith('"')) ||
|
||||
(url.startsWith("'") && url.endsWith("'"))
|
||||
) {
|
||||
url = url.slice(1, -1);
|
||||
}
|
||||
if (!url.includes('/dukang_prod')) throw new Error('unexpected prod url');
|
||||
const stg = url.replace('/dukang_prod', '/dukang_staging');
|
||||
|
||||
const envPath = path.join(apiRoot, '.env.staging');
|
||||
let t = fs.readFileSync(envPath, 'utf8');
|
||||
if (!/^DATABASE_URL=/m.test(t)) {
|
||||
t = `DATABASE_URL=\n${t}`;
|
||||
}
|
||||
t = t.replace(/^DATABASE_URL=.*$/m, `DATABASE_URL=${JSON.stringify(stg)}`);
|
||||
fs.writeFileSync(envPath, t);
|
||||
|
||||
const u = new URL(stg);
|
||||
console.log(`ok ${u.hostname}:${u.port || 3306}${u.pathname}`);
|
||||
@@ -4,7 +4,8 @@ const { existsSync } = require('fs');
|
||||
const { resolve } = require('path');
|
||||
|
||||
const apiRoot = resolve(__dirname, '..');
|
||||
const envFile = process.env.DUKANG_ENV_FILE ?? '.env.production';
|
||||
const envFile = process.env.DUKANG_ENV_FILE
|
||||
?? (process.env.APP_ENV === 'staging' ? '.env.staging' : '.env.production');
|
||||
const envPath = resolve(apiRoot, envFile);
|
||||
|
||||
if (!existsSync(envPath)) {
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import type { WechatJsapiPrepayParams } from '@dukang/shared-types';
|
||||
|
||||
export type PayMethod = 'JSAPI' | 'NATIVE';
|
||||
|
||||
export type PayOrderResult =
|
||||
| { mode: 'mock'; externalNo: string }
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams };
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams }
|
||||
| { mode: 'native'; codeUrl: string; externalNo: string };
|
||||
|
||||
export interface IPayProvider {
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult>;
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult>;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayMockProvider implements IPayProvider {
|
||||
async payOrder(_orderId: bigint, _openId?: string, _platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
_openId?: string,
|
||||
_platform?: 'h5' | 'mini',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (!loadAppConfig().mockPay) {
|
||||
throw new Error('Real WeChat pay requires PayWechatProvider');
|
||||
}
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
import { PayMockProvider } from './pay.mock.provider';
|
||||
import { PayWechatProvider } from './pay.wechat.provider';
|
||||
|
||||
/** 按当前 process.env 动态选择 Mock / 微信 JSAPI 支付 */
|
||||
/** 按当前 process.env 动态选择 Mock / 微信支付 */
|
||||
@Injectable()
|
||||
export class PayRouterProvider implements IPayProvider {
|
||||
constructor(
|
||||
@@ -16,7 +16,12 @@ export class PayRouterProvider implements IPayProvider {
|
||||
return loadAppConfig().mockPay ? this.mock : this.wechat;
|
||||
}
|
||||
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform);
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform, payMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { loadAppConfig } from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { WECHAT_PROVIDER } from '../integrations.constants';
|
||||
import type { IWechatProvider } from '../wechat/wechat.interface';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayWechatProvider implements IPayProvider {
|
||||
@@ -14,28 +14,60 @@ export class PayWechatProvider implements IPayProvider {
|
||||
@Inject(WECHAT_PROVIDER) private readonly wechat: IWechatProvider,
|
||||
) {}
|
||||
|
||||
async payOrder(orderId: bigint, openId?: string, platform: 'h5' | 'mini' = 'h5'): Promise<PayOrderResult> {
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform: 'h5' | 'mini' = 'h5',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (loadAppConfig().mockPay) {
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
if (!this.wechat.isPayEnabled()) {
|
||||
throw new Error('微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID 等商户参数');
|
||||
}
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new Error('订单不存在');
|
||||
|
||||
const amountFen = Math.round(Number(order.payAmount) * 100);
|
||||
const notifyUrl = process.env.WX_PAY_NOTIFY_URL ?? '';
|
||||
|
||||
if (payMethod === 'NATIVE') {
|
||||
this.logger.log(`create NATIVE prepay order=${order.orderNo} mchid=${this.wechat.getMchId()}`);
|
||||
const { codeUrl } = await this.wechat.createNativePrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
notifyUrl,
|
||||
});
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl,
|
||||
externalNo: `NATIVE-${order.orderNo}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
this.logger.log(`create JSAPI prepay order=${order.orderNo} mchid=${this.wechat.getMchId()} platform=${platform}`);
|
||||
const prepay = await this.wechat.createJsapiPrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
openId,
|
||||
notifyUrl: process.env.WX_PAY_NOTIFY_URL ?? '',
|
||||
notifyUrl,
|
||||
platform,
|
||||
});
|
||||
return { mode: 'jsapi', prepay };
|
||||
|
||||
@@ -553,6 +553,55 @@ export class WechatApiProvider implements IWechatProvider {
|
||||
};
|
||||
}
|
||||
|
||||
async createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
if (!this.isPayEnabled()) {
|
||||
throw new InternalServerErrorException(
|
||||
'微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID、WX_MCH_SERIAL_NO、WX_MCH_PRIVATE_KEY、WX_API_V3_KEY',
|
||||
);
|
||||
}
|
||||
const notifyUrl = params.notifyUrl || this.notifyUrl;
|
||||
if (!notifyUrl) {
|
||||
throw new InternalServerErrorException('请配置 WX_PAY_NOTIFY_URL');
|
||||
}
|
||||
const payAppId = this.appId || this.miniAppId;
|
||||
if (!payAppId) {
|
||||
throw new InternalServerErrorException('微信支付未配置:请设置 WX_APP_ID');
|
||||
}
|
||||
const body = {
|
||||
appid: payAppId,
|
||||
mchid: this.mchId,
|
||||
description: params.description,
|
||||
out_trade_no: params.orderNo,
|
||||
notify_url: notifyUrl,
|
||||
amount: { total: params.amountFen, currency: 'CNY' },
|
||||
};
|
||||
const path = '/v3/pay/transactions/native';
|
||||
const payload = JSON.stringify(body);
|
||||
const auth = this.signPayRequest('POST', path, payload);
|
||||
const res = await this.fetchPayJson<{ code_url?: string }>(
|
||||
`https://api.mch.weixin.qq.com${path}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: auth,
|
||||
},
|
||||
body: payload,
|
||||
},
|
||||
);
|
||||
if (!res.code_url) {
|
||||
throw new InternalServerErrorException('微信 Native 下单失败');
|
||||
}
|
||||
this.logger.log(`NATIVE prepay ok mchid=${this.mchId} orderNo=${params.orderNo}`);
|
||||
return { codeUrl: res.code_url };
|
||||
}
|
||||
|
||||
async parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -51,6 +51,10 @@ export class WechatDisabledProvider implements IWechatProvider {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
createNativePrepay() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
parsePayNotification() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
@@ -132,6 +132,14 @@ export interface IWechatProvider {
|
||||
platform?: 'h5' | 'mini';
|
||||
}): Promise<WechatJsapiPrepayParams>;
|
||||
|
||||
/** 创建 Native 扫码支付 code_url */
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}): Promise<{ codeUrl: string }>;
|
||||
|
||||
/** 解析并验签支付回调通知 */
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
|
||||
@@ -80,6 +80,10 @@ export class WechatMockProvider implements IWechatProvider {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
createNativePrepay(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
parsePayNotification(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
@@ -80,6 +80,15 @@ export class WechatRouterProvider implements IWechatProvider {
|
||||
return this.resolve().createJsapiPrepay(params);
|
||||
}
|
||||
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
return this.resolve().createNativePrepay(params);
|
||||
}
|
||||
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -5,19 +5,33 @@ import { resolve } from 'path';
|
||||
/**
|
||||
* 环境变量加载策略(后加载的文件覆盖先前的同名键):
|
||||
*
|
||||
* - 本地开发:仅 `.env` + `.env.local`
|
||||
* `.env.development` 仅作参考模板,不自动加载
|
||||
* - local:`.env` + `.env.local`
|
||||
* - staging:`.env.staging` + `.env.staging.local`(同机测试栈,APP_ENV=staging)
|
||||
* - production:`.env.production` + `.env.production.local`
|
||||
*
|
||||
* - 服务器(NODE_ENV=production):仅 `.env.production` + `.env.production.local`
|
||||
* 不使用 `.env`,避免与本地开发配置混淆
|
||||
* 判定:优先 `APP_ENV`;未设置时 `NODE_ENV=production` → production,否则 local。
|
||||
* staging 在 PM2 中仍设 `NODE_ENV=production`(构建产物),靠 `APP_ENV=staging` 区分。
|
||||
*/
|
||||
const apiRoot = resolve(__dirname, '..');
|
||||
const nodeEnv = process.env.NODE_ENV ?? 'development';
|
||||
const isProduction = nodeEnv === 'production';
|
||||
|
||||
const layers = isProduction
|
||||
? [resolve(apiRoot, '.env.production'), resolve(apiRoot, '.env.production.local')]
|
||||
: [resolve(apiRoot, '.env'), resolve(apiRoot, '.env.local')];
|
||||
function resolveAppEnv(): 'local' | 'staging' | 'production' {
|
||||
const raw = (process.env.APP_ENV ?? '').trim().toLowerCase();
|
||||
if (raw === 'staging' || raw === 'stage' || raw === 'test') return 'staging';
|
||||
if (raw === 'production' || raw === 'prod') return 'production';
|
||||
if (raw === 'local' || raw === 'development' || raw === 'dev') return 'local';
|
||||
if (nodeEnv === 'production') return 'production';
|
||||
return 'local';
|
||||
}
|
||||
|
||||
const appEnv = resolveAppEnv();
|
||||
|
||||
const layers =
|
||||
appEnv === 'staging'
|
||||
? [resolve(apiRoot, '.env.staging'), resolve(apiRoot, '.env.staging.local')]
|
||||
: appEnv === 'production'
|
||||
? [resolve(apiRoot, '.env.production'), resolve(apiRoot, '.env.production.local')]
|
||||
: [resolve(apiRoot, '.env'), resolve(apiRoot, '.env.local')];
|
||||
|
||||
for (const file of layers) {
|
||||
if (existsSync(file)) {
|
||||
@@ -28,3 +42,6 @@ for (const file of layers) {
|
||||
if (!process.env.NODE_ENV) {
|
||||
process.env.NODE_ENV = nodeEnv;
|
||||
}
|
||||
if (!process.env.APP_ENV) {
|
||||
process.env.APP_ENV = appEnv;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import { SuperAdminGuard } from '../../common/guards/super-admin.guard';
|
||||
import { AdminDashboardService } from './admin-dashboard.service';
|
||||
import { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
@Controller('admin/dashboard')
|
||||
@UseGuards(HqAuthGuard)
|
||||
@@ -13,6 +14,11 @@ export class AdminDashboardController {
|
||||
return this.dashboardService.getStats();
|
||||
}
|
||||
|
||||
@Get('analytics')
|
||||
analytics(@Query() query: AdminDashboardAnalyticsQueryDto) {
|
||||
return this.dashboardService.getAnalytics(query);
|
||||
}
|
||||
|
||||
@Get('version')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
version() {
|
||||
|
||||
@@ -1,5 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
function startOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function endOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
function parseYmd(s: string): Date | null {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
|
||||
const d = new Date(`${s}T00:00:00`);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function formatYmd(d: Date): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function eachDate(from: Date, to: Date): string[] {
|
||||
const out: string[] = [];
|
||||
const cur = startOfDay(from);
|
||||
const end = startOfDay(to);
|
||||
while (cur <= end) {
|
||||
out.push(formatYmd(cur));
|
||||
cur.setDate(cur.getDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function num(v: Prisma.Decimal | number | string | null | undefined): number {
|
||||
if (v == null) return 0;
|
||||
return typeof v === 'number' ? v : Number(v);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminDashboardService {
|
||||
@@ -59,7 +98,6 @@ export class AdminDashboardService {
|
||||
redeemToday,
|
||||
deliveriesTotal,
|
||||
pendingPayouts,
|
||||
/** 合伙人已确认、待总部审核打款 */
|
||||
pendingBills,
|
||||
pendingPartnerDraftBills,
|
||||
openTickets,
|
||||
@@ -85,4 +123,426 @@ export class AdminDashboardService {
|
||||
deployedAt: row.deployedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
async getAnalytics(query: AdminDashboardAnalyticsQueryDto) {
|
||||
const today = startOfDay(new Date());
|
||||
const defaultFrom = new Date(today);
|
||||
defaultFrom.setDate(defaultFrom.getDate() - 29);
|
||||
|
||||
const from =
|
||||
(query.dateFrom ? parseYmd(query.dateFrom) : null) ?? defaultFrom;
|
||||
const to =
|
||||
(query.dateTo ? parseYmd(query.dateTo) : null) ?? today;
|
||||
const rangeStart = startOfDay(from <= to ? from : to);
|
||||
const rangeEnd = endOfDay(from <= to ? to : from);
|
||||
|
||||
let filterCityCode: string | null | undefined;
|
||||
let filterCityId: bigint | null | undefined;
|
||||
if (query.cityId === 'none') {
|
||||
filterCityCode = null;
|
||||
filterCityId = null;
|
||||
} else if (query.cityId) {
|
||||
const city = await this.prisma.commonCity.findUnique({
|
||||
where: { id: BigInt(query.cityId) },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
if (city) {
|
||||
filterCityCode = city.code;
|
||||
filterCityId = city.id;
|
||||
}
|
||||
}
|
||||
|
||||
const filterPromoNone = query.promoCodeId === 'none';
|
||||
const filterPromoId =
|
||||
query.promoCodeId && query.promoCodeId !== 'none'
|
||||
? BigInt(query.promoCodeId)
|
||||
: undefined;
|
||||
const filterPartnerId = query.partnerAccountId
|
||||
? BigInt(query.partnerAccountId)
|
||||
: undefined;
|
||||
|
||||
const userWhere: Prisma.UserWhereInput = {
|
||||
status: 1,
|
||||
mergedIntoUserId: null,
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityCode === null) {
|
||||
userWhere.OR = [
|
||||
{ cityPreference: null },
|
||||
{ cityPreference: { selectedCityCode: null } },
|
||||
];
|
||||
} else if (filterCityCode) {
|
||||
userWhere.cityPreference = { selectedCityCode: filterCityCode };
|
||||
}
|
||||
if (filterPromoNone) {
|
||||
userWhere.promoTouch = { is: null };
|
||||
} else if (filterPromoId !== undefined) {
|
||||
userWhere.promoTouch = { promoCodeId: filterPromoId };
|
||||
}
|
||||
|
||||
const orderWhere: Prisma.OrderWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId !== undefined && filterCityId !== null) {
|
||||
orderWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPromoNone) {
|
||||
orderWhere.promoCodeId = null;
|
||||
} else if (filterPromoId !== undefined) {
|
||||
orderWhere.promoCodeId = filterPromoId;
|
||||
}
|
||||
|
||||
const partnerWhere: Prisma.PartnerAccountWhereInput = {
|
||||
isPrimary: 1,
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
partnerWhere.cityId = null;
|
||||
} else if (filterCityId !== undefined) {
|
||||
partnerWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) {
|
||||
partnerWhere.id = filterPartnerId;
|
||||
}
|
||||
|
||||
const storeWhere: Prisma.StoreWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
// 门店必有 cityId
|
||||
storeWhere.id = { in: [] };
|
||||
} else if (filterCityId !== undefined) {
|
||||
storeWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) {
|
||||
storeWhere.partnerAccountId = filterPartnerId;
|
||||
}
|
||||
|
||||
const redeemWhere: Prisma.RedeemRecordWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
redeemWhere.id = { in: [] };
|
||||
} else {
|
||||
const storeFilter: Prisma.StoreWhereInput = {};
|
||||
if (filterCityId !== undefined) storeFilter.cityId = filterCityId;
|
||||
if (filterPartnerId !== undefined) storeFilter.partnerAccountId = filterPartnerId;
|
||||
if (Object.keys(storeFilter).length) {
|
||||
redeemWhere.store = storeFilter;
|
||||
}
|
||||
}
|
||||
|
||||
const skipOrders = filterCityId === null;
|
||||
|
||||
const [users, orders, partners, stores, redeems, cities, promos, partnerNames] =
|
||||
await Promise.all([
|
||||
this.prisma.user.findMany({
|
||||
where: userWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityPreference: { select: { selectedCityCode: true } },
|
||||
promoTouch: { select: { promoCodeId: true } },
|
||||
},
|
||||
}),
|
||||
skipOrders
|
||||
? Promise.resolve([])
|
||||
: this.prisma.order.findMany({
|
||||
where: orderWhere,
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
promoCodeId: true,
|
||||
payStatus: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.partnerAccount.findMany({
|
||||
where: partnerWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
companyName: true,
|
||||
name: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.store.findMany({
|
||||
where: storeWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
partnerAccountId: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.redeemRecord.findMany({
|
||||
where: redeemWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
amount: true,
|
||||
settleAmount: true,
|
||||
store: { select: { cityId: true, partnerAccountId: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.commonCity.findMany({
|
||||
select: { id: true, code: true, name: true },
|
||||
}),
|
||||
this.prisma.commonPromoCode.findMany({
|
||||
select: { id: true, code: true, name: true },
|
||||
}),
|
||||
this.prisma.partnerAccount.findMany({
|
||||
where: { isPrimary: 1 },
|
||||
select: { id: true, companyName: true, name: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const cityByCode = new Map(cities.map((c) => [c.code, c]));
|
||||
const cityById = new Map(cities.map((c) => [c.id.toString(), c]));
|
||||
const promoById = new Map(promos.map((p) => [p.id.toString(), p]));
|
||||
const partnerLabel = new Map(
|
||||
partnerNames.map((p) => [
|
||||
p.id.toString(),
|
||||
p.companyName || p.name || `合伙人#${p.id}`,
|
||||
]),
|
||||
);
|
||||
|
||||
const dateKeys = eachDate(rangeStart, rangeEnd);
|
||||
type DateBucket = {
|
||||
date: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byDateMap = new Map<string, DateBucket>(
|
||||
dateKeys.map((d) => [
|
||||
d,
|
||||
{ date: d, users: 0, orders: 0, partners: 0, stores: 0, redeems: 0, redeemAmount: 0 },
|
||||
]),
|
||||
);
|
||||
|
||||
type CityBucket = {
|
||||
cityId: string;
|
||||
cityName: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byCityMap = new Map<string, CityBucket>();
|
||||
|
||||
type PromoBucket = {
|
||||
promoCodeId: string | null;
|
||||
code: string;
|
||||
name: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
};
|
||||
const byPromoMap = new Map<string, PromoBucket>();
|
||||
|
||||
type PartnerBucket = {
|
||||
partnerAccountId: string;
|
||||
companyName: string;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byPartnerMap = new Map<string, PartnerBucket>();
|
||||
|
||||
const ensureCity = (key: string, cityId: string, cityName: string) => {
|
||||
let b = byCityMap.get(key);
|
||||
if (!b) {
|
||||
b = {
|
||||
cityId,
|
||||
cityName,
|
||||
users: 0,
|
||||
orders: 0,
|
||||
partners: 0,
|
||||
stores: 0,
|
||||
redeems: 0,
|
||||
redeemAmount: 0,
|
||||
};
|
||||
byCityMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
const ensurePromo = (
|
||||
key: string,
|
||||
promoCodeId: string | null,
|
||||
code: string,
|
||||
name: string,
|
||||
) => {
|
||||
let b = byPromoMap.get(key);
|
||||
if (!b) {
|
||||
b = { promoCodeId, code, name, users: 0, orders: 0 };
|
||||
byPromoMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
const ensurePartner = (key: string, companyName: string) => {
|
||||
let b = byPartnerMap.get(key);
|
||||
if (!b) {
|
||||
b = {
|
||||
partnerAccountId: key,
|
||||
companyName,
|
||||
stores: 0,
|
||||
redeems: 0,
|
||||
redeemAmount: 0,
|
||||
};
|
||||
byPartnerMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
for (const u of users) {
|
||||
const d = formatYmd(u.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.users += 1;
|
||||
|
||||
const code = u.cityPreference?.selectedCityCode ?? null;
|
||||
if (code && cityByCode.has(code)) {
|
||||
const city = cityByCode.get(code)!;
|
||||
ensureCity(city.id.toString(), city.id.toString(), city.name).users += 1;
|
||||
} else {
|
||||
ensureCity('none', 'none', '未选城').users += 1;
|
||||
}
|
||||
|
||||
const pid = u.promoTouch?.promoCodeId?.toString() ?? null;
|
||||
if (pid && promoById.has(pid)) {
|
||||
const p = promoById.get(pid)!;
|
||||
ensurePromo(pid, pid, p.code, p.name).users += 1;
|
||||
} else {
|
||||
ensurePromo('none', null, 'ORGANIC', '自然量').users += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const payingUserIds = new Set<string>();
|
||||
for (const o of orders) {
|
||||
const d = formatYmd(o.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.orders += 1;
|
||||
|
||||
const cid = o.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).orders += 1;
|
||||
|
||||
const pid = o.promoCodeId?.toString() ?? null;
|
||||
if (pid && promoById.has(pid)) {
|
||||
const p = promoById.get(pid)!;
|
||||
ensurePromo(pid, pid, p.code, p.name).orders += 1;
|
||||
} else {
|
||||
ensurePromo('none', null, 'NONE', '无推广码').orders += 1;
|
||||
}
|
||||
|
||||
if (o.payStatus === 'PAID') {
|
||||
payingUserIds.add(o.userId.toString());
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of partners) {
|
||||
const d = formatYmd(p.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.partners += 1;
|
||||
|
||||
if (p.cityId) {
|
||||
const cid = p.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).partners += 1;
|
||||
} else {
|
||||
ensureCity('none', 'none', '未绑定城市').partners += 1;
|
||||
}
|
||||
|
||||
const key = p.id.toString();
|
||||
ensurePartner(key, p.companyName || p.name || `合伙人#${key}`);
|
||||
}
|
||||
|
||||
for (const s of stores) {
|
||||
const d = formatYmd(s.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.stores += 1;
|
||||
|
||||
const cid = s.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).stores += 1;
|
||||
|
||||
const pid = s.partnerAccountId.toString();
|
||||
ensurePartner(pid, partnerLabel.get(pid) || `合伙人#${pid}`).stores += 1;
|
||||
}
|
||||
|
||||
let redeemAmountTotal = 0;
|
||||
for (const r of redeems) {
|
||||
const amount = num(r.amount);
|
||||
redeemAmountTotal += amount;
|
||||
|
||||
const d = formatYmd(r.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) {
|
||||
day.redeems += 1;
|
||||
day.redeemAmount += amount;
|
||||
}
|
||||
|
||||
const cid = r.store.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
const cityBucket = ensureCity(cid, cid, city?.name ?? `城市#${cid}`);
|
||||
cityBucket.redeems += 1;
|
||||
cityBucket.redeemAmount += amount;
|
||||
|
||||
const pid = r.store.partnerAccountId.toString();
|
||||
const partnerBucket = ensurePartner(
|
||||
pid,
|
||||
partnerLabel.get(pid) || `合伙人#${pid}`,
|
||||
);
|
||||
partnerBucket.redeems += 1;
|
||||
partnerBucket.redeemAmount += amount;
|
||||
}
|
||||
|
||||
const byCity = [...byCityMap.values()].sort(
|
||||
(a, b) =>
|
||||
b.users + b.orders + b.partners + b.stores + b.redeems -
|
||||
(a.users + a.orders + a.partners + a.stores + a.redeems),
|
||||
);
|
||||
const byPromo = [...byPromoMap.values()].sort(
|
||||
(a, b) => b.users + b.orders - (a.users + a.orders),
|
||||
);
|
||||
const byPartner = [...byPartnerMap.values()].sort(
|
||||
(a, b) => b.stores + b.redeems - (a.stores + a.redeems),
|
||||
);
|
||||
|
||||
return {
|
||||
summary: {
|
||||
users: users.length,
|
||||
orders: orders.length,
|
||||
payingUsers: payingUserIds.size,
|
||||
partners: partners.length,
|
||||
stores: stores.length,
|
||||
redeems: redeems.length,
|
||||
redeemAmount: Math.round(redeemAmountTotal * 100) / 100,
|
||||
},
|
||||
byDate: dateKeys.map((d) => {
|
||||
const row = byDateMap.get(d)!;
|
||||
return {
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
};
|
||||
}),
|
||||
byCity: byCity.map((row) => ({
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
})),
|
||||
byPromo,
|
||||
byPartner: byPartner.map((row) => ({
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
@@ -10,7 +10,11 @@ import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||
import { TradeService } from '../trade/trade.service';
|
||||
import { HqProxyOrderCreateDto, HqProxyOrderPreviewDto } from './dto/hq-proxy-order.dto';
|
||||
import {
|
||||
HqProxyOrderCreateDto,
|
||||
HqProxyOrderPayDto,
|
||||
HqProxyOrderPreviewDto,
|
||||
} from './dto/hq-proxy-order.dto';
|
||||
|
||||
@Controller('admin/proxy-orders')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@@ -42,4 +46,19 @@ export class AdminProxyOrdersController {
|
||||
) {
|
||||
return this.tradeService.createHqProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(@Param('id') id: string, @Body() dto: HqProxyOrderPayDto) {
|
||||
return this.tradeService.payHqProxyOrder(BigInt(id), dto.payMethod ?? 'NATIVE');
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), { hq: true });
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
payStatus(@Param('id') id: string) {
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,33 @@ export class AdminOrdersQueryDto extends PaginationQueryDto {
|
||||
createdTo?: string;
|
||||
}
|
||||
|
||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
||||
export class AdminDashboardAnalyticsQueryDto {
|
||||
/** YYYY-MM-DD,默认近 30 天 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateFrom?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateTo?: string;
|
||||
|
||||
/** 开城城市 id;`none` = 用户未选城 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cityId?: string;
|
||||
|
||||
/** 推广码 id;`none` = 无归因 / 订单无推广码 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
|
||||
/** 城市合伙人(主账号)id */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
partnerAccountId?: string;
|
||||
}
|
||||
|
||||
export class AdminStoresQueryDto extends PaginationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -85,3 +85,9 @@ export class HqProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class HqProxyOrderPayDto {
|
||||
@IsOptional()
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod?: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -93,3 +93,8 @@ export class PartnerProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class PartnerProxyOrderPayDto {
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { PartnerPermissionGuard } from '../../common/guards/partner-permission.g
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import {
|
||||
PartnerProxyOrderCreateDto,
|
||||
PartnerProxyOrderPayDto,
|
||||
PartnerProxyOrderPreviewDto,
|
||||
} from './dto/partner-proxy-order.dto';
|
||||
import { ManualShipOrderDto } from '../ops/dto/admin-mutate.dto';
|
||||
@@ -223,11 +224,6 @@ export class PartnerProxyOrderController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Post('preview')
|
||||
preview(@CurrentUser() user: AuthUser, @Body() dto: PartnerProxyOrderPreviewDto) {
|
||||
return this.tradeService.previewPartnerProxyOrderForPartner(user.actorId, dto);
|
||||
@@ -241,4 +237,36 @@ export class PartnerProxyOrderController {
|
||||
) {
|
||||
return this.tradeService.createPartnerProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: PartnerProxyOrderPayDto,
|
||||
) {
|
||||
return this.tradeService.payPartnerProxyOrder(user.actorId, BigInt(id), dto.payMethod);
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), {
|
||||
partnerAccountId: user.actorId,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
async payStatus(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
await this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id/track')
|
||||
track(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrderTrack(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1257,7 +1257,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1271,10 +1271,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1299,9 +1299,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? primary.id,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: primary.id,
|
||||
@@ -1312,23 +1310,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'PARTNER_PROXY',
|
||||
remark: `合伙人线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
remark: `合伙人代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1342,8 +1330,6 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
this.analyticsService.trackPartnerOneSafe(partnerAccountId, 'PARTNER_H5', {
|
||||
partnerAccountId: primary.id,
|
||||
eventName: 'partner_proxy_order_create',
|
||||
@@ -1359,7 +1345,17 @@ export class TradeService {
|
||||
},
|
||||
});
|
||||
|
||||
return serializeBigInt(mapOrderCompat(order));
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: primary.name,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单列表:按 proxyPartnerAccountId 归属,与管仓订单无关 */
|
||||
@@ -1547,7 +1543,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1561,10 +1557,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1589,9 +1585,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? null,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: null,
|
||||
@@ -1602,23 +1596,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'HQ_PROXY',
|
||||
remark: `总部线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
remark: `总部代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1632,15 +1616,245 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
return serializeBigInt({
|
||||
id: order.id,
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: proxyDisplayName,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单支付:NATIVE 商家码 / JSAPI 合伙人微信代付 */
|
||||
async payPartnerProxyOrder(
|
||||
partnerAccountId: bigint,
|
||||
orderId: bigint,
|
||||
payMethod: 'NATIVE' | 'JSAPI',
|
||||
) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
let openId: string | undefined;
|
||||
if (payMethod === 'JSAPI') {
|
||||
openId = primary.wxOpenId ?? undefined;
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay && !openId) {
|
||||
throw new BadRequestException('请先在微信内登录并绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, openId, 'h5', payMethod);
|
||||
|
||||
if (payResult.mode === 'native') {
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (payResult.mode === 'jsapi') {
|
||||
return {
|
||||
mode: 'jsapi' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
prepay: payResult.prepay,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(order.id, payResult.externalNo, 'PARTNER_PROXY_MOCK_PAY');
|
||||
return {
|
||||
mode: 'mock' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 总部代下单支付:仅 Native 收款码 */
|
||||
async payHqProxyOrder(orderId: bigint, payMethod: 'NATIVE' | 'JSAPI' = 'NATIVE') {
|
||||
if (payMethod !== 'NATIVE') {
|
||||
throw new BadRequestException('总部代下单仅支持收款码支付');
|
||||
}
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, undefined, 'h5', 'NATIVE');
|
||||
if (payResult.mode !== 'native') {
|
||||
throw new BadRequestException('无法生成收款码');
|
||||
}
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mock 环境确认代下单支付 */
|
||||
async mockConfirmProxyPay(
|
||||
orderId: bigint,
|
||||
opts: { partnerAccountId?: bigint; hq?: boolean },
|
||||
) {
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay) {
|
||||
throw new BadRequestException('仅 MOCK_PAY 环境可用');
|
||||
}
|
||||
|
||||
let order;
|
||||
if (opts.partnerAccountId != null) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(opts.partnerAccountId);
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
}
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.payStatus === 'PAID') {
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
if (order.status !== 'PENDING_PAY') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(
|
||||
order.id,
|
||||
`MOCK-CONFIRM-${Date.now()}`,
|
||||
opts.hq ? 'HQ_PROXY_MOCK_PAY' : 'PARTNER_PROXY_MOCK_PAY',
|
||||
);
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
|
||||
async getProxyPayStatus(orderId: bigint) {
|
||||
const order = await this.prisma.order.findUnique({
|
||||
where: { id: orderId },
|
||||
select: {
|
||||
id: true,
|
||||
orderNo: true,
|
||||
status: true,
|
||||
payStatus: true,
|
||||
payAmount: true,
|
||||
deliveryType: true,
|
||||
payExpireAt: true,
|
||||
paidAt: true,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
paidAt: order.paidAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async getPartnerProxyOrderTrack(partnerAccountId: bigint, orderId: bigint) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
select: { id: true, deliveryType: true },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
return this.fulfillmentService.getOrderTrack(orderId);
|
||||
}
|
||||
|
||||
private async markProxyOrderPaid(orderId: bigint, externalNo: string, operator: string) {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
if (order.payStatus === 'PAID') return;
|
||||
|
||||
const now = new Date();
|
||||
const paySnapshot = await this.partnerCityService.resolveForOrder(
|
||||
order.cityId,
|
||||
order.receiverDistrict,
|
||||
);
|
||||
const toStatus =
|
||||
order.deliveryType === 'ON_SITE_PICKUP' ? 'PENDING_RECEIVE' : 'PENDING_SHIP';
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.order.update({
|
||||
where: { id: order.id },
|
||||
data: {
|
||||
status: toStatus,
|
||||
payStatus: 'PAID',
|
||||
paidAt: now,
|
||||
payExternalNo: externalNo,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? order.partnerAccountIdAtPay,
|
||||
orderCommissionRateAtPay:
|
||||
paySnapshot?.orderCommissionRate ?? order.orderCommissionRateAtPay,
|
||||
},
|
||||
});
|
||||
await tx.logThirdParty.create({
|
||||
data: {
|
||||
provider: 'WECHAT_PAY',
|
||||
scene: 'ORDER_PAY',
|
||||
refType: 'ORDER',
|
||||
refId: order.id,
|
||||
externalNo,
|
||||
amount: order.payAmount,
|
||||
status: 'SUCCESS',
|
||||
},
|
||||
});
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: order.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus,
|
||||
operator,
|
||||
}),
|
||||
});
|
||||
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
||||
if (!delivery) {
|
||||
await tx.orderDelivery.create({
|
||||
data: { orderId: order.id, provider: 'MANUAL' },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await this.afterOrderPaid(order.id);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -97,7 +97,7 @@
|
||||
| SC-04 | 门店核销 | 出码/报手机号→核销→权益扣减→门店账本×60% |
|
||||
| SC-05 | 拓店入驻 | 合伙人录入→负责人复核→总部审核→试核销100元→营业 |
|
||||
| SC-06 | 售后工单 | 用户四类型→总部审→仓/合伙人协同→补发/退款 |
|
||||
| SC-07 | 代下单 | 总部/合伙人手机号建用户下单(Wave 3);合伙人侧:双短信确认、线下完成发权益、订单记代下单人;总部本期对齐后续 |
|
||||
| SC-07 | 代下单 | 总部/合伙人手机号建用户下单;在线支付(商家收款码 / 合伙人微信代付)后发权益;配送进入待发货由总部履约,现场提货走自提闭环;订单记代下单人 |
|
||||
| SC-08 | 问卷+评价 | 成交后问卷;核销后门店评价 |
|
||||
| SC-09 | 推广归因 | 推广码进小程序→绑定合伙人→统计成交/佣金 |
|
||||
|
||||
@@ -403,7 +403,7 @@
|
||||
|
||||
| OPT | 波次 | 说明 |
|
||||
|-----|------|------|
|
||||
| OPT-002 代下单 | W3 | 合伙人主账号:客户验码→选品/履约(配送须勾选自动收货或现场提货选门店)→合伙人确认码;线下已收款直接完成发权益;新用户 sourceType=PARTNER_PROXY;总部代下单后续对齐 |
|
||||
| OPT-002 代下单 | W3 | 合伙人主账号:选品/履约(配送须勾选自动收货或现场提货)→创建待支付订单→收款码或微信代付(合伙人 openId)→支付成功发权益;配送单 PENDING_SHIP 由总部发货,合伙人可看物流;现场提货支付后自提闭环;新用户 sourceType=PARTNER_PROXY;总部代下单同为在线收款码支付 |
|
||||
| OPT-006 弱网 | W3 | W1~2 重试+人工补核销 |
|
||||
| OPT-010 未出账提现 | W2 | 含 FIN-001~003 |
|
||||
| OPT-005 现场提货 | W2 | — |
|
||||
@@ -432,6 +432,7 @@
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
|------|------|------|
|
||||
| v3.0.2 | 2026-08-02 | OPT-002/SC-07:代下单改为在线支付(收款码/合伙人微信代付);去掉线下已收款直完成;配送单总部履约、合伙人可看物流 |
|
||||
| v3.0.1 | 2026-07-27 | ACC-012/OPT-002/SC-07:明确合伙人代下单双短信、线下完成、来源 PARTNER_PROXY、C 端展示代下单人 |
|
||||
| v3.0 | 2026-07-11 | 由产品 PRD v1.3 整理为工程 V3.0 事实源;配套 `@dukang-v3` skill 与 `v3-delivery-lead` agent |
|
||||
|
||||
|
||||
Reference in New Issue
Block a user