fix(wxlogin): 修复微信登录 40029 + 新增商家(企业账号)全流程

微信登录修复:
- 根因:manifest.json 的 mp-weixin.appid 为空 → 开发者工具用测试号,code 与服务端 appid 不匹配
- 修复:填入 wx40ca4b02d4d1cb58
- WxLogin 增加错误码语义映射(40029 appid 不一致 / 40125 secret 错 / 45011 频繁 / 40226 风控)
- 登录页新增手机号登录兜底通道(微信不可用时业务不被卡住)

商家(企业账号):
- 新表 fa_merchant / fa_merchant_order / fa_invoice(纯新增,DB 40→45 表)
- Merchant 控制器:apply/info/update/bills/invoices/invoice/bindBatch
  入驻含企业信息+营业执照+开票信息+结算方式(预付/月结)
  账单按月汇总、开票额度按已付-已开票校验、批量下单按批次归属
- Auth::switchRole 支持 merchant(2001/2002/2003 语义码 + redirect)
- Auth::profile 增加 is_merchant / merchant

前端:
- 登录页角色扩为 业主/师傅/商家 三类
- pages/merchant/apply 企业入驻;workbench 商家工作台(经营数据+按月账单+近期订单+六宫格)
- pages/merchant/batch 批量下单(多地址×多数量)→ 逐单建单支付 → 绑定批次
- pages/merchant/invoice 开票申请与记录
- pages/mine 增加商家入驻/切换商家端入口;角色徽章三态

验证:163 项断言全通过(page_flow 47 + e2e 65 + phase2 27 + phase3 24)
这个提交包含在:
linda
2026-10-28 16:22:20 +08:00
父节点 6ff685afc9
当前提交 4e73c8164a
共有 15 个文件被更改,包括 1264 次插入 和 22 次删除

70
db/schema_phase3.sql 普通文件
查看文件

@@ -0,0 +1,70 @@
-- ============================================================================
-- 优匠优服 · Phase 3 商家(企业账号)
-- 纯新增表,不改动既有表结构与数据
-- ============================================================================
SET NAMES utf8mb4;
-- 商家入驻档案
CREATE TABLE IF NOT EXISTS `fa_merchant` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '关联 fa_user.id',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '企业/商户名称',
`license_no` varchar(50) NOT NULL DEFAULT '' COMMENT '统一社会信用代码',
`license_image` varchar(255) NOT NULL DEFAULT '' COMMENT '营业执照图',
`legal_person` varchar(50) NOT NULL DEFAULT '' COMMENT '法人代表',
`contact` varchar(50) NOT NULL DEFAULT '' COMMENT '联系人',
`mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '联系电话',
`province` varchar(50) NOT NULL DEFAULT '',
`city` varchar(50) NOT NULL DEFAULT '',
`district` varchar(50) NOT NULL DEFAULT '',
`address` varchar(255) NOT NULL DEFAULT '' COMMENT '经营地址',
`invoice_title` varchar(100) NOT NULL DEFAULT '' COMMENT '发票抬头',
`invoice_tax_no` varchar(50) NOT NULL DEFAULT '' COMMENT '纳税人识别号',
`invoice_bank` varchar(100) NOT NULL DEFAULT '' COMMENT '开户行',
`invoice_account` varchar(50) NOT NULL DEFAULT '' COMMENT '银行账号',
`settle_type` enum('prepay','monthly') NOT NULL DEFAULT 'prepay' COMMENT '预付/月结',
`verify_status` enum('pending','pass','reject') NOT NULL DEFAULT 'pending',
`audit_msg` varchar(255) NOT NULL DEFAULT '',
`order_count` int(11) NOT NULL DEFAULT '0',
`total_amount` decimal(12,2) NOT NULL DEFAULT '0.00',
`createtime` bigint(16) DEFAULT NULL,
`updatetime` bigint(16) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
KEY `verify_status` (`verify_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商家档案';
-- 商家订单归属(批次对账用,不侵入 fa_order)
CREATE TABLE IF NOT EXISTS `fa_merchant_order` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`merchant_id` int(10) unsigned NOT NULL DEFAULT '0',
`order_id` int(10) unsigned NOT NULL DEFAULT '0',
`batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '批次号(批量下单)',
`createtime` bigint(16) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `order_id` (`order_id`),
KEY `merchant_id` (`merchant_id`),
KEY `batch_no` (`batch_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商家订单归属';
-- 开票申请
CREATE TABLE IF NOT EXISTS `fa_invoice` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`merchant_id` int(10) unsigned NOT NULL DEFAULT '0',
`user_id` int(10) unsigned NOT NULL DEFAULT '0',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00',
`type` enum('normal','special') NOT NULL DEFAULT 'normal' COMMENT '普票/专票',
`title` varchar(100) NOT NULL DEFAULT '',
`tax_no` varchar(50) NOT NULL DEFAULT '',
`email` varchar(100) NOT NULL DEFAULT '',
`remark` varchar(255) NOT NULL DEFAULT '',
`status` enum('wait','issued','reject') NOT NULL DEFAULT 'wait',
`invoice_no` varchar(50) NOT NULL DEFAULT '',
`createtime` bigint(16) DEFAULT NULL,
`updatetime` bigint(16) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `merchant_id` (`merchant_id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开票申请';
-- 回滚:DROP TABLE IF EXISTS `fa_invoice`,`fa_merchant_order`,`fa_merchant`;

查看文件

@@ -50,7 +50,7 @@
"quickapp" : {}, "quickapp" : {},
/* 小程序特有相关 */ /* 小程序特有相关 */
"mp-weixin" : { "mp-weixin" : {
"appid" : "", "appid" : "wx40ca4b02d4d1cb58",
"setting" : { "setting" : {
"urlCheck" : false "urlCheck" : false
}, },

查看文件

@@ -66,6 +66,22 @@
"path": "pages/mine/mine", "path": "pages/mine/mine",
"style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" } "style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" }
}, },
{
"path": "pages/merchant/apply",
"style": { "navigationBarTitleText": "商家入驻" }
},
{
"path": "pages/merchant/workbench",
"style": { "navigationBarTitleText": "商家工作台" }
},
{
"path": "pages/merchant/batch",
"style": { "navigationBarTitleText": "批量下单" }
},
{
"path": "pages/merchant/invoice",
"style": { "navigationBarTitleText": "开具发票" }
},
{ {
"path": "pages/master/orders", "path": "pages/master/orders",
"style": { "style": {

查看文件

@@ -10,13 +10,9 @@
<view class="card"> <view class="card">
<view class="role"> <view class="role">
<view class="role-item" :class="{ on: role === 'user' }" @tap="role = 'user'"> <view class="role-item" v-for="r in roles" :key="r.key" :class="{ on: role === r.key }" @tap="role = r.key">
<text class="role-name">我是业主</text> <text class="role-name">{{ r.name }}</text>
<text class="role-desc">下单找师傅</text> <text class="role-desc">{{ r.desc }}</text>
</view>
<view class="role-item" :class="{ on: role === 'master' }" @tap="role = 'master'">
<text class="role-name">我是师傅</text>
<text class="role-desc">接单赚收入</text>
</view> </view>
</view> </view>
@@ -25,6 +21,17 @@
<text class="wx-txt">{{ loading ? '微信授权中...' : '微信一键登录' }}</text> <text class="wx-txt">{{ loading ? '微信授权中...' : '微信一键登录' }}</text>
</view> </view>
<view class="fallback">
<view class="fb-toggle" @tap="showPhone = !showPhone">
<text class="fb-toggle-t">{{ showPhone ? '收起手机号登录' : '微信授权失败?改用手机号登录' }}</text>
</view>
<view class="fb-body" v-if="showPhone">
<input class="fb-input" v-model="mobile" type="number" maxlength="11" placeholder="请输入手机号" />
<input class="fb-input" v-model="code" type="number" maxlength="6" placeholder="验证码(联调固定 123456)" />
<view class="fb-btn" @tap="phoneLogin">手机号登录 / 注册</view>
</view>
</view>
<view class="tip">授权仅用于账号识别,不会获取你的其他信息</view> <view class="tip">授权仅用于账号识别,不会获取你的其他信息</view>
<view class="agree">登录即代表同意《用户服务协议》与《隐私政策》</view> <view class="agree">登录即代表同意《用户服务协议》与《隐私政策》</view>
</view> </view>
@@ -41,6 +48,15 @@
const role = ref('user'); const role = ref('user');
const loading = ref(false); const loading = ref(false);
const showBack = ref(false); const showBack = ref(false);
const showPhone = ref(false);
const mobile = ref('');
const code = ref('');
const roles = [
{ key: 'user', name: '我是业主', desc: '下单找师傅' },
{ key: 'master', name: '我是师傅', desc: '接单赚收入' },
{ key: 'merchant', name: '我是商家', desc: '企业批量下单' }
];
function toast(t) { uni.showToast({ title: t, icon: 'none' }); } function toast(t) { uni.showToast({ title: t, icon: 'none' }); }
@@ -83,11 +99,39 @@
}); });
} }
function phoneLogin() {
if (loading.value) return;
if (!/^1\d{10}$/.test(mobile.value)) { toast('请输入正确的手机号'); return; }
if (!code.value) { toast('请输入验证码'); return; }
loading.value = true;
api.login({ mobile: mobile.value, code: code.value }).then((data) => {
loading.value = false;
setToken(data.token);
setUser(data.userinfo);
setRole(role.value);
toast('登录成功');
setTimeout(() => routeAfterLogin(), 500);
}).catch((e) => {
loading.value = false;
toast(e.message || '登录失败');
});
}
function routeAfterLogin() { function routeAfterLogin() {
if (role.value === 'user') { if (role.value === 'user') {
uni.reLaunch({ url: '/YJYF/YJYF' }); uni.reLaunch({ url: '/YJYF/YJYF' });
return; return;
} }
if (role.value === 'merchant') {
api.merchantInfo().then((res) => {
if (!res.applied || res.merchant.verify_status !== 'pass') {
uni.redirectTo({ url: '/pages/merchant/apply' });
} else {
uni.redirectTo({ url: '/pages/merchant/workbench' });
}
}).catch(() => uni.redirectTo({ url: '/pages/merchant/apply' }));
return;
}
api.masterInfo().then((res) => { api.masterInfo().then((res) => {
if (!res.applied || res.master.verify_status !== 'pass') { if (!res.applied || res.master.verify_status !== 'pass') {
uni.redirectTo({ url: '/pages/master/apply' }); uni.redirectTo({ url: '/pages/master/apply' });
@@ -112,12 +156,19 @@
.brand { position: relative; display: block; font-size: 52rpx; font-weight: 700; color: #fff; letter-spacing: 6rpx; text-shadow: 0 3rpx 12rpx rgba(180,80,10,.3); } .brand { position: relative; display: block; font-size: 52rpx; font-weight: 700; color: #fff; letter-spacing: 6rpx; text-shadow: 0 3rpx 12rpx rgba(180,80,10,.3); }
.slogan { position: relative; display: block; margin-top: 14rpx; font-size: 26rpx; color: rgba(255,255,255,.88); letter-spacing: 2rpx; } .slogan { position: relative; display: block; margin-top: 14rpx; font-size: 26rpx; color: rgba(255,255,255,.88); letter-spacing: 2rpx; }
.card { position: relative; margin: -140rpx 40rpx 0; padding: 40rpx 34rpx 34rpx; background: #fff; border-radius: 24rpx; box-shadow: 0 16rpx 40rpx rgba(226,120,26,.16); } .card { position: relative; margin: -140rpx 40rpx 0; padding: 40rpx 34rpx 34rpx; background: #fff; border-radius: 24rpx; box-shadow: 0 16rpx 40rpx rgba(226,120,26,.16); }
.role { display: flex; margin-bottom: 36rpx; } .role { display: flex; margin-bottom: 34rpx; }
.role-item { flex: 1; padding: 22rpx 0; border-radius: 16rpx; background: #F7F7F7; display: flex; flex-direction: column; align-items: center; border: 2rpx solid transparent; } .role-item { flex: 1; margin-right: 12rpx; padding: 18rpx 0; border-radius: 16rpx; background: #F7F7F7; display: flex; flex-direction: column; align-items: center; border: 2rpx solid transparent; }
.role-item:last-child { margin-right: 0; }
.role-item.on { background: linear-gradient(135deg, #FFF8EE 0%, #FFE9D2 100%); border-color: #F9A65B; } .role-item.on { background: linear-gradient(135deg, #FFF8EE 0%, #FFE9D2 100%); border-color: #F9A65B; }
.role-name { font-size: 30rpx; font-weight: 600; color: #333; } .role-name { font-size: 26rpx; font-weight: 600; color: #333; }
.role-item.on .role-name { color: #C4580A; } .role-item.on .role-name { color: #C4580A; }
.role-desc { margin-top: 6rpx; font-size: 22rpx; color: #9A9A9A; } .role-desc { margin-top: 4rpx; font-size: 19rpx; color: #9A9A9A; }
.fallback { margin-top: 20rpx; }
.fb-toggle { text-align: center; padding: 12rpx 0; }
.fb-toggle-t { font-size: 22rpx; color: #9A9A9A; text-decoration: underline; }
.fb-body { margin-top: 10rpx; }
.fb-input { height: 88rpx; margin-bottom: 14rpx; padding: 0 24rpx; background: #F7F7F7; border-radius: 14rpx; font-size: 28rpx; color: #222; }
.fb-btn { height: 84rpx; display: flex; align-items: center; justify-content: center; border-radius: 42rpx; background: #FFF3E6; color: #E36B0C; font-size: 28rpx; font-weight: 600; }
.wx-btn { height: 96rpx; display: flex; align-items: center; justify-content: center; border-radius: 48rpx; background: linear-gradient(135deg, #4BC86A 0%, #2FA84F 100%); box-shadow: 0 10rpx 24rpx rgba(47,168,79,.28); } .wx-btn { height: 96rpx; display: flex; align-items: center; justify-content: center; border-radius: 48rpx; background: linear-gradient(135deg, #4BC86A 0%, #2FA84F 100%); box-shadow: 0 10rpx 24rpx rgba(47,168,79,.28); }
.wx-btn.disabled { opacity: .7; } .wx-btn.disabled { opacity: .7; }
.wx-icon { width: 44rpx; height: 44rpx; border-radius: 50%; background: #fff; display: flex; align-items: center; justify-content: center; margin-right: 14rpx; } .wx-icon { width: 44rpx; height: 44rpx; border-radius: 50%; background: #fff; display: flex; align-items: center; justify-content: center; margin-right: 14rpx; }

139
pages/merchant/apply.vue 普通文件
查看文件

@@ -0,0 +1,139 @@
<template>
<view class="page">
<view class="hero">
<text class="hero-t">商家入驻</text>
<text class="hero-s">企业账号可批量下单、按月对账、开具发票</text>
</view>
<view class="status" v-if="info">
<text class="st-t">当前状态:{{ statusText }}</text>
<text class="st-m" v-if="info.merchant.audit_msg">审核意见:{{ info.merchant.audit_msg }}</text>
</view>
<view class="card" v-if="canEdit">
<view class="block-title">企业信息</view>
<view class="fi"><text class="fk">企业名称</text><input class="fv" v-model="form.name" placeholder="与营业执照一致" /></view>
<view class="fi"><text class="fk">信用代码</text><input class="fv" v-model="form.license_no" maxlength="18" placeholder="统一社会信用代码" /></view>
<view class="fi"><text class="fk">法人代表</text><input class="fv" v-model="form.legal_person" placeholder="法人姓名" /></view>
<view class="block-title">联系方式</view>
<view class="fi"><text class="fk">联系人</text><input class="fv" v-model="form.contact" placeholder="对接人姓名" /></view>
<view class="fi"><text class="fk">联系电话</text><input class="fv" v-model="form.mobile" type="number" maxlength="11" placeholder="手机号" /></view>
<view class="fi"><text class="fk">经营地址</text><input class="fv" v-model="form.address" placeholder="门店 / 办公地址" /></view>
<view class="block-title">开票与结算</view>
<view class="fi"><text class="fk">发票抬头</text><input class="fv" v-model="form.invoice_title" placeholder="不填默认同企业名称" /></view>
<view class="fi"><text class="fk">税号</text><input class="fv" v-model="form.invoice_tax_no" placeholder="纳税人识别号" /></view>
<view class="fi"><text class="fk">结算方式</text>
<view class="seg">
<view class="seg-i" :class="{ on: form.settle_type === 'prepay' }" @tap="form.settle_type = 'prepay'">预付</view>
<view class="seg-i" :class="{ on: form.settle_type === 'monthly' }" @tap="form.settle_type = 'monthly'">月结</view>
</view>
</view>
<view class="hint">营业执照照片上传将在正式版接入 chooseMedia(当前以文本占位)</view>
<view class="submit" :class="{ disabled: submitting }" @tap="submit">{{ submitting ? '提交中...' : '提交审核' }}</view>
</view>
<view class="card" v-else>
<view class="li"><text class="k">企业名称</text><text class="v">{{ info.merchant.name }}</text></view>
<view class="li"><text class="k">信用代码</text><text class="v">{{ info.merchant.license_no }}</text></view>
<view class="li"><text class="k">联系人</text><text class="v">{{ info.merchant.contact }} {{ info.merchant.mobile }}</text></view>
<view class="li"><text class="k">经营地址</text><text class="v">{{ info.merchant.address }}</text></view>
<view class="li"><text class="k">累计订单</text><text class="v">{{ info.merchant.order_count }} 单</text></view>
<view class="li"><text class="k">累计金额</text><text class="v">¥{{ info.merchant.total_amount }}</text></view>
<view class="go" @tap="goWorkbench">进入商家工作台 ›</view>
</view>
</view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
import { isLogin, toLogin, getUser } from '@/utils/request.js';
const info = ref(null);
const submitting = ref(false);
const form = reactive({
name: '', license_no: '', legal_person: '', contact: '', mobile: '',
province: '贵州省', city: '遵义市', district: '', address: '',
invoice_title: '', invoice_tax_no: '', settle_type: 'prepay'
});
const statusText = computed(() => {
if (!info.value || !info.value.merchant) return '未入驻';
const s = info.value.merchant.verify_status;
return { pending: '待审核', pass: '已通过', reject: '未通过' }[s] || s;
});
const canEdit = computed(() => !info.value || !info.value.applied || info.value.merchant.verify_status === 'reject');
function goWorkbench() { uni.redirectTo({ url: '/pages/merchant/workbench' }); }
async function load() {
if (!isLogin()) { toLogin(); return; }
const res = await api.merchantInfo();
info.value = res.applied ? res : null;
if (res.applied) {
const m = res.merchant;
form.name = m.name;
form.license_no = m.license_no;
form.legal_person = m.legal_person;
form.contact = m.contact;
form.mobile = m.mobile;
form.address = m.address;
form.invoice_title = m.invoice_title;
form.invoice_tax_no = m.invoice_tax_no;
form.settle_type = m.settle_type;
} else {
const u = getUser();
if (u) form.mobile = u.mobile || '';
}
}
async function submit() {
if (submitting.value) return;
if (!form.name || !form.license_no || !form.contact || !form.mobile) {
uni.showToast({ title: '请填写企业名称/信用代码/联系人/电话', icon: 'none' });
return;
}
submitting.value = true;
try {
await api.merchantApply(form);
uni.showToast({ title: '已提交,等待审核' });
load();
} catch (e) {
} finally {
submitting.value = false;
}
}
onShow(() => load());
</script>
<style scoped>
.page { min-height: 100vh; background: #F5F6F8; padding-bottom: 60rpx; }
.hero { padding: 40rpx 36rpx; background: linear-gradient(160deg,#FFB85C 0%,#F98D25 60%,#ED6F0E 100%); }
.hero-t { display: block; font-size: 40rpx; font-weight: 700; color: #fff; }
.hero-s { display: block; margin-top: 10rpx; font-size: 24rpx; color: rgba(255,255,255,.9); }
.status { margin: 22rpx 28rpx 0; padding: 20rpx 24rpx; background: #FFF7F0; border-radius: 16rpx; display: flex; flex-direction: column; }
.st-t { font-size: 26rpx; color: #C4580A; font-weight: 600; }
.st-m { margin-top: 6rpx; font-size: 22rpx; color: #9A9A9A; }
.card { margin: 22rpx 28rpx 0; padding: 22rpx 24rpx; background: #fff; border-radius: 20rpx; box-shadow: 0 6rpx 20rpx rgba(240,129,31,.06); }
.block-title { margin: 18rpx 0 4rpx; font-size: 26rpx; font-weight: 700; color: #1F1F1F; }
.block-title:first-child { margin-top: 0; }
.fi { display: flex; align-items: center; min-height: 88rpx; border-bottom: 1rpx solid #F4F4F4; }
.fk { width: 160rpx; font-size: 26rpx; color: #666; }
.fv { flex: 1; height: 88rpx; font-size: 28rpx; color: #222; }
.seg { display: flex; }
.seg-i { padding: 0 28rpx; line-height: 56rpx; margin-right: 12rpx; border-radius: 28rpx; background: #F5F5F5; font-size: 24rpx; color: #666; }
.seg-i.on { background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); color: #fff; }
.hint { margin-top: 16rpx; font-size: 20rpx; color: #BDBDBD; line-height: 30rpx; }
.submit { height: 92rpx; margin-top: 24rpx; display: flex; align-items: center; justify-content: center; border-radius: 46rpx; color: #fff; font-size: 30rpx; font-weight: 600; background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); }
.submit.disabled { opacity: .7; }
.li { display: flex; justify-content: space-between; padding: 14rpx 0; border-bottom: 1rpx solid #F4F4F4; }
.k { flex-shrink: 0; width: 150rpx; font-size: 26rpx; color: #666; }
.v { flex: 1; text-align: right; font-size: 26rpx; color: #333; }
.go { margin-top: 24rpx; height: 84rpx; display: flex; align-items: center; justify-content: center; border-radius: 42rpx; background: #FFF3E6; color: #E36B0C; font-size: 28rpx; font-weight: 600; }
</style>

189
pages/merchant/batch.vue 普通文件
查看文件

@@ -0,0 +1,189 @@
<template>
<view class="page">
<view class="card">
<view class="card-title">选择服务</view>
<view class="fi">
<text class="fk">服务类目</text>
<picker :range="catNames" @change="onCat">
<view class="picker">{{ catNames[catIdx] || '请选择' }} ›</view>
</picker>
</view>
<view class="fi">
<text class="fk">服务项目</text>
<picker :range="svcNames" @change="onSvc">
<view class="picker">{{ svcNames[svcIdx] || '请选择' }} ›</view>
</picker>
</view>
<view class="hint" v-if="svc">单价 {{ svc.price_text }} · {{ svc.price_type_text }}</view>
</view>
<view class="card">
<view class="card-head">
<text class="card-title">服务地址({{ rows.length }} 个)</text>
<text class="card-more" @tap="addRow">+ 添加</text>
</view>
<view class="row" v-for="(r, i) in rows" :key="i">
<view class="row-head">
<text class="row-no">#{{ i + 1 }}</text>
<text class="row-del" @tap="delRow(i)">删除</text>
</view>
<input class="input" v-model="r.contact" placeholder="联系人" />
<input class="input" v-model="r.mobile" type="number" maxlength="11" placeholder="联系电话" />
<input class="input" v-model="r.address" placeholder="详细地址(小区/楼栋/门牌)" />
<view class="row-foot">
<view class="mini">
<text class="mini-k">楼层</text>
<view class="st"><view class="st-btn" @tap="step(r, 'floor', -1)">-</view><text class="st-v">{{ r.floor }}</text><view class="st-btn" @tap="step(r, 'floor', 1)">+</view></view>
</view>
<view class="mini">
<text class="mini-k">数量</text>
<view class="st"><view class="st-btn" @tap="step(r, 'num', -1)">-</view><text class="st-v">{{ r.num }}</text><view class="st-btn" @tap="step(r, 'num', 1)">+</view></view>
</view>
<view class="mini">
<text class="mini-k">电梯</text>
<view class="seg">
<view class="seg-i" :class="{ on: r.elevator === 1 }" @tap="r.elevator = 1">有</view>
<view class="seg-i" :class="{ on: r.elevator === 0 }" @tap="r.elevator = 0">无</view>
</view>
</view>
</view>
</view>
</view>
<view class="bar">
<view class="bar-l"><text class="bar-k">共 {{ rows.length }} 单</text><text class="bar-p">¥{{ estimate }}</text></view>
<view class="bar-btn" :class="{ disabled: submitting }" @tap="submit">{{ submitting ? '提交中...' : '批量提交并支付' }}</view>
</view>
</view>
</template>
<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
const cats = ref([]);
const catIdx = ref(0);
const svcs = ref([]);
const svcIdx = ref(0);
const submitting = ref(false);
const rows = ref([]);
const catNames = computed(() => cats.value.map(c => c.name));
const svcNames = computed(() => svcs.value.map(s => s.name + ' ' + s.price_text));
const svc = computed(() => svcs.value[svcIdx.value] || null);
const estimate = computed(() => {
if (!svc.value) return '0.00';
const base = Number(svc.value.base_price) || 0;
return rows.value.reduce((sum, r) => sum + base * r.num, 0).toFixed(2);
});
function newRow() {
return { contact: '', mobile: '', address: '', floor: 1, elevator: 1, num: 1 };
}
function addRow() { rows.value.push(newRow()); }
function delRow(i) { if (rows.value.length > 1) rows.value.splice(i, 1); }
function step(r, key, d) { r[key] = Math.max(1, r[key] + d); }
async function onCat(e) {
catIdx.value = Number(e.detail.value);
svcIdx.value = 0;
const res = await api.services({ cat_id: cats.value[catIdx.value].id });
svcs.value = res.list || [];
}
function onSvc(e) { svcIdx.value = Number(e.detail.value); }
async function loadCats() {
const res = await api.cats();
cats.value = res.list || [];
if (cats.value.length) {
const r2 = await api.services({ cat_id: cats.value[0].id });
svcs.value = r2.list || [];
}
}
async function submit() {
if (submitting.value) return;
if (!svc.value) { uni.showToast({ title: '请选择服务项目', icon: 'none' }); return; }
const valid = rows.value.filter(r => r.contact && r.mobile && r.address);
if (!valid.length) { uni.showToast({ title: '请至少填写一个完整地址', icon: 'none' }); return; }
submitting.value = true;
const orderIds = [];
let failed = 0;
for (const r of valid) {
try {
const addr = await api.addressSave({
contact: r.contact, mobile: r.mobile,
province: '贵州省', city: '遵义市', district: '', address: r.address,
floor: r.floor, has_elevator: r.elevator, is_default: 0
});
const order = await api.orderCreate({
service_id: svc.value.id, address_id: addr.id,
urgent: 0, goods_num: r.num, remark: '商家批量下单'
});
await api.orderPay({ order_id: order.order_id, pay_type: 'mock' });
orderIds.push(order.order_id);
} catch (e) {
failed++;
}
}
let batchNo = '';
if (orderIds.length) {
try {
const b = await api.merchantBindBatch({ order_ids: orderIds.join(','), batch_no: '' });
batchNo = b.batch_no;
} catch (e) {}
}
submitting.value = false;
uni.showModal({
title: '批量下单完成',
content: '成功 ' + orderIds.length + ' 单' + (failed ? ',失败 ' + failed + ' 单' : '') + (batchNo ? '\n批次号:' + batchNo : ''),
showCancel: false,
success: () => {
if (orderIds.length) uni.redirectTo({ url: '/pages/order/list' });
}
});
}
onLoad(() => {
rows.value = [newRow()];
loadCats();
});
</script>
<style scoped>
.page { min-height: 100vh; background: #F5F6F8; padding: 22rpx 28rpx 180rpx; }
.card { padding: 24rpx; background: #fff; border-radius: 20rpx; margin-bottom: 20rpx; box-shadow: 0 6rpx 20rpx rgba(240,129,31,.06); }
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6rpx; }
.card-title { font-size: 28rpx; font-weight: 700; color: #1F1F1F; }
.card-more { font-size: 24rpx; color: #F0710D; font-weight: 600; }
.fi { display: flex; align-items: center; min-height: 88rpx; border-bottom: 1rpx solid #F4F4F4; }
.fk { width: 170rpx; font-size: 26rpx; color: #666; }
.picker { font-size: 28rpx; color: #222; }
.hint { margin-top: 12rpx; font-size: 22rpx; color: #9A9A9A; }
.row { padding: 18rpx 0; border-bottom: 1rpx dashed #EDEDED; }
.row:last-child { border-bottom: none; }
.row-head { display: flex; justify-content: space-between; margin-bottom: 8rpx; }
.row-no { font-size: 24rpx; font-weight: 700; color: #F0710D; }
.row-del { font-size: 22rpx; color: #9A9A9A; }
.input { height: 80rpx; margin-bottom: 10rpx; padding: 0 20rpx; background: #F7F7F7; border-radius: 12rpx; font-size: 26rpx; color: #222; }
.row-foot { display: flex; align-items: center; justify-content: space-between; }
.mini { display: flex; align-items: center; }
.mini-k { font-size: 22rpx; color: #9A9A9A; margin-right: 8rpx; }
.st { display: flex; align-items: center; }
.st-btn { width: 48rpx; height: 48rpx; line-height: 46rpx; text-align: center; border-radius: 24rpx; background: #F0F0F0; color: #666; font-size: 24rpx; }
.st-v { min-width: 46rpx; text-align: center; font-size: 26rpx; color: #222; }
.seg { display: flex; }
.seg-i { padding: 0 18rpx; line-height: 48rpx; margin-right: 8rpx; border-radius: 24rpx; background: #F0F0F0; font-size: 22rpx; color: #666; }
.seg-i.on { background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); color: #fff; }
.bar { position: fixed; left: 0; right: 0; bottom: 0; height: 120rpx; padding: 0 28rpx; padding-bottom: env(safe-area-inset-bottom); display: flex; align-items: center; justify-content: space-between; background: #fff; box-shadow: 0 -6rpx 24rpx rgba(0,0,0,.07); }
.bar-l { display: flex; align-items: baseline; }
.bar-k { font-size: 24rpx; color: #666; }
.bar-p { margin-left: 8rpx; font-size: 38rpx; font-weight: 700; color: #F0710D; }
.bar-btn { height: 84rpx; padding: 0 44rpx; display: flex; align-items: center; border-radius: 42rpx; color: #fff; font-size: 28rpx; font-weight: 600; background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); box-shadow: 0 8rpx 20rpx rgba(240,113,13,.3); }
.bar-btn.disabled { opacity: .7; }
</style>

117
pages/merchant/invoice.vue 普通文件
查看文件

@@ -0,0 +1,117 @@
<template>
<view class="page">
<view class="card">
<view class="card-head"><text class="card-title">开票信息</text><text class="card-more" @tap="go('/pages/merchant/apply')">修改 ›</text></view>
<view class="li"><text class="k">发票抬头</text><text class="v">{{ title || '未设置' }}</text></view>
<view class="li"><text class="k">税号</text><text class="v">{{ taxNo || '未设置' }}</text></view>
<view class="li"><text class="k">可开票金额</text><text class="v big">¥{{ available }}</text></view>
</view>
<view class="card">
<view class="card-title">申请开票</view>
<view class="fi"><text class="fk">开票金额</text><input class="fv" type="digit" v-model="amount" placeholder="不超过可开票金额" /></view>
<view class="fi"><text class="fk">发票类型</text>
<view class="seg">
<view class="seg-i" :class="{ on: type === 'normal' }" @tap="type = 'normal'">普通发票</view>
<view class="seg-i" :class="{ on: type === 'special' }" @tap="type = 'special'">专用发票</view>
</view>
</view>
<view class="fi"><text class="fk">接收邮箱</text><input class="fv" v-model="email" placeholder="电子发票接收邮箱" /></view>
<view class="btn" :class="{ disabled: submitting }" @tap="submit">{{ submitting ? '提交中...' : '提交开票申请' }}</view>
</view>
<view class="card">
<view class="card-head"><text class="card-title">开票记录</text><text class="card-more">{{ list.length }} 条</text></view>
<view class="iv" v-for="i in list" :key="i.id">
<view class="iv-top">
<text class="iv-type">{{ i.type_text }}</text>
<text class="iv-amt">¥{{ i.amount }}</text>
</view>
<text class="iv-meta">{{ i.title }} · {{ i.time_text }}</text>
<text class="iv-status">{{ i.status_text }}{{ i.invoice_no ? '(' + i.invoice_no + ')' : '' }}</text>
</view>
<view class="empty" v-if="!list.length">暂无开票记录</view>
</view>
</view>
</template>
<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
const title = ref('');
const taxNo = ref('');
const available = ref(0);
const amount = ref('');
const email = ref('');
const type = ref('normal');
const list = ref([]);
const submitting = ref(false);
function go(url) { uni.navigateTo({ url: url }); }
async function load() {
try {
const res = await api.merchantInfo();
if (res.applied) {
title.value = res.merchant.invoice_title || res.merchant.name;
taxNo.value = res.merchant.invoice_tax_no;
available.value = res.merchant.invoiceable;
}
} catch (e) {}
try {
const res = await api.merchantInvoices();
list.value = res.list || [];
} catch (e) {}
}
async function submit() {
if (submitting.value) return;
const amt = Number(amount.value);
if (!amt || amt <= 0) {
uni.showToast({ title: '请填写开票金额', icon: 'none' });
return;
}
submitting.value = true;
try {
await api.merchantInvoice({ amount: amt, type: type.value, email: email.value });
uni.showToast({ title: '已提交开票申请' });
amount.value = '';
load();
} catch (e) {
} finally {
submitting.value = false;
}
}
onShow(() => load());
</script>
<style scoped>
.page { min-height: 100vh; background: #F5F6F8; padding: 22rpx 28rpx 60rpx; }
.card { padding: 24rpx; background: #fff; border-radius: 20rpx; margin-bottom: 20rpx; box-shadow: 0 6rpx 20rpx rgba(240,129,31,.06); }
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8rpx; }
.card-title { font-size: 28rpx; font-weight: 700; color: #1F1F1F; }
.card-more { font-size: 22rpx; color: #9A9A9A; }
.li { display: flex; justify-content: space-between; padding: 14rpx 0; border-bottom: 1rpx solid #F4F4F4; }
.k { flex-shrink: 0; width: 180rpx; font-size: 26rpx; color: #666; }
.v { flex: 1; text-align: right; font-size: 26rpx; color: #333; }
.v.big { font-size: 32rpx; font-weight: 700; color: #F0710D; }
.fi { display: flex; align-items: center; min-height: 88rpx; border-bottom: 1rpx solid #F4F4F4; }
.fk { width: 170rpx; font-size: 26rpx; color: #666; }
.fv { flex: 1; height: 88rpx; font-size: 28rpx; color: #222; }
.seg { display: flex; }
.seg-i { padding: 0 24rpx; line-height: 56rpx; margin-right: 12rpx; border-radius: 28rpx; background: #F5F5F5; font-size: 24rpx; color: #666; }
.seg-i.on { background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); color: #fff; }
.btn { height: 88rpx; margin-top: 20rpx; display: flex; align-items: center; justify-content: center; border-radius: 44rpx; color: #fff; font-size: 30rpx; font-weight: 600; background: linear-gradient(135deg,#FFA93F 0%,#F0710D 100%); }
.btn.disabled { opacity: .7; }
.iv { padding: 16rpx 0; border-bottom: 1rpx solid #F4F4F4; display: flex; flex-direction: column; }
.iv:last-of-type { border-bottom: none; }
.iv-top { display: flex; align-items: baseline; justify-content: space-between; }
.iv-type { font-size: 26rpx; font-weight: 600; color: #333; }
.iv-amt { font-size: 30rpx; font-weight: 700; color: #F0710D; }
.iv-meta { margin-top: 6rpx; font-size: 22rpx; color: #9A9A9A; }
.iv-status { margin-top: 6rpx; font-size: 22rpx; color: #2FA84F; }
.empty { padding: 40rpx 0; text-align: center; font-size: 24rpx; color: #9A9A9A; }
</style>

145
pages/merchant/workbench.vue 普通文件
查看文件

@@ -0,0 +1,145 @@
<template>
<view class="page">
<view class="header">
<view class="deco"></view>
<view class="h-top">
<view class="h-l">
<text class="h-name">{{ info ? info.name : '商家' }}</text>
<text class="h-meta">{{ info ? ('结算方式:' + (info.settle_type === 'monthly' ? '月结' : '预付')) : '加载中...' }}</text>
</view>
<view class="h-badge">{{ verifyText }}</view>
</view>
<view class="stats">
<view class="stat"><text class="stat-n">{{ info ? info.order_count : 0 }}</text><text class="stat-l">累计订单</text></view>
<view class="stat"><text class="stat-n">{{ info ? info.total_amount : 0 }}</text><text class="stat-l">累计金额</text></view>
<view class="stat"><text class="stat-n">{{ info ? info.invoiceable : 0 }}</text><text class="stat-l">可开票</text></view>
</view>
</view>
<view class="grid">
<view class="gi" v-for="g in entries" :key="g.key" @tap="g.action">
<view class="gi-icon" :style="{ background: g.bg }"><text class="gi-t" :style="{ color: g.color }">{{ g.icon }}</text></view>
<text class="gi-name">{{ g.name }}</text>
</view>
</view>
<view class="card">
<view class="card-head"><text class="card-title">按月账单</text><text class="card-more" @tap="load">刷新</text></view>
<view class="m-row" v-for="(m, i) in months" :key="i">
<text class="m-month">{{ m.month }}</text>
<text class="m-cnt">{{ m.cnt }} 单</text>
<text class="m-amt">¥{{ m.amount }}</text>
</view>
<view class="empty" v-if="!months.length">暂无账单</view>
</view>
<view class="card">
<view class="card-head"><text class="card-title">近期订单</text><text class="card-more" @tap="go('/pages/order/list')">全部 ›</text></view>
<view class="o-row" v-for="o in orders" :key="o.id">
<view class="o-l">
<text class="o-name">{{ o.service_name }}</text>
<text class="o-no">{{ o.order_no }} · {{ o.time_text }}</text>
</view>
<view class="o-r">
<text class="o-amt">¥{{ o.pay_amount }}</text>
<text class="o-status">{{ o.status_text }}</text>
</view>
</view>
<view class="empty" v-if="!orders.length">暂无订单</view>
</view>
<view class="back" @tap="backToUser">切换到业主身份</view>
</view>
</template>
<script setup>
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
import { isLogin, toLogin } from '@/utils/request.js';
import { setRole } from '@/utils/role.js';
const info = ref(null);
const months = ref([]);
const orders = ref([]);
const verifyText = computed(() => {
if (!info.value) return '';
return { pending: '审核中', pass: '已认证', reject: '未通过' }[info.value.verify_status] || '';
});
const entries = [
{ key: 'batch', name: '批量下单', icon: '批', bg: '#FFF1E0', color: '#E07A2E', action: () => go('/pages/merchant/batch') },
{ key: 'orders', name: '企业订单', icon: '单', bg: '#EAF2FF', color: '#4A7CFF', action: () => go('/pages/order/list') },
{ key: 'invoice', name: '开具发票', icon: '票', bg: '#E8F7EE', color: '#2FA84F', action: () => go('/pages/merchant/invoice') },
{ key: 'profile', name: '企业资料', icon: '档', bg: '#F0EBFF', color: '#7A5AF8', action: () => go('/pages/merchant/apply') },
{ key: 'address', name: '服务地址', icon: '址', bg: '#FFF0F0', color: '#E8331B', action: () => uni.showToast({ title: '地址管理开发中', icon: 'none' }) },
{ key: 'service', name: '联系客服', icon: '服', bg: '#EAF6FF', color: '#2A8FD8', action: () => uni.makePhoneCall({ phoneNumber: '4000000000' }) }
];
function go(url) { uni.navigateTo({ url: url }); }
async function load() {
if (!isLogin()) { toLogin(); return; }
try {
const res = await api.merchantInfo();
if (!res.applied || res.merchant.verify_status !== 'pass') {
uni.redirectTo({ url: '/pages/merchant/apply' });
return;
}
info.value = res.merchant;
} catch (e) { return; }
try {
const b = await api.merchantBills();
months.value = b.months || [];
orders.value = b.orders || [];
} catch (e) {}
}
function backToUser() {
api.switchRole({ role: 'user' }).then((res) => {
setRole('user');
uni.reLaunch({ url: res.redirect || '/YJYF/YJYF' });
}).catch(() => {});
}
onShow(() => load());
</script>
<style scoped>
.page { min-height: 100vh; background: #F5F6F8; padding-bottom: 60rpx; }
.header { position: relative; padding: 34rpx 30rpx 26rpx; overflow: hidden; background: linear-gradient(160deg,#FFB85C 0%,#F98D25 55%,#ED6F0E 100%); }
.deco { position: absolute; width: 320rpx; height: 320rpx; right: -120rpx; top: -130rpx; border-radius: 50%; background: rgba(255,255,255,.13); }
.h-top { position: relative; display: flex; align-items: center; justify-content: space-between; }
.h-l { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.h-name { font-size: 36rpx; font-weight: 700; color: #fff; }
.h-meta { margin-top: 8rpx; font-size: 22rpx; color: rgba(255,255,255,.9); }
.h-badge { flex-shrink: 0; padding: 0 22rpx; line-height: 52rpx; border-radius: 26rpx; background: #fff; color: #E36B0C; font-size: 22rpx; font-weight: 700; }
.stats { position: relative; display: flex; margin-top: 26rpx; padding-top: 22rpx; border-top: 1rpx solid rgba(255,255,255,.25); }
.stat { flex: 1; display: flex; flex-direction: column; align-items: center; }
.stat-n { font-size: 34rpx; font-weight: 700; color: #fff; }
.stat-l { margin-top: 4rpx; font-size: 20rpx; color: rgba(255,255,255,.88); }
.grid { display: flex; flex-wrap: wrap; margin: 22rpx 28rpx 0; padding: 16rpx 0; background: #fff; border-radius: 22rpx; box-shadow: 0 6rpx 20rpx rgba(240,129,31,.06); }
.gi { width: 33.33%; display: flex; flex-direction: column; align-items: center; padding: 18rpx 0; }
.gi-icon { width: 84rpx; height: 84rpx; border-radius: 24rpx; display: flex; align-items: center; justify-content: center; }
.gi-t { font-size: 30rpx; font-weight: 700; }
.gi-name { margin-top: 12rpx; font-size: 22rpx; color: #333; }
.card { margin: 22rpx 28rpx 0; padding: 24rpx; background: #fff; border-radius: 22rpx; box-shadow: 0 6rpx 20rpx rgba(240,129,31,.06); }
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8rpx; }
.card-title { font-size: 28rpx; font-weight: 700; color: #1F1F1F; }
.card-more { font-size: 22rpx; color: #9A9A9A; }
.m-row { display: flex; align-items: center; padding: 16rpx 0; border-bottom: 1rpx solid #F4F4F4; }
.m-month { flex: 1; font-size: 26rpx; color: #333; }
.m-cnt { width: 120rpx; text-align: right; font-size: 22rpx; color: #9A9A9A; }
.m-amt { width: 160rpx; text-align: right; font-size: 28rpx; font-weight: 700; color: #F0710D; }
.o-row { display: flex; align-items: center; justify-content: space-between; padding: 16rpx 0; border-bottom: 1rpx solid #F4F4F4; }
.o-l { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.o-name { font-size: 26rpx; color: #333; }
.o-no { margin-top: 4rpx; font-size: 20rpx; color: #B5B5B5; }
.o-r { display: flex; flex-direction: column; align-items: flex-end; }
.o-amt { font-size: 28rpx; font-weight: 700; color: #F0710D; }
.o-status { margin-top: 4rpx; font-size: 20rpx; color: #9A9A9A; }
.empty { padding: 40rpx 0; text-align: center; font-size: 24rpx; color: #9A9A9A; }
.back { margin: 26rpx 28rpx 0; height: 92rpx; display: flex; align-items: center; justify-content: center; background: #fff; border-radius: 46rpx; font-size: 28rpx; color: #F0710D; font-weight: 600; }
</style>

查看文件

@@ -39,6 +39,14 @@
<view class="role-btn" @tap="masterCard.action">{{ masterCard.btn }}</view> <view class="role-btn" @tap="masterCard.action">{{ masterCard.btn }}</view>
</view> </view>
<view class="rolecard">
<view class="role-top">
<text class="role-title">{{ merchantCard.title }}</text>
<text class="role-sub">{{ merchantCard.desc }}</text>
</view>
<view class="role-btn" @tap="merchantCard.action">{{ merchantCard.btn }}</view>
</view>
<view class="menu"> <view class="menu">
<view class="menu-item" @tap="go('/pages/order/list')"> <view class="menu-item" @tap="go('/pages/order/list')">
<text class="menu-t">我的订单</text><text class="menu-a">›</text> <text class="menu-t">我的订单</text><text class="menu-a">›</text>
@@ -70,11 +78,16 @@
const user = ref(null); const user = ref(null);
const master = ref(null); const master = ref(null);
const merchant = ref(null);
const unread = ref(0); const unread = ref(0);
const coupon = ref(0); const coupon = ref(0);
const avatarText = computed(() => (user.value && user.value.nickname ? user.value.nickname.slice(0, 1) : '我')); const avatarText = computed(() => (user.value && user.value.nickname ? user.value.nickname.slice(0, 1) : '我'));
const roleText = computed(() => (master.value && master.value.verify_status === 'pass' ? '认证师傅' : '业主')); const roleText = computed(() => {
if (master.value && master.value.verify_status === 'pass') return '认证师傅';
if (merchant.value && merchant.value.verify_status === 'pass') return '认证商家';
return '个人用户';
});
const masterCard = computed(() => { const masterCard = computed(() => {
const m = master.value; const m = master.value;
@@ -90,6 +103,20 @@
return { title: '切换为师傅身份', desc: '进入师傅工作台接单', btn: '切换师傅端', action: switchToMaster }; return { title: '切换为师傅身份', desc: '进入师傅工作台接单', btn: '切换师傅端', action: switchToMaster };
}); });
const merchantCard = computed(() => {
const m = merchant.value;
if (!m) {
return { title: '成为优匠优服商家', desc: '企业认证,支持批量下单 / 对账 / 开票', btn: '商家入驻', action: () => go('/pages/merchant/apply') };
}
if (m.verify_status === 'pending') {
return { title: '商家资质审核中', desc: '平台将在 1-2 个工作日内完成审核', btn: '查看进度', action: () => go('/pages/merchant/apply') };
}
if (m.verify_status === 'reject') {
return { title: '商家资质未通过', desc: m.audit_msg || '请补充资料后重新提交', btn: '重新提交', action: () => go('/pages/merchant/apply') };
}
return { title: m.name || '我的企业账号', desc: '进入商家工作台:批量下单 / 账单 / 开票', btn: '切换商家端', action: switchToMerchant };
});
function toast(t) { uni.showToast({ title: t, icon: 'none' }); } function toast(t) { uni.showToast({ title: t, icon: 'none' }); }
function go(url) { uni.navigateTo({ url: url }); } function go(url) { uni.navigateTo({ url: url }); }
function callService() { uni.makePhoneCall({ phoneNumber: '4000000000' }); } function callService() { uni.makePhoneCall({ phoneNumber: '4000000000' }); }
@@ -100,12 +127,22 @@
const res = await api.profile(); const res = await api.profile();
user.value = res; user.value = res;
master.value = res.master; master.value = res.master;
merchant.value = res.merchant;
unread.value = res.unread_count || 0; unread.value = res.unread_count || 0;
coupon.value = res.coupon_count || 0; coupon.value = res.coupon_count || 0;
setUser(res); setUser(res);
} catch (e) {} } catch (e) {}
} }
async function switchToMerchant() {
try {
const res = await api.switchRole({ role: 'merchant' });
setRole('merchant');
uni.showToast({ title: '已切换为商家身份' });
setTimeout(() => uni.reLaunch({ url: res.redirect }), 500);
} catch (e) {}
}
async function switchToMaster() { async function switchToMaster() {
try { try {
const res = await api.switchRole({ role: 'master' }); const res = await api.switchRole({ role: 'master' });

查看文件

@@ -87,6 +87,19 @@ class Auth extends Base
]; ];
} }
$merchant = Db::name('merchant')->where('user_id', $uid)->find();
$merchantInfo = null;
if ($merchant) {
$merchantInfo = [
'id' => (int)$merchant['id'],
'name' => $merchant['name'],
'verify_status' => $merchant['verify_status'],
'audit_msg' => $merchant['audit_msg'],
'settle_type' => $merchant['settle_type'],
'can_order' => $merchant['verify_status'] === 'pass',
];
}
return [ return [
'id' => (int)$user['id'], 'id' => (int)$user['id'],
'nickname' => $user['nickname'] ?: ('用户' . substr((string)$user['mobile'], -4)), 'nickname' => $user['nickname'] ?: ('用户' . substr((string)$user['mobile'], -4)),
@@ -97,6 +110,8 @@ class Auth extends Base
'unread_count' => (int)$unread, 'unread_count' => (int)$unread,
'is_master' => $master ? true : false, 'is_master' => $master ? true : false,
'master' => $masterInfo, 'master' => $masterInfo,
'is_merchant' => $merchant ? true : false,
'merchant' => $merchantInfo,
]; ];
} }
@@ -141,9 +156,10 @@ class Auth extends Base
public function switchRole() public function switchRole()
{ {
$role = $this->request->post('role', 'user'); $role = $this->request->post('role', 'user');
if (!in_array($role, ['user', 'master'], true)) { if (!in_array($role, ['user', 'master', 'merchant'], true)) {
$this->error('角色参数错误'); $this->error('角色参数错误');
} }
if ($role === 'master') { if ($role === 'master') {
$master = $this->masterInfo(); $master = $this->masterInfo();
if (!$master) { if (!$master) {
@@ -156,9 +172,27 @@ class Auth extends Base
$this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003); $this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003);
} }
} }
$this->success('切换成功', [
'role' => $role, if ($role === 'merchant') {
'redirect' => $role === 'master' ? '/pages/master/workbench' : '/YJYF/YJYF', $merchant = Db::name('merchant')->where('user_id', $this->uid())->find();
]); if (!$merchant) {
$this->error('请先完成商家入驻', ['need_apply' => 1], 2001);
}
if ($merchant['verify_status'] === 'pending') {
$this->error('商家资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
}
if ($merchant['verify_status'] === 'reject') {
$this->error('资质未通过:' . $merchant['audit_msg'], ['verify_status' => 'reject'], 2003);
}
}
$redirect = '/YJYF/YJYF';
if ($role === 'master') {
$redirect = '/pages/master/workbench';
} elseif ($role === 'merchant') {
$redirect = '/pages/merchant/workbench';
}
$this->success('切换成功', ['role' => $role, 'redirect' => $redirect]);
} }
} }

查看文件

@@ -0,0 +1,292 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 商家端(企业账号):入驻 / 资料 / 账单 / 开票 / 批量下单归属
*/
class Merchant extends Base
{
/**
* 商家入驻 / 重新提交
* @ApiMethod (POST)
*/
public function apply()
{
$data = [
'name' => trim((string)$this->request->post('name')),
'license_no' => trim((string)$this->request->post('license_no')),
'license_image' => (string)$this->request->post('license_image'),
'legal_person' => trim((string)$this->request->post('legal_person')),
'contact' => trim((string)$this->request->post('contact')),
'mobile' => trim((string)$this->request->post('mobile')),
'province' => trim((string)$this->request->post('province')),
'city' => trim((string)$this->request->post('city')),
'district' => trim((string)$this->request->post('district')),
'address' => trim((string)$this->request->post('address')),
'invoice_title' => trim((string)$this->request->post('invoice_title')),
'invoice_tax_no' => trim((string)$this->request->post('invoice_tax_no')),
'invoice_bank' => trim((string)$this->request->post('invoice_bank')),
'invoice_account' => trim((string)$this->request->post('invoice_account')),
'settle_type' => $this->request->post('settle_type', 'prepay'),
];
if ($data['name'] === '' || $data['license_no'] === '' || $data['contact'] === '' || $data['mobile'] === '') {
$this->error('请填写企业名称、统一社会信用代码、联系人和电话');
}
if (!preg_match('/^1\d{10}$/', $data['mobile'])) {
$this->error('联系电话格式不正确');
}
if (!in_array($data['settle_type'], ['prepay', 'monthly'], true)) {
$data['settle_type'] = 'prepay';
}
$exist = Db::name('merchant')->where('user_id', $this->uid())->find();
if ($exist && $exist['verify_status'] === 'pass') {
$this->error('您已是认证商家,无需重复入驻');
}
$save = array_merge($data, [
'verify_status' => 'pending',
'audit_msg' => '',
'updatetime' => time(),
]);
if ($exist) {
Db::name('merchant')->where('id', $exist['id'])->update($save);
$id = (int)$exist['id'];
} else {
$save['user_id'] = $this->uid();
$save['createtime'] = time();
$id = Db::name('merchant')->insertGetId($save);
}
$this->success('提交成功,请等待审核', ['merchant_id' => $id]);
}
/**
* 商家档案与经营数据
*/
public function info()
{
$merchant = $this->merchantInfo();
if (!$merchant) {
$this->success('未入驻', ['applied' => false]);
return;
}
$uid = $this->uid();
$orderCount = (int)Db::name('order')->where('user_id', $uid)->where('pay_status', 1)->count();
$totalAmount = (float)Db::name('order')->where('user_id', $uid)->where('pay_status', 1)->sum('pay_amount');
$invoiced = (float)Db::name('invoice')->where('merchant_id', $merchant['id'])->where('status', 'issued')->sum('amount');
$this->success('', [
'applied' => true,
'merchant' => [
'id' => (int)$merchant['id'],
'name' => $merchant['name'],
'license_no' => $merchant['license_no'],
'legal_person' => $merchant['legal_person'],
'contact' => $merchant['contact'],
'mobile' => $merchant['mobile'],
'address' => $merchant['province'] . $merchant['city'] . $merchant['district'] . $merchant['address'],
'invoice_title' => $merchant['invoice_title'],
'invoice_tax_no' => $merchant['invoice_tax_no'],
'settle_type' => $merchant['settle_type'],
'verify_status' => $merchant['verify_status'],
'audit_msg' => $merchant['audit_msg'],
'order_count' => $orderCount,
'total_amount' => round($totalAmount, 2),
'invoiced_amount' => round($invoiced, 2),
'invoiceable' => round(max(0, $totalAmount - $invoiced), 2),
],
]);
}
/**
* 维护资料(联系人 / 地址 / 开票信息)
* @ApiMethod (POST)
*/
public function update()
{
$merchant = $this->requireMerchant();
$fields = ['contact', 'mobile', 'province', 'city', 'district', 'address',
'invoice_title', 'invoice_tax_no', 'invoice_bank', 'invoice_account'];
$data = ['updatetime' => time()];
foreach ($fields as $f) {
$v = $this->request->post($f, null);
if ($v !== null) {
$data[$f] = trim((string)$v);
}
}
if (isset($data['mobile']) && $data['mobile'] !== '' && !preg_match('/^1\d{10}$/', $data['mobile'])) {
$this->error('联系电话格式不正确');
}
Db::name('merchant')->where('id', $merchant['id'])->update($data);
$this->success('已保存');
}
/**
* 账单中心:按月汇总 + 近期订单
*/
public function bills()
{
$this->requireMerchant();
$uid = $this->uid();
$months = Db::name('order')
->field("FROM_UNIXTIME(createtime,'%Y-%m') as month, count(*) as cnt, sum(pay_amount) as amount")
->where('user_id', $uid)->where('pay_status', 1)
->group('month')->order('month desc')->limit(12)->select();
foreach ($months as &$m) {
$m['amount'] = round((float)$m['amount'], 2);
$m['cnt'] = (int)$m['cnt'];
}
unset($m);
$orders = Db::name('order')->field('id,order_no,service_name,pay_amount,status,createtime')
->where('user_id', $uid)->order('id desc')->limit(20)->select();
foreach ($orders as &$o) {
$o['pay_amount'] = (float)$o['pay_amount'];
$o['status_text'] = \app\common\library\OrderStatus::label($o['status']);
$o['time_text'] = date('Y-m-d H:i', (int)$o['createtime']);
}
unset($o);
$this->success('', ['months' => $months, 'orders' => $orders]);
}
/**
* 开票记录
*/
public function invoices()
{
$merchant = $this->requireMerchant();
$list = Db::name('invoice')->where('merchant_id', $merchant['id'])->order('id desc')->limit(30)->select();
$statusText = ['wait' => '开票中', 'issued' => '已开票', 'reject' => '已驳回'];
foreach ($list as &$row) {
$row['amount'] = (float)$row['amount'];
$row['status_text'] = isset($statusText[$row['status']]) ? $statusText[$row['status']] : $row['status'];
$row['type_text'] = $row['type'] === 'special' ? '专用发票' : '普通发票';
$row['time_text'] = date('Y-m-d H:i', (int)$row['createtime']);
}
unset($row);
$this->success('', ['list' => $list]);
}
/**
* 申请开票
* @ApiMethod (POST)
*/
public function invoice()
{
$merchant = $this->requireMerchant();
$amount = round((float)$this->request->post('amount'), 2);
$type = $this->request->post('type', 'normal');
$email = trim((string)$this->request->post('email'));
if ($amount <= 0) {
$this->error('请填写开票金额');
}
if (!in_array($type, ['normal', 'special'], true)) {
$this->error('发票类型错误');
}
$paid = (float)Db::name('order')->where('user_id', $this->uid())->where('pay_status', 1)->sum('pay_amount');
$used = (float)Db::name('invoice')->where('merchant_id', $merchant['id'])->where('status', 'in', ['wait', 'issued'])->sum('amount');
$available = round(max(0, $paid - $used), 2);
if ($amount > $available) {
$this->error('可开票金额不足,当前可开 ¥' . $available);
}
Db::name('invoice')->insert([
'merchant_id' => (int)$merchant['id'],
'user_id' => $this->uid(),
'amount' => $amount,
'type' => $type,
'title' => $merchant['invoice_title'] ?: $merchant['name'],
'tax_no' => $merchant['invoice_tax_no'],
'email' => $email,
'status' => 'wait',
'createtime' => time(),
'updatetime' => time(),
]);
$this->success('开票申请已提交,3 个工作日内开具');
}
/**
* 批量下单后绑定批次(订单本身走已验收的 /order/create)
* @ApiMethod (POST)
*/
public function bindBatch()
{
$merchant = $this->requireMerchant();
// 兼容三种入参:数组 / 逗号串 / 混合
$raw = $this->request->post('order_ids');
$orderIds = [];
foreach ((array)$raw as $v) {
foreach (explode(',', (string)$v) as $one) {
$one = (int)$one;
if ($one > 0) {
$orderIds[] = $one;
}
}
}
$orderIds = array_values(array_unique($orderIds));
$batchNo = trim((string)$this->request->post('batch_no', ''));
if (empty($orderIds)) {
$this->error('缺少订单');
}
if ($batchNo === '') {
$batchNo = date('YmdHis') . mt_rand(100, 999);
}
$ok = 0;
foreach ($orderIds as $oid) {
$oid = (int)$oid;
if (!Db::name('order')->where('id', $oid)->where('user_id', $this->uid())->find()) {
continue;
}
if (Db::name('merchant_order')->where('order_id', $oid)->find()) {
continue;
}
Db::name('merchant_order')->insert([
'merchant_id' => (int)$merchant['id'],
'order_id' => $oid,
'batch_no' => $batchNo,
'createtime' => time(),
]);
$ok++;
}
$this->success('已归属到批次', ['batch_no' => $batchNo, 'count' => $ok]);
}
/**
* 当前用户商家档案
*/
protected function merchantInfo()
{
return Db::name('merchant')->where('user_id', $this->uid())->find();
}
/**
* 要求已通过审核的商家
*/
protected function requireMerchant()
{
$m = $this->merchantInfo();
if (!$m) {
$this->error('请先完成商家入驻', ['need_apply' => 1], 2001);
}
if ($m['verify_status'] === 'pending') {
$this->error('商家资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
}
if ($m['verify_status'] === 'reject') {
$this->error('资质未通过:' . $m['audit_msg'], ['verify_status' => 'reject'], 2003);
}
return $m;
}
}

查看文件

@@ -33,9 +33,16 @@ class WxLogin
} }
$wx = json_decode($resp, true); $wx = json_decode($resp, true);
if (empty($wx['openid'])) { if (empty($wx['openid'])) {
$ec = isset($wx['errcode']) ? $wx['errcode'] : '-'; $ec = isset($wx['errcode']) ? (int)$wx['errcode'] : 0;
$em = isset($wx['errmsg']) ? $wx['errmsg'] : '未知错误'; $em = isset($wx['errmsg']) ? $wx['errmsg'] : '未知错误';
return ['error' => '微信登录失败(' . $ec . '):' . $em]; $hint = [
40029 => '小程序 appid 与服务端配置不一致:请确认 manifest.json 的 mp-weixin.appid 为 ' . $appid,
40125 => 'appsecret 配置错误,请检查 .env 的 [wechat] secret',
45011 => '登录请求过于频繁,请稍后重试',
40226 => '该微信账号被风控限制,请稍后再试',
];
$msg = isset($hint[$ec]) ? $hint[$ec] : ('微信登录失败(' . $ec . '):' . $em);
return ['error' => $msg, 'errcode' => $ec];
} }
return $wx; return $wx;
} }

查看文件

@@ -37,7 +37,7 @@ const sql = (s) => execFileSync('ssh', ['-o', 'BatchMode=yes', 'root@8.137.181.6
sec('微信授权登录'); sec('微信授权登录');
let r = await api('/auth/wxlogin', { method: 'POST', data: { code: 'invalid_code_x' } }); let r = await api('/auth/wxlogin', { method: 'POST', data: { code: 'invalid_code_x' } });
chk(r.code !== 1 && /微信登录失败/.test(r.msg || ''), '无效 code 被微信侧拒绝并回显原因', r.msg); chk(r.code !== 1 && /微信登录失败|appid/.test(r.msg || ''), '无效 code 被微信侧拒绝并给出排查指引', r.msg);
r = await api('/auth/wxlogin', { method: 'POST', data: {} }); r = await api('/auth/wxlogin', { method: 'POST', data: {} });
chk(r.code !== 1, '缺少 code 时参数校验生效', r.msg); chk(r.code !== 1, '缺少 code 时参数校验生效', r.msg);

136
tests/phase3_merchant.js 普通文件
查看文件

@@ -0,0 +1,136 @@
/**
* Phase 3 验证:商家(企业账号)注册 / 登录 / 全业务流程
* 运行:node tests/phase3_merchant.js
*/
const { execFileSync } = require('child_process');
const BASE = process.env.API_BASE || 'https://yjyf.gzyakj.com.cn/api';
let pass = 0, fail = 0;
const failures = [];
const ok = (m, e) => { pass++; console.log(' ✅ ' + m + (e ? ' → ' + e : '')); };
const bad = (m, e) => { fail++; failures.push(m + ' :: ' + e); console.log(' ❌ ' + m + ' → ' + e); };
const chk = (c, m, e) => (c ? ok(m, e) : bad(m, e || '断言失败'));
const sec = (t) => console.log('\n▌' + t);
async function api(path, opt) {
const o = opt || {};
const headers = {};
if (o.token) headers.token = o.token;
let body;
if (o.data) {
headers['content-type'] = 'application/x-www-form-urlencoded';
body = new URLSearchParams(o.data).toString();
}
const res = await fetch(BASE + path, { method: o.method || 'GET', headers, body });
const text = await res.text();
try { return JSON.parse(text); } catch (e) { throw new Error('非 JSON: ' + text.slice(0, 120)); }
}
const sql = (s) => execFileSync('ssh', ['-o', 'BatchMode=yes', 'root@8.137.181.63', `mysql -uyjyf -pyjyf yjyf -e "${s}"`], { encoding: 'utf8' }).trim();
(async () => {
const stamp = String(Date.now()).slice(-8);
const mobile = '138' + stamp;
console.log('═══════════════════════════════════════════════════');
console.log(' Phase 3 验证:商家注册 / 登录 / 全业务流程');
console.log('═══════════════════════════════════════════════════');
sec('账号与身份');
const login = await api('/auth/login', { method: 'POST', data: { mobile: mobile, code: '123456' } });
const token = login.data.token;
chk(login.code === 1, '手机号登录(微信不可用时的兜底通道)');
chk(login.data.userinfo.is_merchant === false, '新账号默认个人用户');
let r = await api('/auth/switchRole', { method: 'POST', token: token, data: { role: 'merchant' } });
chk(r.code === 2001 && r.data.need_apply === 1, '未入驻切商家被拦截(2001)', r.msg);
sec('商家入驻');
r = await api('/merchant/apply', {
method: 'POST', token: token,
data: {
name: '遵义优匠物业服务有限公司', license_no: '91520300MA6XXXXX1A',
legal_person: '王老板', contact: '李经理', mobile: mobile,
province: '贵州省', city: '遵义市', district: '汇川区', address: '大连路 100 号 3 楼',
invoice_title: '遵义优匠物业服务有限公司', invoice_tax_no: '91520300MA6XXXXX1A',
settle_type: 'monthly'
}
});
chk(r.code === 1 && r.data.merchant_id > 0, '提交企业资料', 'merchant_id=' + r.data.merchant_id);
const merchantId = r.data.merchant_id;
r = await api('/merchant/info', { token: token });
chk(r.data.applied && r.data.merchant.verify_status === 'pending', '入驻后状态=待审核');
chk(r.data.merchant.settle_type === 'monthly', '结算方式保存为月结');
r = await api('/auth/switchRole', { method: 'POST', token: token, data: { role: 'merchant' } });
chk(r.code === 2002, '审核中切商家被拦截(2002)', r.msg);
sql(`UPDATE fa_merchant SET verify_status='pass' WHERE id=${merchantId}`);
r = await api('/auth/switchRole', { method: 'POST', token: token, data: { role: 'merchant' } });
chk(r.code === 1 && r.data.redirect === '/pages/merchant/workbench', '审核通过 → 切换商家端', r.data && r.data.redirect);
sec('工作台数据');
r = await api('/merchant/info', { token: token });
const m = r.data.merchant;
chk(m && Number(m.order_count) === 0 && Number(m.total_amount) === 0, '初始经营数据为 0', '订单 ' + m.order_count + ' / 金额 ' + m.total_amount);
chk(m.invoiceable !== undefined, '可开票金额字段就绪', '¥' + m.invoiceable);
sec('批量下单');
const svc = (await api('/home/services?cat_id=1')).data.list.find(s => s.price_type === 'fixed');
const orderIds = [];
for (const i of [1, 2]) {
const addr = await api('/address/save', {
method: 'POST', token: token,
data: { contact: '门店' + i, mobile: mobile, province: '贵州省', city: '遵义市', district: '汇川区', address: '批量测试地址 ' + i, floor: 3, has_elevator: 1, is_default: 0 }
});
const o = await api('/order/create', { method: 'POST', token: token, data: { service_id: svc.id, address_id: addr.data.id, goods_num: 1, remark: '商家批量下单' } });
await api('/order/pay', { method: 'POST', token: token, data: { order_id: o.data.order_id } });
orderIds.push(o.data.order_id);
}
chk(orderIds.length === 2, '逐单创建并支付', orderIds.join(','));
r = await api('/merchant/bindBatch', { method: 'POST', token: token, data: { order_ids: orderIds.join(','), batch_no: '' } });
chk(r.code === 1 && r.data.count === 2 && r.data.batch_no, '归属到同一批次', 'batch_no=' + r.data.batch_no + ' count=' + r.data.count);
r = await api('/merchant/bindBatch', { method: 'POST', token: token, data: { order_ids: orderIds.join(','), batch_no: '' } });
chk(r.code === 1 && r.data.count === 0, '重复归属被忽略(幂等)', 'count=' + r.data.count);
sec('账单中心');
r = await api('/merchant/bills', { token: token });
chk(r.code === 1 && r.data.months.length >= 1, '按月汇总生成', r.data.months[0] && (r.data.months[0].month + ' / ' + r.data.months[0].cnt + ' 单 / ¥' + r.data.months[0].amount));
chk(r.data.orders.length === 2, '近期订单明细', r.data.orders.length + ' 条');
sec('开票');
r = await api('/merchant/info', { token: token });
const available = Number(r.data.merchant.invoiceable);
chk(available > 0, '可开票金额已累计', '¥' + available);
r = await api('/merchant/invoice', { method: 'POST', token: token, data: { amount: available + 100, type: 'normal' } });
chk(r.code !== 1, '超额开票被拦截', r.msg);
r = await api('/merchant/invoice', { method: 'POST', token: token, data: { amount: 50, type: 'special', email: 'fin@example.com' } });
chk(r.code === 1, '提交开票申请(专用发票)', r.msg);
r = await api('/merchant/invoices', { token: token });
chk(r.code === 1 && r.data.list.length === 1 && r.data.list[0].type_text === '专用发票', '开票记录回显', r.data.list[0] && r.data.list[0].status_text);
r = await api('/merchant/invoice', { method: 'POST', token: token, data: { amount: available, type: 'normal' } });
chk(r.code !== 1, '已申请金额占用额度(防重复开票)', r.msg);
sec('资料维护与身份切回');
r = await api('/merchant/update', { method: 'POST', token: token, data: { contact: '新经理', mobile: mobile } });
chk(r.code === 1, '维护联系人', r.msg);
r = await api('/merchant/info', { token: token });
chk(r.data.merchant.contact === '新经理', '资料已更新');
r = await api('/auth/switchRole', { method: 'POST', token: token, data: { role: 'user' } });
chk(r.code === 1 && r.data.redirect === '/YJYF/YJYF', '切回个人用户', r.data && r.data.redirect);
r = await api('/auth/profile', { token: token });
chk(r.data.is_merchant === true && Number(r.data.merchant.id) === Number(merchantId), 'profile 携带商家身份', 'merchant_id=' + r.data.merchant.id);
console.log('\n═══════════════════════════════════════════════════');
console.log(` 结果:通过 ${pass} 项 / 失败 ${fail} 项`);
if (fail) { console.log(' 失败明细:'); failures.forEach(f => console.log(' - ' + f)); process.exitCode = 1; }
else console.log(' 🎉 商家注册/登录/批量下单/对账/开票 全流程通过');
console.log('═══════════════════════════════════════════════════');
})().catch(e => { console.error('\n💥 中断: ' + e.message); process.exitCode = 1; });

查看文件

@@ -54,5 +54,14 @@ export default {
/* ---------- 评价 ---------- */ /* ---------- 评价 ---------- */
reviewCreate: (data) => post('/review/create', data), reviewCreate: (data) => post('/review/create', data),
reviewList: (masterId) => get('/review/masterList', { master_id: masterId }) reviewList: (masterId) => get('/review/masterList', { master_id: masterId }),
/* ---------- 商家端 ---------- */
merchantApply: (data) => post('/merchant/apply', data),
merchantInfo: () => get('/merchant/info'),
merchantUpdate: (data) => post('/merchant/update', data),
merchantBills: () => get('/merchant/bills'),
merchantInvoices: () => get('/merchant/invoices'),
merchantInvoice: (data) => post('/merchant/invoice', data),
merchantBindBatch: (data) => post('/merchant/bindBatch', data)
}; };