feat: 新增账号安全模块及资质校验功能

- 新增账号安全页面及支付密码验证组件
- 新增用户类型选择流程及商家资质管理
- 新增订单资质校验逻辑,师傅需满足订单证书要求
- 新增企业资质认证相关数据库表及接口
- 优化用户列表展示,区分个人与商家用户类型
这个提交包含在:
2026-11-21 15:37:01 +08:00
父节点 8a35d93a15
当前提交 b71980dd6b
共有 58 个文件被更改,包括 1515 次插入 和 169 次删除

查看文件

@@ -0,0 +1,19 @@
-- Apply after schema_account_security.sql. Existing shared locks are preserved
-- for both credentials because their original source cannot be distinguished.
DELIMITER $$
DROP PROCEDURE IF EXISTS `migrate_account_security_lockout`$$
CREATE PROCEDURE `migrate_account_security_lockout`()
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fa_user_security'
AND COLUMN_NAME = 'payment_failed_attempts') THEN
ALTER TABLE `fa_user_security`
ADD COLUMN `payment_failed_attempts` int unsigned NOT NULL DEFAULT 0,
ADD COLUMN `payment_locked_until` int unsigned NOT NULL DEFAULT 0;
UPDATE `fa_user_security`
SET `payment_failed_attempts` = `failed_attempts`, `payment_locked_until` = `locked_until`;
END IF;
END$$
CALL `migrate_account_security_lockout`()$$
DROP PROCEDURE `migrate_account_security_lockout`$$
DELIMITER ;

查看文件

@@ -0,0 +1,8 @@
-- Separate the user enterprise-certification menu from the existing enterprise business records.
UPDATE fa_auth_rule SET title='企业业务档案', remark='企业业务记录、订单、员工和开票档案', updatetime=UNIX_TIMESTAMP() WHERE name='merchant';
INSERT INTO fa_auth_rule (type,pid,name,title,icon,ismenu,weigh,status,createtime,updatetime)
SELECT 'file',p.id,'merchant/certificates','企业资质认证','fa fa-id-card-o',1,164,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
FROM fa_auth_rule p WHERE p.name='user' AND NOT EXISTS (SELECT 1 FROM fa_auth_rule WHERE name='merchant/certificates');
-- Preserve access for existing roles that could already view merchant records.
UPDATE fa_auth_group g JOIN fa_auth_rule oldrule ON oldrule.name='merchant' JOIN fa_auth_rule cert ON cert.name='merchant/certificates'
SET g.rules=CONCAT(g.rules,',',cert.id) WHERE g.rules <> '*' AND FIND_IN_SET(oldrule.id,g.rules)>0 AND FIND_IN_SET(cert.id,g.rules)=0;

查看文件

@@ -0,0 +1,23 @@
CREATE TABLE IF NOT EXISTS `fa_user_security` (
`user_id` int unsigned NOT NULL,
`payment_password_hash` varchar(255) NOT NULL DEFAULT '',
`failed_attempts` int unsigned NOT NULL DEFAULT 0,
`locked_until` int unsigned NOT NULL DEFAULT 0,
`payment_failed_attempts` int unsigned NOT NULL DEFAULT 0,
`payment_locked_until` int unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='账号安全凭证';
CREATE TABLE IF NOT EXISTS `fa_user_enterprise_cert` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`user_id` int unsigned NOT NULL,
`company_name` varchar(255) NOT NULL,
`license_no` varchar(64) NOT NULL,
`license_image` varchar(255) NOT NULL,
`legal_person` varchar(100) NOT NULL DEFAULT '',
`verify_status` enum('pending','pass','reject') NOT NULL DEFAULT 'pending',
`audit_msg` varchar(500) NOT NULL DEFAULT '',
`createtime` int unsigned NOT NULL DEFAULT 0,
`updatetime` int unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`), KEY `verify_status` (`verify_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户企业资质认证';

查看文件

@@ -0,0 +1,8 @@
-- Preserve existing users as already classified; new accounts must select once.
ALTER TABLE `fa_user`
ADD COLUMN `identity_selected` tinyint(1) NOT NULL DEFAULT 1 COMMENT '用户类型是否已选择',
ADD COLUMN `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '商家资料公司名称',
ADD COLUMN `company_legal_person` varchar(100) NOT NULL DEFAULT '' COMMENT '商家资料法人姓名',
ADD COLUMN `company_legal_mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '商家资料法人手机号',
ADD COLUMN `company_tech_mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '商家资料技术手机号';
ALTER TABLE `fa_user` ALTER COLUMN `identity_selected` SET DEFAULT 0;

查看文件

@@ -80,7 +80,7 @@ class Home extends Backend
// 4. 实时待办预警与风控中心(6大核心运营待办)
$pendingMaster = Master::where('verify_status', 'pending')->count();
$pendingMerchant = Merchant::where('verify_status', 'pending')->count();
$pendingMerchant = Db::name('user_enterprise_cert')->where('verify_status', 'pending')->count();
$waitingAppeal = Appeal::where('status', 'wait')->count();
$waitingWithdraw = Withdraw::where('status', 'wait')->count();
$waitingInvoice = Db::name('invoice')->where('status', 'wait')->count();

查看文件

@@ -144,7 +144,7 @@ class MasterCert extends Backend
? "技能证书审核通过({$certName})"
: "技能证书审核未通过({$certName})";
$msgContent = $status === 'pass'
? "您上传的「{$certName}」已通过平台审核,可正常承接对应资质要求的工单。"
? "您上传的「{$certName}」已通过平台审核,有效期内可向相关订单用户展示。"
: ("您上传的「{$certName}」未通过审核,原因:" . ($auditMsg !== '' ? $auditMsg : '照片不清晰或证件不符合要求,请重新上传。'));
Db::name('message')->insert([

查看文件

@@ -30,12 +30,68 @@ class Merchant extends Backend
$this->view->assign("verifyStatusList", $this->model->getVerifyStatusList());
}
/** 独立展示用户提交的企业资质;审核接口沿用原权限。 */
public function certificates()
{
return $this->view->fetch();
}
public function index()
{
$this->request->filter(['strip_tags', 'trim']);
if (false === $this->request->isAjax()) {
return $this->view->fetch();
}
if ($this->request->isPost() && $this->request->post('view') === 'audit_cert') {
if (!$this->auth->check('merchant/edit')) $this->error('无权审核企业资质');
$this->token();
$id = (int)$this->request->post('id');
$decision = (string)$this->request->post('decision', '');
$reason = trim((string)$this->request->post('audit_msg', ''));
if (!in_array($decision, ['pass', 'reject'], true)) $this->error('审核状态无效');
if ($decision === 'reject' && $reason === '') $this->error('请输入驳回原因');
if (mb_strlen($reason) > 500) $this->error('驳回原因过长');
$updated = Db::name('user_enterprise_cert')->where('id', $id)->where('verify_status', 'pending')->update([
'verify_status' => $decision, 'audit_msg' => $decision === 'reject' ? $reason : '', 'updatetime' => time(),
]);
if (!$updated) $this->error('申请不存在或已处理,请刷新');
$this->success('审核完成');
}
if ($this->request->get('view') === 'certs') {
$offset = max(0, (int)$this->request->get('offset', 0));
$limit = min(100, max(1, (int)$this->request->get('limit', 20)));
$search = trim((string)$this->request->get('search', ''));
$makeQuery = function () use ($search) {
$query = Db::name('user_enterprise_cert')->alias('c')->join('user u', 'u.id = c.user_id', 'LEFT');
if ($search !== '') $query->where(function ($q) use ($search) {
$q->where('c.company_name', 'like', '%' . $search . '%')->whereOr('c.license_no', 'like', '%' . $search . '%')->whereOr('u.mobile', 'like', '%' . $search . '%');
});
return $query;
};
$total = $makeQuery()->count();
$rows = $makeQuery()->field('c.*,u.nickname,u.mobile,u.user_type')->order('c.id', 'desc')->limit($offset, $limit)->select();
foreach ($rows as &$row) $row['license_url'] = cdnurl($row['license_image'], true);
unset($row);
return json(['total' => $total, 'rows' => $rows]);
}
if ($this->request->get('view') === 'accounts') {
$offset = max(0, (int)$this->request->get('offset', 0));
$limit = min(100, max(1, (int)$this->request->get('limit', 20)));
$search = trim((string)$this->request->get('search', ''));
$makeQuery = function () use ($search) {
$query = Db::name('user')->where('user_type', 'merchant')->where('identity_selected', 1);
if ($search !== '') $query->where(function ($q) use ($search) {
$q->where('nickname', 'like', '%' . $search . '%')
->whereOr('mobile', 'like', '%' . $search . '%')
->whereOr('company_name', 'like', '%' . $search . '%');
});
return $query;
};
$total = $makeQuery()->count();
$rows = $makeQuery()->field('id,nickname,mobile,company_name,company_legal_person,company_legal_mobile,company_tech_mobile,createtime')
->order('id', 'desc')->limit($offset, $limit)->select();
return json(['total' => $total, 'rows' => $rows]);
}
if ($this->request->request('keyField')) {
return $this->selectpage();
}

查看文件

@@ -445,6 +445,9 @@ class Order extends Backend
if (!$targetMaster || $targetMaster['verify_status'] !== 'pass') {
$this->error('所选师傅不存在或未通过实名认证');
}
if (!\app\common\library\OrderQualification::forMaster($row['qual_req'] ?? '', $masterId)) {
$this->error('所选师傅未持有符合订单要求的有效认证证书:' . $row['qual_req']);
}
$oldMasterId = (int)$row['master_id'];
if ($oldMasterId === $masterId && (int)$row['status'] >= 3) {
$this->error('当前工单已由该师傅承接,无需重复指派');

查看文件

@@ -39,11 +39,13 @@ class User extends Backend
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with('group')
->where($where)
->order($sort, $order)
->paginate($limit);
$filters = json_decode((string)$this->request->get('filter', '{}'), true);
$selectedType = is_array($filters) ? ($filters['user_type'] ?? null) : null;
$query = $this->model->with('group')->where($where);
if (in_array($selectedType, ['personal', 'merchant'], true)) {
$query->where('user.identity_selected', 1);
}
$list = $query->order($sort, $order)->paginate($limit);
$rows = $list->items();
$uids = array_column($rows, 'id');
@@ -103,6 +105,13 @@ class User extends Backend
$v->hidden(['password', 'salt']);
$roles = [];
if (!(int)$v['identity_selected']) {
$roles[] = ['type' => 'unselected', 'label' => '待选择用户类型'];
} elseif ($v['user_type'] === 'merchant') {
$roles[] = ['type' => 'merchant_user', 'label' => '商家用户'];
} else {
$roles[] = ['type' => 'owner', 'label' => '个人用户'];
}
if (isset($masterMap[$uid]) && $masterMap[$uid]['verify_status'] === 'pass') {
$roles[] = ['type' => 'master', 'label' => '认证师傅 (' . $masterMap[$uid]['realname'] . ')'];
}
@@ -111,10 +120,6 @@ class User extends Backend
} elseif (isset($memberMap[$uid]) && !empty($memberMap[$uid])) {
$roles[] = ['type' => 'member', 'label' => '企业子账号 (' . $memberMap[$uid] . ')'];
}
if (empty($roles)) {
$roles[] = ['type' => 'owner', 'label' => '个人业主'];
}
$v['role_badges'] = $roles;
$v['order_count'] = $orderStatMap[$uid]['cnt'] ?? 0;
$v['total_spent'] = $orderStatMap[$uid]['spent'] ?? '0.00';
@@ -139,6 +144,7 @@ class User extends Backend
$uid = (int)$row['id'];
$masterProfile = Db::name('master')->where('user_id', $uid)->find();
$enterpriseCert = Db::name('user_enterprise_cert')->where('user_id', $uid)->find();
$merchantProfile = Db::name('merchant')->where('user_id', $uid)->find();
if (!$merchantProfile) {
$memberBind = Db::name('merchant_member')->alias('mm')
@@ -201,6 +207,7 @@ class User extends Backend
'row' => $row,
'masterProfile' => $masterProfile,
'merchantProfile' => $merchantProfile,
'enterpriseCert' => $enterpriseCert,
'addressList' => $addressList,
'recentOrders' => $recentOrders,
'coupons' => $coupons,

查看文件

@@ -61,4 +61,7 @@
config: {$config|json_encode}
};
require.config.site.version += "-admin-list-20261119";
if (require.config.controllername === 'merchant' || require.config.controllername === 'user.user') {
require.config.site.version += "-identity-security-20261121";
}
</script>

查看文件

@@ -448,13 +448,13 @@
</a>
<!-- 商家待审 -->
<a href="{:url('merchant/index', ['verify_status' => 'pending'])}" class="action-card addtabsit" title="企业商家">
<a href="{:url('merchant/certificates')}" class="action-card addtabsit" title="企业资质认证">
<div class="action-info">
<div class="action-icon" style="background: #f0fdf4; color: #16a34a;">
<i class="fa fa-building-o"></i>
</div>
<div class="action-text">
<div class="name">商家待审核</div>
<div class="name">企业资质待审核</div>
<div class="sub">企业资质核验</div>
</div>
</div>

查看文件

@@ -0,0 +1,8 @@
<div class="panel panel-default panel-intro">
<div class="panel-heading"><strong>企业资质认证</strong><p class="text-muted">个人用户和商家用户均可提交企业资质认证;认证不会改变用户类型。</p></div>
<div class="panel-body">
<form id="cert-audit-token">{:token()}</form>
<div id="certs-toolbar" class="toolbar"><a href="javascript:;" class="btn btn-primary" id="certs-refresh" title="刷新"><i class="fa fa-refresh"></i></a></div>
<table id="certs-table" class="table table-striped table-bordered table-hover table-nowrap" data-operate-audit="{:$auth->check('merchant/edit')}" width="100%"></table>
</div>
</div>

查看文件

@@ -1,8 +1,8 @@
<div class="panel panel-default panel-intro">
<div class="panel-heading">
{:build_heading(null,FALSE)}
<span>企业业务档案及旧资质记录</span>
<ul class="nav nav-tabs" data-field="verify_status">
<li class="{:$Think.get.verify_status === null ? 'active' : ''}"><a href="#t-all" data-value="" data-toggle="tab">全部商家</a></li>
<li class="{:$Think.get.verify_status === null ? 'active' : ''}"><a href="#t-all" data-value="" data-toggle="tab">全部档案</a></li>
<li class="{:$Think.get.verify_status === 'pending' ? 'active' : ''}"><a href="#t-pending" data-value="pending" data-toggle="tab"><i class="fa fa-clock-o text-warning"></i> 企业资质待审</a></li>
<li class="{:$Think.get.verify_status === 'pass' ? 'active' : ''}"><a href="#t-pass" data-value="pass" data-toggle="tab"><i class="fa fa-check-circle text-success"></i> 认证通过</a></li>
<li class="{:$Think.get.verify_status === 'reject' ? 'active' : ''}"><a href="#t-reject" data-value="reject" data-toggle="tab"><i class="fa fa-times-circle text-danger"></i> 已驳回</a></li>
@@ -30,3 +30,4 @@
</div>
</div>
</div>

查看文件

@@ -35,12 +35,16 @@
<div class="ud-name">
<span>{$row.nickname|default=$row.username|htmlentities}</span>
<span class="label {if $row.status=='normal'}label-success{else/}label-default{/if}">{if $row.status=='normal'}正常{else/}已停用{/if}</span>
<span class="label {if $row.user_type=='merchant' && $row.identity_selected}label-primary{else/}label-default{/if}">{if !$row.identity_selected}待选择用户类型{elseif $row.user_type=='merchant'/}商家用户{else/}个人用户{/if}</span>
{if !empty($masterProfile) && $masterProfile.verify_status=='pass'}
<span class="label label-warning"><i class="fa fa-wrench"></i> 认证师傅:{$masterProfile.realname|htmlentities}</span>
{/if}
{if !empty($merchantProfile) && $merchantProfile.verify_status=='pass'}
<span class="label label-primary"><i class="fa fa-building-o"></i> 关联企业:{$merchantProfile.name|htmlentities}</span>
{/if}
{if !empty($enterpriseCert)}
<span class="label label-info">企业资质:{if $enterpriseCert.verify_status=='pass'}已认证{elseif $enterpriseCert.verify_status=='pending'/}审核中{else/}未通过{/if}</span>
{/if}
</div>
<div class="ud-sub">
账号: {$row.username|htmlentities} &nbsp;|&nbsp;
@@ -66,6 +70,32 @@
</div>
</div>
{if !empty($enterpriseCert)}
<div class="ud-card">
<div class="ud-card-hd"><i class="fa fa-certificate"></i> 企业资质认证</div>
<div class="ud-card-bd">
<table class="table table-bordered table-condensed" style="margin-bottom:0;"><tbody>
<tr><th>企业名称</th><td>{$enterpriseCert.company_name|htmlentities}</td><th>营业执照号码</th><td>{$enterpriseCert.license_no|htmlentities}</td></tr>
<tr><th>法人姓名</th><td>{$enterpriseCert.legal_person|default='未填写'|htmlentities}</td><th>审核结果</th><td>{if $enterpriseCert.verify_status=='pass'}已通过{elseif $enterpriseCert.verify_status=='pending'/}待审核{else/}已驳回:{$enterpriseCert.audit_msg|htmlentities}{/if}</td></tr>
</tbody></table>
</div>
</div>
{/if}
{if $row.identity_selected && $row.user_type=='merchant'}
<div class="ud-card">
<div class="ud-card-hd"><i class="fa fa-building-o"></i> 商家用户资料</div>
<div class="ud-card-bd">
<table class="table table-bordered table-condensed" style="margin-bottom:0;">
<tbody>
<tr><th>公司名称</th><td>{$row.company_name|default='未填写'|htmlentities}</td><th>法人姓名</th><td>{$row.company_legal_person|default='未填写'|htmlentities}</td></tr>
<tr><th>法人手机号</th><td>{$row.company_legal_mobile|default='未填写'|htmlentities}</td><th>技术手机号</th><td>{$row.company_tech_mobile|default='未填写'|htmlentities}</td></tr>
</tbody>
</table>
</div>
</div>
{/if}
<div class="row">
<!-- 常用上门服务地址簿 -->
<div class="col-xs-12 col-sm-6">

查看文件

@@ -1,5 +1,11 @@
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-heading"><strong>用户列表</strong><p class="text-muted">查看个人用户、商家用户及其独立的师傅身份。</p>
<ul class="nav nav-tabs" data-field="user_type">
<li class="active"><a href="#users-all" data-value="" data-toggle="tab">全部用户</a></li>
<li><a href="#users-personal" data-value="personal" data-toggle="tab">个人用户</a></li>
<li><a href="#users-merchant" data-value="merchant" data-toggle="tab">商家用户</a></li>
</ul>
</div>
<div class="panel-body">
<div id="myTabContent" class="tab-content">

查看文件

@@ -43,6 +43,9 @@ class Auth extends Base
if (!$user) {
// 若数据库中无此手机号:直连数据库插入注册新会员
if (!preg_match('/^\S{6,30}$/', $password)) {
$this->error('登录密码须为6至30位非空字符');
}
$ret = $this->auth->register($mobile, $password, '', $mobile, []);
if (!$ret) {
$this->error($this->auth->getError() ?: '注册登录失败');
@@ -54,9 +57,10 @@ class Auth extends Base
if (empty($user['password'])) {
$this->error('该账号尚未设置登录密码,请使用微信一键登录后设置密码');
}
$encryptPassword = $this->auth->getEncryptPassword($password, $user['salt']);
if ($user['password'] !== $encryptPassword) {
$this->error('手机号或密码不正确');
try {
\app\common\library\AccountSecurity::verify((int)$user['id'], 'login', $password);
} catch (\Throwable $e) {
$this->error($e->getMessage() === '密码不正确' ? '手机号或密码不正确' : $e->getMessage());
}
$this->auth->direct($user['id']);
}
@@ -83,7 +87,7 @@ class Auth extends Base
protected function profileData()
{
$uid = $this->uid();
$user = Db::name('user')->field('id,nickname,mobile,email,avatar,money,score,user_type,contact_address,createtime')->where('id', $uid)->find();
$user = Db::name('user')->field('id,nickname,mobile,email,avatar,money,score,user_type,identity_selected,company_name,company_legal_person,company_legal_mobile,company_tech_mobile,contact_address,createtime')->where('id', $uid)->find();
$master = Db::name('master')->where('user_id', $uid)->find();
$couponCount = Db::name('user_coupon')->where('user_id', $uid)->where('status', 'unused')->count();
@@ -152,13 +156,7 @@ class Auth extends Base
'pending_verify' => $getCnt(7),
];
if ($merchantRole === 'member' && $merchant && $merchant['verify_status'] === 'pass') {
$userType = 'merchant';
} elseif (!empty($user['user_type']) && in_array($user['user_type'], ['personal', 'merchant'], true)) {
$userType = $user['user_type'];
} else {
$userType = ($merchant && $merchant['verify_status'] === 'pass') ? 'merchant' : 'personal';
}
$userType = in_array($user['user_type'], ['personal', 'merchant'], true) ? $user['user_type'] : 'personal';
return [
'id' => (int)$user['id'],
@@ -167,10 +165,11 @@ class Auth extends Base
'email' => !empty($user['email']) ? (string)$user['email'] : ($merchant && !empty($merchant['email']) ? (string)$merchant['email'] : ''),
'contact_address' => !empty($user['contact_address']) ? (string)$user['contact_address'] : ($merchant ? (string)($merchant['province'] . $merchant['city'] . $merchant['district'] . $merchant['address']) : ''),
'user_type' => $userType,
'company_name' => $merchant ? (string)$merchant['name'] : '',
'legal_person' => $merchant && isset($merchant['legal_person']) ? (string)$merchant['legal_person'] : '',
'legal_mobile' => $merchant && isset($merchant['legal_mobile']) ? (string)$merchant['legal_mobile'] : '',
'tech_mobile' => $merchant && isset($merchant['tech_mobile']) ? (string)$merchant['tech_mobile'] : '',
'identity_selected' => (bool)$user['identity_selected'],
'company_name' => $user['company_name'] !== '' ? $user['company_name'] : ($merchant ? (string)$merchant['name'] : ''),
'legal_person' => $user['company_legal_person'] !== '' ? $user['company_legal_person'] : ($merchant ? (string)($merchant['legal_person'] ?? '') : ''),
'legal_mobile' => $user['company_legal_mobile'] !== '' ? $user['company_legal_mobile'] : ($merchant ? (string)($merchant['legal_mobile'] ?? '') : ''),
'tech_mobile' => $user['company_tech_mobile'] !== '' ? $user['company_tech_mobile'] : ($merchant ? (string)($merchant['tech_mobile'] ?? '') : ''),
'avatar' => !empty($user['avatar']) ? (strpos((string)$user['avatar'], 'http') === 0 ? $user['avatar'] : cdnurl($user['avatar'], true)) : '',
'balance' => (float)$user['money'],
'coupon_count' => (int)$couponCount,
@@ -190,10 +189,14 @@ class Auth extends Base
public function saveAccount()
{
$uid = $this->uid();
$currentUserType = Db::name('user')->where('id', $uid)->value('user_type');
$userType = trim((string)$this->request->post('user_type', $currentUserType ?: 'personal'));
if (!in_array($userType, ['personal', 'merchant'], true)) {
$userType = 'personal';
$currentUser = Db::name('user')->where('id', $uid)->find();
$userType = (string)$currentUser['user_type'];
$requestedType = $this->request->post('user_type', null);
if ($requestedType !== null && $requestedType !== $userType) {
$this->error('用户类型确定后不可自行修改');
}
if (empty($currentUser['identity_selected'])) {
$this->error('请先选择用户类型');
}
$nickname = trim((string)$this->request->post('nickname', ''));
$mobile = trim((string)$this->request->post('mobile', ''));
@@ -221,19 +224,18 @@ class Auth extends Base
}
$merchantRel = $this->merchantOf($uid);
if ($userType === 'merchant') {
if (!$merchantRel || ($merchantRel['merchant']['verify_status'] ?? '') !== 'pass') {
$this->error('请先提交企业入驻申请并通过审核后再启用商家账号');
}
}
$userUpdate = [
'nickname' => $nickname,
'user_type' => $userType,
'contact_address' => $contactAddress,
'email' => $email,
'updatetime' => time(),
];
if ($userType === 'merchant') {
foreach (['company_name' => $companyName, 'company_legal_person' => $legalPerson, 'company_legal_mobile' => $legalMobile, 'company_tech_mobile' => $techMobile] as $field => $value) {
$requestField = ['company_name' => 'company_name', 'company_legal_person' => 'legal_person', 'company_legal_mobile' => 'legal_mobile', 'company_tech_mobile' => 'tech_mobile'][$field];
if ($this->request->has($requestField, 'post')) $userUpdate[$field] = $value;
}
}
if ($mobile !== '' && preg_match('/^1\d{10}$/', $mobile)) {
$conflict = Db::name('user')->where('mobile', $mobile)->where('id', '<>', $uid)->find();
if ($conflict) {
@@ -268,6 +270,22 @@ class Auth extends Base
$this->success('保存成功', ['userinfo' => $this->profileData()]);
}
/** 首次登录选择用户类型,原子更新防止重复选择。 */
public function selectIdentity()
{
$type = trim((string)$this->request->post('user_type', ''));
if (!in_array($type, ['personal', 'merchant'], true)) {
$this->error('请选择个人用户或商家用户');
}
$updated = Db::name('user')->where('id', $this->uid())->where('identity_selected', 0)->update([
'user_type' => $type, 'identity_selected' => 1, 'updatetime' => time(),
]);
if (!$updated) {
$this->error('用户类型确定后不可自行修改');
}
$this->success('选择成功', ['userinfo' => $this->profileData()]);
}
/**
* 微信授权登录(小程序 uni.login 拿到的 code)
* @ApiMethod (POST)

查看文件

@@ -35,6 +35,16 @@ class Base extends Api
return (int)$this->auth->id;
}
/** Verify the account payment password before any balance debit. */
protected function requirePaymentPassword()
{
try {
\app\common\library\AccountSecurity::verify($this->uid(), 'payment', (string)$this->request->post('payment_password', ''));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/** 验证新头像属于当前账号,且是符合限制的图片附件。 */
protected function validateAvatar($url)
{

查看文件

@@ -6,6 +6,7 @@ use app\common\library\CommissionService;
use app\common\library\FinanceConfigService;
use app\common\library\FinishImageUrls;
use app\common\library\OrderStatus;
use app\common\library\OrderQualification;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
use app\common\library\TencentVerifyService;
@@ -750,7 +751,10 @@ class Master extends Base
}
$now = time();
$qualificationCerts = OrderQualification::certificates((int)$master['id']);
$qualificationToday = date('Y-m-d');
foreach ($list as &$row) {
$row['qualification_allowed'] = OrderQualification::allows($row['qual_req'], $qualificationCerts, $qualificationToday);
unset($row['verify_code'], $row['_has_coord'], $row['_dist_km'], $row['_same_city']);
$row['appoint_text'] = $row['appoint_time'] ? date('Y-m-d H:i', (int)$row['appoint_time']) : '接单后与业主预约';
$row['pay_amount'] = (float)$row['pay_amount'];
@@ -897,6 +901,9 @@ class Master extends Base
if ((int)$order['status'] !== OrderStatus::PENDING_ACCEPT || (int)$order['master_id'] !== 0) {
$this->error('手慢了,该订单已被接走');
}
if (!OrderQualification::forMaster($order['qual_req'] ?? '', (int)$master['id'])) {
$this->error('该订单要求持有已审核通过且有效的「' . $order['qual_req'] . '」,请先上传认证证书');
}
$affected = Db::name('order')
->where('id', $orderId)
@@ -1320,6 +1327,9 @@ class Master extends Base
if ((int)$order['master_id'] > 0) {
$this->error('该订单已选定师傅');
}
if (!OrderQualification::forMaster($order['qual_req'] ?? '', (int)$master['id'])) {
$this->error('该订单要求持有已审核通过且有效的「' . $order['qual_req'] . '」,请先上传认证证书');
}
if ($amount <= 0) {
$this->error('请填写报价金额');
}
@@ -1354,6 +1364,7 @@ class Master extends Base
public function withdraw()
{
$master = $this->requireMaster();
$this->requirePaymentPassword();
$amount = round((float)$this->request->post('amount'), 2);
$wxCode = trim((string)$this->request->post('wx_code', ''));
$channel = trim((string)$this->request->post('channel', 'wechat'));
@@ -2331,6 +2342,7 @@ class Master extends Base
$estCommission = $estCalc['commission'];
$estMasterFee = $estCalc['settle_amount'];
$qualificationAllowed = OrderQualification::forMaster($order['qual_req'] ?? '', $masterId);
$data = [
'id' => (int)$order['id'],
'order_no' => $order['order_no'],
@@ -2368,6 +2380,7 @@ class Master extends Base
'express_company' => (string)($order['express_company'] ?? ''),
'goods_arrived' => (int)($order['goods_arrived'] ?? 1),
'qual_req' => (string)($order['qual_req'] ?? ''),
'qualification_allowed' => $qualificationAllowed,
'master_req' => (string)($order['master_req'] ?? ''),
'contact' => $contactDisplay,
'mobile' => $mobile,
@@ -2392,8 +2405,8 @@ class Master extends Base
'description' => $myQuote['description'],
'status' => $myQuote['status'],
] : null,
'can_grab' => ($order['price_type'] !== 'quote' && (int)$order['status'] === OrderStatus::PENDING_ACCEPT && (int)$order['master_id'] === 0 && (int)$order['user_id'] !== $this->uid()),
'can_quote' => ($order['price_type'] === 'quote' && in_array((int)$order['status'], [OrderStatus::PENDING_ACCEPT, OrderStatus::QUOTING], true) && (int)$order['master_id'] === 0 && !$myQuote && (int)$order['user_id'] !== $this->uid()),
'can_grab' => ($qualificationAllowed && $order['price_type'] !== 'quote' && (int)$order['status'] === OrderStatus::PENDING_ACCEPT && (int)$order['master_id'] === 0 && (int)$order['user_id'] !== $this->uid()),
'can_quote' => ($qualificationAllowed && $order['price_type'] === 'quote' && in_array((int)$order['status'], [OrderStatus::PENDING_ACCEPT, OrderStatus::QUOTING], true) && (int)$order['master_id'] === 0 && !$myQuote && (int)$order['user_id'] !== $this->uid()),
];
// 本人已接工单:附带完整履约节点、增项补差、完工取证、结算入账与操作轨迹
@@ -2943,7 +2956,7 @@ class Master extends Base
}
$this->success('', [
'notice' => '请上传本人真实的技能证书信息。技能证书审核通过后,才能接商家指定资质要求的订单。',
'notice' => '请上传本人真实的技能证书信息。审核通过且在有效期内的证书名称会展示给相关订单用户。',
'is_master_applied' => $master ? 1 : 0,
'verify_status' => $master ? (string)$master['verify_status'] : '',
'items' => $items,

查看文件

@@ -591,53 +591,12 @@ class Merchant extends Base
}
}
/**
* 要求已通过审核的商家
* 若当前用户为 merchant 类型但无 merchant 档案,则自动创建一条空档案兜底
* 同一 user_id 只能创建一条(user_id 唯一约束已由后台 add() 保证)
*/
/** 要求商家档案已通过审核;账号类型不代表企业资质。 */
protected function requireMerchant()
{
$m = $this->merchantInfo();
if (!$m) {
$curUser = Db::name('user')->where('id', $this->uid())->find();
if ($curUser && !empty($curUser['user_type']) && $curUser['user_type'] === 'merchant') {
// 再次确认:user_id 必须唯一,防止并发创建重复记录
$existCheck = Db::name('merchant')->where('user_id', $this->uid())->find();
if ($existCheck) {
if ($existCheck['verify_status'] !== 'pass') {
Db::name('merchant')->where('id', (int)$existCheck['id'])->update([
'verify_status' => 'pass',
'updatetime' => time(),
]);
$existCheck['verify_status'] = 'pass';
}
return $existCheck;
}
$now = time();
$newId = Db::name('merchant')->insertGetId([
'user_id' => $this->uid(),
'name' => !empty($curUser['nickname']) ? (string)$curUser['nickname'] : '商家用户',
'license_no' => null,
'contact' => (string)$curUser['nickname'],
'mobile' => (string)$curUser['mobile'],
'address' => isset($curUser['contact_address']) ? (string)$curUser['contact_address'] : '',
'email' => isset($curUser['email']) ? (string)$curUser['email'] : '',
'verify_status' => 'pass',
'createtime' => $now,
'updatetime' => $now,
]);
return Db::name('merchant')->where('id', $newId)->find();
}
$this->error('请先在「账号信息」切换为商家类型', null, 2001);
}
if ($m['verify_status'] !== 'pass') {
Db::name('merchant')->where('id', (int)$m['id'])->update([
'verify_status' => 'pass',
'updatetime' => time(),
]);
$m['verify_status'] = 'pass';
if (!$m || $m['verify_status'] !== 'pass') {
$this->error('请先完成商家资质审核', null, 2001);
}
return $m;
}

查看文件

@@ -7,6 +7,7 @@ use app\common\library\FinanceConfigService;
use app\common\library\OrderStatus;
use app\common\library\OrderServiceSnapshot;
use app\common\library\OrderPaymentResultService;
use app\common\library\MasterOrderCredentials;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
use think\Db;
@@ -640,6 +641,7 @@ class Order extends Base
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'order');
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'order', 0, $wxCode);
@@ -725,6 +727,7 @@ class Order extends Base
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'diff');
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'diff', 0, $wxCode);
@@ -1035,6 +1038,23 @@ class Order extends Base
}
}
// 一次性读取订单关联师傅的公开技能与有效证书,避免报价列表逐人查询。
$credentialMasterIds = array_column($quotes, 'master_id');
if ($master) $credentialMasterIds[] = $master['id'];
$credentialMasterIds = array_values(array_unique(array_filter(array_map('intval', $credentialMasterIds))));
if ($credentialMasterIds) {
$skillRows = Db::name('master_skill')->field('master_id,skill_name,status')
->where('master_id', 'in', $credentialMasterIds)->where('status', 'normal')->select();
$certRows = Db::name('master_cert')->field('master_id,cert_name,status,is_long_term,expire_date')
->where('master_id', 'in', $credentialMasterIds)->where('status', 'pass')->select();
$credentials = MasterOrderCredentials::project($credentialMasterIds, $skillRows, $certRows, date('Y-m-d'));
if ($master) $master = array_merge($master, $credentials[$master['id']]);
foreach ($quotes as &$quote) {
if (isset($credentials[$quote['master_id']])) $quote = array_merge($quote, $credentials[$quote['master_id']]);
}
unset($quote);
}
$creatorUser = Db::name('user')->where('id', (int)$order['user_id'])->find();
$rawCreatorMobile = (string)(($creatorUser && !empty($creatorUser['mobile'])) ? $creatorUser['mobile'] : $order['mobile']);
$maskedCreatorMobile = strlen($rawCreatorMobile) >= 7 ? substr_replace($rawCreatorMobile, '****', 3, 4) : $rawCreatorMobile;
@@ -1224,8 +1244,14 @@ class Order extends Base
$payType = trim((string)$this->request->post('pay_type', 'wechat'));
$order = $this->ownOrder($orderId, 'user');
$quoteMasterId = (int)Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->value('master_id');
if ($quoteMasterId > 0 && !\app\common\library\OrderQualification::forMaster($order['qual_req'] ?? '', $quoteMasterId)) {
$this->error('该师傅目前没有符合订单要求的有效认证证书,请选择其他师傅');
}
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'quote', $quoteId);
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'quote', $quoteId, $wxCode);

查看文件

@@ -0,0 +1,133 @@
<?php
namespace app\api\controller;
use app\common\library\AccountSecurity;
use app\common\library\WxLogin;
use app\common\library\TencentVerifyService;
use app\common\library\EnterpriseLicenseImage;
use think\Db;
class Security extends Base
{
private function verifyBoundPhone($code, $mobile)
{
if (trim((string)$code) === '') $this->error('请先验证绑定的微信手机号');
$phone = WxLogin::getPhoneNumber((string)$code);
$verified = isset($phone['purePhoneNumber']) ? (string)$phone['purePhoneNumber'] : (string)($phone['phoneNumber'] ?? '');
if (isset($phone['error']) || $verified === '' || !hash_equals((string)$mobile, $verified)) {
$this->error('手机号验证失败,请使用绑定手机号重新验证');
}
}
public function status()
{
$user = Db::name('user')->field('password,mobile')->where('id', $this->uid())->find();
$security = Db::name('user_security')->where('user_id', $this->uid())->find();
$cert = Db::name('user_enterprise_cert')->where('user_id', $this->uid())->find();
$this->success('', [
'has_login_password' => !empty($user['password']),
'has_payment_password' => $security && $security['payment_password_hash'] !== '',
'enterprise_cert' => $cert ?: null,
]);
}
public function changeLoginPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
$old = (string)$this->request->post('old_password', '');
if (!preg_match('/^\S{6,30}$/', $new)) $this->error('登录密码须为6至30位非空字符');
$user = Db::name('user')->field('password,mobile')->where('id', $uid)->find();
if (!empty($user['password'])) {
try { AccountSecurity::verify($uid, 'login', $old); } catch (\Throwable $e) { $this->error($e->getMessage()); }
$ignoreOld = false;
} else {
$this->verifyBoundPhone($this->request->post('phone_code', ''), $user['mobile']);
$ignoreOld = true;
}
if (!$this->auth->changepwd($new, $old, $ignoreOld)) $this->error($this->auth->getError() ?: '设置失败');
\app\common\library\Token::clear($uid);
$this->success('登录密码已更新,请重新登录');
}
public function setPaymentPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
try { AccountSecurity::verify($uid, 'login', (string)$this->request->post('login_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', '')->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
if (!$updated) $this->error('支付密码已设置,请使用修改功能');
$this->success('支付密码设置成功');
}
public function changePaymentPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
$oldHash = (string)Db::name('user_security')->where('user_id', $uid)->value('payment_password_hash');
try { AccountSecurity::verify($uid, 'payment', (string)$this->request->post('old_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', $oldHash)->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
if (!$updated) $this->error('支付密码已变更,请重新操作');
$this->success('支付密码修改成功');
}
public function submitEnterpriseCert()
{
$uid = $this->uid();
$name = trim((string)$this->request->post('company_name', ''));
$license = strtoupper(trim((string)$this->request->post('license_no', '')));
$image = trim((string)$this->request->post('license_image', ''));
$person = trim((string)$this->request->post('legal_person', ''));
if ($name === '' || mb_strlen($name) > 255) $this->error('请填写企业名称');
if (!preg_match('/^[A-Z0-9]{15,18}$/', $license)) $this->error('请填写正确的营业执照号码');
if (mb_strlen($person) > 100) $this->error('法人姓名过长');
$attachment = Db::name('attachment')->where('user_id', $uid)->where('url', $image)->where('category', 'cert')->find();
if (!$attachment || (int)$attachment['filesize'] > 10 * 1024 * 1024 || !in_array(strtolower((string)$attachment['mimetype']), ['image/jpeg', 'image/png', 'image/webp'], true)) {
$this->error('请上传本人营业执照图片');
}
$existing = Db::name('user_enterprise_cert')->where('user_id', $uid)->find();
$data = ['company_name' => $name, 'license_no' => $license, 'license_image' => $image,
'legal_person' => $person, 'verify_status' => 'pending', 'audit_msg' => '', 'updatetime' => time()];
if ($existing) {
if ($existing['verify_status'] !== 'reject') $this->error('已有企业资质申请,审核中或已通过');
$updated = Db::name('user_enterprise_cert')->where('id', (int)$existing['id'])->where('verify_status', 'reject')->update($data);
if (!$updated) $this->error('申请状态已变更,请刷新后重试');
} else {
$data['user_id'] = $uid;
$data['createtime'] = time();
try { Db::name('user_enterprise_cert')->insert($data); }
catch (\Throwable $e) { $this->error('提交失败,请刷新后重试'); }
}
$this->success('企业资质已提交,请等待审核');
}
public function recognizeEnterpriseLicense()
{
$image = trim((string)$this->request->post('license_image', ''));
$attachment = Db::name('attachment')->where('user_id', $this->uid())->where('url', $image)->where('category', 'cert')->find();
if (!$attachment || (int)$attachment['filesize'] > 10 * 1024 * 1024 || !in_array(strtolower((string)$attachment['mimetype']), ['image/jpeg', 'image/png', 'image/webp'], true)) {
$this->error('请上传本人营业执照图片');
}
try {
$imageBytes = EnterpriseLicenseImage::read($attachment);
} catch (\Throwable $e) {
$this->error('图片读取失败,请重新上传或手动填写');
}
try {
$reply = TencentVerifyService::request('ocr', '2018-11-19', 'BizLicenseOCR', ['ImageBase64' => base64_encode($imageBytes)]);
$data = $reply['Response'] ?? [];
if (!empty($data['Error']) || empty($data['Name']) || empty($data['RegNum'])) {
$this->error('未能识别营业执照,请重新上传或手动填写');
}
$this->success('识别成功,请核对信息', ['company_name' => (string)$data['Name'], 'license_no' => (string)$data['RegNum'], 'legal_person' => (string)($data['Person'] ?? '')]);
} catch (\think\exception\HttpResponseException $e) {
throw $e;
} catch (\Throwable $e) {
$this->error('营业执照识别暂不可用,请手动填写');
}
}
}

查看文件

@@ -212,52 +212,10 @@ class User extends Api
$this->error(__('Operation failed'), $url);
}
/**
* 重置密码
*
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="newpassword", type="string", required=true, description="新密码")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
*/
/** 密码找回暂不开放,保留旧路由返回明确提示。 */
public function resetpwd()
{
$type = $this->request->post("type", "mobile");
$mobile = $this->request->post("mobile");
$email = $this->request->post("email");
$newpassword = $this->request->post("newpassword");
$captcha = $this->request->post("captcha");
if (!$newpassword || !$captcha) {
$this->error(__('Invalid parameters'));
}
//验证Token
if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
$this->error(__('Password must be 6 to 30 characters'));
}
if ($type == 'mobile') {
$this->error('短信验证码通道已移除,暂不支持手机短信找回密码');
} else {
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
$user = \app\common\model\User::getByEmail($email);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Ems::check($email, $captcha, 'resetpwd', true);
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Ems::flush($email, 'resetpwd');
}
//模拟一次登录
$this->auth->direct($user->id);
$ret = $this->auth->changepwd($newpassword, '', true);
if ($ret) {
$this->success(__('Reset password successful'));
} else {
$this->error($this->auth->getError());
}
$this->error('暂不支持找回密码');
}
/**

查看文件

@@ -0,0 +1,56 @@
<?php
namespace app\common\library;
use think\Db;
/** Shared account credential verification and per-account throttling. */
class AccountSecurity
{
public static function ensure($uid)
{
$prefix = config('database.prefix');
if (!preg_match('/^[A-Za-z0-9_]+$/', $prefix)) {
throw new \RuntimeException('数据库配置错误');
}
Db::execute("INSERT IGNORE INTO `{$prefix}user_security` (`user_id`) VALUES (?)", [(int)$uid]);
}
public static function verify($uid, $kind, $password)
{
if (!in_array($kind, ['login', 'payment'], true)) {
throw new \InvalidArgumentException('验证类型错误');
}
$attemptsField = $kind === 'payment' ? 'payment_failed_attempts' : 'failed_attempts';
$lockedField = $kind === 'payment' ? 'payment_locked_until' : 'locked_until';
self::ensure($uid);
Db::startTrans();
try {
$row = Db::name('user_security')->where('user_id', (int)$uid)->lock(true)->find();
if ((int)$row[$lockedField] > time()) {
throw new \RuntimeException('密码错误次数过多,请15分钟后重试');
}
if ($kind === 'login') {
$user = Db::name('user')->field('password,salt')->where('id', (int)$uid)->find();
$correct = $user && $user['password'] !== '' && hash_equals((string)$user['password'], md5(md5($password) . $user['salt']));
} elseif ($kind === 'payment') {
if ($row['payment_password_hash'] === '') {
throw new \RuntimeException('请先在账号安全中设置支付密码');
}
$correct = password_verify($password, $row['payment_password_hash']);
}
$failures = $correct ? 0 : (int)$row[$attemptsField] + 1;
Db::name('user_security')->where('user_id', (int)$uid)->update([
$attemptsField => $failures >= 5 ? 0 : $failures,
$lockedField => $failures >= 5 ? time() + 900 : 0,
]);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
if (!$correct) {
throw new \RuntimeException($failures >= 5 ? '密码错误次数过多,请15分钟后重试' : '密码不正确');
}
return true;
}
}

查看文件

@@ -221,14 +221,10 @@ class Auth
return false;
}
if ($user->loginfailure >= 10 && time() - $user->loginfailuretime < 86400) {
$this->setError('Please try again after 1 day');
return false;
}
if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
$user->save(['loginfailure' => $user->loginfailure + 1, 'loginfailuretime' => time()]);
$this->setError('Password is incorrect');
try {
AccountSecurity::verify((int)$user->id, 'login', $password);
} catch (\RuntimeException $e) {
$this->setError($e->getMessage() === '密码不正确' ? 'Password is incorrect' : $e->getMessage());
return false;
}

查看文件

@@ -0,0 +1,44 @@
<?php
namespace app\common\library;
use think\Loader;
/** Reads an already-authorized attachment without accepting a caller-supplied remote URL. */
class EnterpriseLicenseImage
{
public static function read(array $attachment)
{
$url = (string)($attachment['url'] ?? '');
$size = (int)($attachment['filesize'] ?? 0);
if ($url === '' || $url[0] !== '/' || $size <= 0 || $size > 10 * 1024 * 1024) {
throw new \RuntimeException('营业执照图片无效');
}
if (($attachment['storage'] ?? '') === 'cos') {
$config = get_addon_config('cos');
if (!$config || empty($config['bucket']) || empty($config['region']) || empty($config['secretId']) || empty($config['secretKey'])) {
throw new \RuntimeException('云存储未配置');
}
Loader::addNamespace('Qcloud\\Cos', ROOT_PATH . 'addons/cos/library/Qcloud/Cos/');
$client = new \Qcloud\Cos\Client([
'region' => $config['region'], 'schema' => 'https',
'credentials' => ['secretId' => $config['secretId'], 'secretKey' => $config['secretKey']],
]);
$result = $client->getObject(['Bucket' => $config['bucket'], 'Key' => ltrim($url, '/'), 'Range' => 'bytes=0-10485760']);
$bytes = (string)$result['Body'];
} elseif (($attachment['storage'] ?? '') === 'local') {
$root = realpath(ROOT_PATH . 'public');
$file = realpath(ROOT_PATH . 'public' . $url);
if (!$root || !$file || strpos($file, $root . DIRECTORY_SEPARATOR) !== 0 || !is_file($file) || !is_readable($file)) {
throw new \RuntimeException('营业执照图片不存在');
}
if (filesize($file) > 10 * 1024 * 1024) throw new \RuntimeException('营业执照图片过大');
$bytes = file_get_contents($file);
} else {
throw new \RuntimeException('不支持的图片存储类型');
}
if (!is_string($bytes) || $bytes === '' || strlen($bytes) > 10 * 1024 * 1024) {
throw new \RuntimeException('营业执照图片读取失败');
}
return $bytes;
}
}

查看文件

@@ -0,0 +1,29 @@
<?php
namespace app\common\library;
class MasterOrderCredentials
{
public static function project(array $masterIds, array $skills, array $certificates, $today)
{
$result = [];
foreach ($masterIds as $id) {
if ((int)$id > 0) $result[(int)$id] = ['skills' => [], 'certificates' => []];
}
foreach ($skills as $row) {
$id = (int)$row['master_id'];
$name = trim((string)$row['skill_name']);
if (isset($result[$id]) && $row['status'] === 'normal' && $name !== '' && !in_array($name, $result[$id]['skills'], true)) {
$result[$id]['skills'][] = $name;
}
}
foreach ($certificates as $row) {
$id = (int)$row['master_id'];
$name = trim((string)$row['cert_name']);
$valid = (int)$row['is_long_term'] === 1 || (!empty($row['expire_date']) && $row['expire_date'] >= $today);
if (isset($result[$id]) && $row['status'] === 'pass' && $valid && $name !== '' && !in_array($name, $result[$id]['certificates'], true)) {
$result[$id]['certificates'][] = $name;
}
}
return $result;
}
}

查看文件

@@ -0,0 +1,31 @@
<?php
namespace app\common\library;
use think\Db;
class OrderQualification
{
public static function certificates($masterId)
{
return Db::name('master_cert')->field('cert_name,cert_code,is_custom,status,is_long_term,expire_date')
->where('master_id', (int)$masterId)->where('status', 'pass')->select();
}
public static function allows($requirement, array $certificates, $today)
{
$requirement = trim((string)$requirement);
if ($requirement === '') return true;
foreach ($certificates as $cert) {
if ((string)$cert['status'] !== 'pass' || (int)$cert['is_custom'] !== 0 || (string)$cert['cert_code'] === 'other') continue;
if (trim((string)$cert['cert_name']) !== $requirement) continue;
if ((int)$cert['is_long_term'] === 1 || (!empty($cert['expire_date']) && $cert['expire_date'] >= $today)) return true;
}
return false;
}
public static function forMaster($requirement, $masterId)
{
if (trim((string)$requirement) === '') return true;
return self::allows($requirement, self::certificates($masterId), date('Y-m-d'));
}
}

查看文件

@@ -15,7 +15,6 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
});
var table = $("#table");
table.on('post-body.bs.table', function () {
$(".btn-detail-mer", this).data("area", ["1040px", "88%"]);
$(".btn-editone", this).data("area", ["920px", "85%"]);
@@ -86,6 +85,43 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
Table.api.bindevent(table);
},
certificates: function () {
var certsTable = $("#certs-table");
function auditCert(row, decision, reason) {
Fast.api.ajax({url: 'merchant/index', type: 'POST', data: {
view: 'audit_cert', id: row.id, decision: decision, audit_msg: reason || '',
__token__: $('#cert-audit-token input[name="__token__"]').val()
}}, function () { location.reload(); });
}
certsTable.bootstrapTable({
url: 'merchant/index?view=certs', pk: 'id', toolbar: '#certs-toolbar',
search: true, searchOnEnterKey: true, searchPlaceholder: '搜索企业名称、证照号码或手机号',
commonSearch: false, showExport: false, pagination: true, pageList: [10, 20, 50, 100], sidePagination: 'server', escape: true,
responseHandler: function (res) {
if (!res || !Array.isArray(res.rows)) { Toastr.error((res && res.msg) || '企业资质列表加载失败'); return {total: 0, rows: []}; }
return res;
},
columns: [[
{field: 'id', title: '申请编号', operate: false},
{field: 'nickname', title: '用户昵称', operate: false},
{field: 'mobile', title: '手机号', operate: false},
{field: 'user_type', title: '用户类型', operate: false, formatter: function (v) { return v === 'merchant' ? '商家用户' : '个人用户'; }},
{field: 'company_name', title: '企业名称', operate: false},
{field: 'license_no', title: '营业执照号码', operate: false},
{field: 'legal_person', title: '法人姓名', operate: false},
{field: 'license_url', title: '营业执照', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
{field: 'verify_status', title: '审核状态', operate: false, formatter: function (v) { return {pending: '待审核', pass: '已通过', reject: '已驳回'}[v] || ''; }},
{field: 'audit_msg', title: '驳回原因', operate: false},
{field: 'createtime', title: '提交时间', operate: false, formatter: Table.api.formatter.datetime},
{field: 'operate', title: '操作', operate: false, events: {
'click .cert-approve': function (e, value, row) { Layer.confirm('确认通过该企业资质认证?', function () { auditCert(row, 'pass', ''); }); },
'click .cert-reject': function (e, value, row) { Layer.prompt({title: '请输入驳回原因', formType: 2}, function (reason) { auditCert(row, 'reject', reason); }); }
}, formatter: function (value, row) { return row.verify_status === 'pending' && certsTable.data('operate-audit') ? '<a href="javascript:;" class="btn btn-xs btn-success cert-approve">通过</a> <a href="javascript:;" class="btn btn-xs btn-danger cert-reject">驳回</a>' : ''; }}
]]
});
$('#certs-refresh').on('click', function () { certsTable.bootstrapTable('refresh'); });
},
add: function () {
Controller.api.bindevent();
},

查看文件

@@ -39,6 +39,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
{field: 'username', title: __('Username'), operate: 'LIKE'},
{field: 'id', title: 'ID', operate: false, visible: false},
{field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
{field: 'user_type', title: '用户类型', searchList: {personal: '个人用户', merchant: '商家用户'}, formatter: function (value, row) { return !Number(row.identity_selected) ? '待选择' : (value === 'merchant' ? '商家用户' : '个人用户'); }},
{
field: 'role_badges',
title: '平台身份角色',
@@ -49,8 +50,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
return '—';
}
return val.map(function (b) {
var cls = b.type === 'master' ? 'warning' : (b.type === 'merchant' ? 'primary' : (b.type === 'member' ? 'info' : 'default'));
return '<span class="label label-' + cls + '" style="margin-right:4px;">' + b.label + '</span>';
var cls = b.type === 'master' ? 'warning' : (b.type === 'merchant' || b.type === 'merchant_user' ? 'primary' : (b.type === 'member' ? 'info' : 'default'));
return '<span class="label label-' + cls + '" style="margin-right:4px;">' + $('<div>').text(b.label).html() + '</span>';
}).join('');
}
},

查看文件

@@ -0,0 +1,123 @@
const assert = require('assert');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const config = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0];
const get = key => (config.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim();
const mysql = process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe';
function sql(query) { return execFileSync(mysql, ['-h', get('hostname'), '-P', get('hostport'), '-u', get('username'), '-D', get('database'), '-N', '-e', query], { encoding: 'utf8', env: { ...process.env, MYSQL_PWD: get('password') } }).trim(); }
function api(route, data, token) { return new Promise((resolve, reject) => {
const req = http.request((process.env.API_BASE || 'http://yjyf:9560/api') + route, { method: data ? 'POST' : 'GET', headers: { ...(token ? { token } : {}), ...(data ? { 'content-type': 'application/x-www-form-urlencoded' } : {}) } }, res => {
let body = ''; res.setEncoding('utf8'); res.on('data', chunk => body += chunk); res.on('end', () => { try { resolve(JSON.parse(body)); } catch (err) { reject(err); } });
}); req.on('error', reject); req.end(data ? new URLSearchParams(data).toString() : undefined);
}); }
(async () => {
let mobile;
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
let uid = 0, orderId = 0;
try {
const login = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.strictEqual(login.code, 1, login.msg); uid = login.data.userinfo.id;
const token = login.data.token;
let denied = await api('/security/resetPassword', { kind: 'login', new_password: 'BadReset123!' }, token);
assert.notStrictEqual(denied.code, 1, 'password recovery must be disabled');
denied = await api('/user/resetpwd', { type: 'email', email: 'test@example.invalid', newpassword: 'BadReset123!', captcha: '000000' });
assert.notStrictEqual(denied.code, 1, 'legacy email password recovery must be disabled');
assert.match(denied.msg, /暂不支持/);
const choice = await api('/auth/selectIdentity', { user_type: 'personal' }, token);
assert.strictEqual(choice.code, 1, choice.msg);
const status = await api('/security/status', null, token);
assert.strictEqual(status.code, 1, status.msg);
assert.strictEqual(status.data.has_login_password, true);
assert.strictEqual(status.data.has_payment_password, false);
let r = await api('/security/changeLoginPassword', { old_password: 'wrong', new_password: 'Changed123!' }, token);
assert.notStrictEqual(r.code, 1, 'wrong old login password must fail');
r = await api('/security/changeLoginPassword', { old_password: 'Initial123!', new_password: 'Changed123!' }, token);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/security/status', null, token);
assert.notStrictEqual(r.code, 1, 'password change invalidates prior login sessions');
r = await api('/auth/login', { mobile, password: 'Changed123!' });
assert.strictEqual(r.code, 1, r.msg);
const newToken = r.data.token;
r = await api('/security/recognizeEnterpriseLicense', { license_image: '/not-owned.png' }, newToken);
assert.notStrictEqual(r.code, 1, 'OCR must reject images not owned by the caller');
sql(`INSERT INTO fa_order (order_no,user_id,status,pay_status,pay_amount,total_amount,createtime) VALUES ('SEC${uid}',${uid},0,0,1,1,UNIX_TIMESTAMP())`);
orderId = Number(sql(`SELECT id FROM fa_order WHERE order_no='SEC${uid}' AND user_id=${uid}`));
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance' }, newToken);
assert.notStrictEqual(r.code, 1, 'balance payment requires a payment password');
assert.match(r.msg, /支付密码/);
r = await api('/security/submitEnterpriseCert', { company_name: 'Example Company', license_no: '123456789012345678', license_image: '/not-owned.png' }, newToken);
assert.notStrictEqual(r.code, 1, 'enterprise certificate image must belong to account');
const testImage = `/uploads/test-enterprise-${uid}.png`;
sql(`INSERT INTO fa_attachment (user_id,category,filename,url,filesize,mimetype,uploadtime,storage) VALUES (${uid},'cert','test.png','${testImage}',10,'image/png',UNIX_TIMESTAMP(),'local')`);
r = await api('/security/submitEnterpriseCert', { company_name: 'Example Company', license_no: '123456789012345678', license_image: testImage }, newToken);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/security/status', null, newToken);
assert.strictEqual(r.data.enterprise_cert.verify_status, 'pending');
r = await api('/auth/profile', null, newToken);
assert.strictEqual(r.data.user_type, 'personal', 'enterprise certification must not change user type');
r = await api('/security/setPaymentPassword', { login_password: 'wrong', new_password: '123456' }, newToken);
assert.notStrictEqual(r.code, 1);
r = await api('/security/setPaymentPassword', { login_password: 'Changed123!', new_password: '123456' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1, 'wrong payment password cannot debit balance');
assert.match(r.msg, /密码/);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '123456' }, newToken);
assert.notStrictEqual(r.code, 1, 'test user has no balance');
assert.match(r.msg, /余额不足/);
r = await api('/security/setPaymentPassword', { login_password: 'Changed123!', new_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'payment password cannot be reset without old password');
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1);
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '654321' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
sql(`INSERT INTO fa_master (user_id,realname,mobile,verify_status,work_status) VALUES (${uid},'Security Test','${mobile}','pass','off')`);
const testMasterId = Number(sql(`SELECT id FROM fa_master WHERE user_id=${uid}`));
sql(`UPDATE fa_order SET master_id=${testMasterId} WHERE id=${orderId} AND user_id=${uid}`);
sql(`UPDATE fa_user SET money=10 WHERE id=${uid}`);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1, 'incorrect payment password cannot pay a funded order');
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 10);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '654321' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
assert.strictEqual(r.data.paid, true);
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 9);
assert.strictEqual(Number(sql(`SELECT pay_status FROM fa_order WHERE id=${orderId}`)), 1);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'order cannot be paid twice');
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 9);
r = await api('/master/withdraw', { amount: '0', channel: 'bank', account: 'test', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1);
assert.match(r.msg, /密码/, 'withdraw rejects wrong payment password before any financial action');
r = await api('/master/withdraw', { amount: '0', channel: 'bank', account: 'test', payment_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'zero-amount withdrawal must fail business validation');
assert.doesNotMatch(r.msg, /密码/, 'correct payment password reaches withdrawal validation');
r = await api('/auth/profile', null, newToken);
assert.strictEqual(r.data.user_type, 'personal');
assert.strictEqual(r.data.master.verify_status, 'pass');
r = await api('/security/status', null, newToken);
assert.strictEqual(r.data.has_payment_password, true);
for (let i = 0; i < 5; i++) {
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, newToken);
assert.notStrictEqual(r.code, 1);
}
r = await api('/security/changePaymentPassword', { old_password: '654321', new_password: '111111' }, newToken);
assert.notStrictEqual(r.code, 1, 'payment password remains locked after repeated failures');
assert.match(r.msg, /15分钟/);
console.log('account security API tests passed');
} finally {
if (uid) sql(`DELETE FROM fa_master WHERE user_id=${Number(uid)} AND realname='Security Test'`);
if (orderId) {
sql(`DELETE FROM fa_wallet_log WHERE order_id=${orderId} AND user_id=${Number(uid)} AND user_type='user'`);
sql(`DELETE FROM fa_pay_order WHERE order_id=${orderId} AND user_id=${Number(uid)}`);
sql(`DELETE FROM fa_order_log WHERE order_id=${orderId}`);
sql(`DELETE FROM fa_order WHERE id=${orderId} AND user_id=${Number(uid)}`);
}
if (uid && sql("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='fa_user_enterprise_cert'") === '1') sql(`DELETE FROM fa_user_enterprise_cert WHERE user_id=${Number(uid)}`);
if (uid) sql(`DELETE FROM fa_attachment WHERE user_id=${Number(uid)} AND url='/uploads/test-enterprise-${Number(uid)}.png'`);
if (uid && sql("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='fa_user_security'") === '1') sql(`DELETE FROM fa_user_security WHERE user_id=${Number(uid)}`);
sql(`DELETE FROM fa_user WHERE mobile='${mobile}' AND username='${mobile}'`);
}
})().catch(e => { console.error(e); process.exitCode = 1; });

查看文件

@@ -0,0 +1,60 @@
const assert = require('assert');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const config = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0];
const get = key => (config.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim();
const mysql = process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe';
function sql(query) { return execFileSync(mysql, ['-h', get('hostname'), '-P', get('hostport'), '-u', get('username'), '-D', get('database'), '-N', '-e', query], { encoding: 'utf8', env: { ...process.env, MYSQL_PWD: get('password') } }).trim(); }
function api(route, data, token) { return new Promise((resolve, reject) => {
const req = http.request((process.env.API_BASE || 'http://yjyf:9560/api') + route, { method: 'POST', headers: { ...(token ? { token } : {}), 'content-type': 'application/x-www-form-urlencoded' } }, res => {
let body = ''; res.setEncoding('utf8'); res.on('data', chunk => body += chunk); res.on('end', () => { try { resolve(JSON.parse(body)); } catch (err) { reject(err); } });
}); req.on('error', reject); req.end(new URLSearchParams(data).toString());
}); }
(async () => {
let mobile;
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
let uid = 0;
try {
let r = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.strictEqual(r.code, 1, r.msg); uid = Number(r.data.userinfo.id); const token = r.data.token;
r = await api('/security/setPaymentPassword', { login_password: 'Initial123!', new_password: '123456' }, token);
assert.strictEqual(r.code, 1, r.msg);
for (let i = 0; i < 4; i++) {
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, token);
assert.notStrictEqual(r.code, 1);
r = await api('/security/setPaymentPassword', { login_password: 'Initial123!', new_password: '111111' }, token);
assert.notStrictEqual(r.code, 1);
}
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, token);
assert.match(r.msg, /15分钟/, 'successful login verification must not reset payment failures');
r = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.strictEqual(r.code, 1, 'payment lock must not prevent login');
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '111111' }, token);
assert.match(r.msg, /15分钟/, 'correct payment password remains locked');
sql(`UPDATE fa_user_security SET payment_failed_attempts=0,payment_locked_until=0 WHERE user_id=${uid}`);
r = await api('/user/login', { account: mobile, password: 'Initial123!' });
assert.strictEqual(r.code, 1, 'legacy login still works with a correct password');
for (let i = 0; i < 5; i++) await api('/auth/login', { mobile, password: 'wrong' });
r = await api('/user/login', { account: mobile, password: 'Initial123!' });
assert.notStrictEqual(r.code, 1, 'legacy login must honor the login lock');
assert.match(r.msg, /15分钟/);
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '654321' }, token);
assert.strictEqual(r.code, 1, 'login lock must not prevent payment password verification');
r = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.match(r.msg, /15分钟/, 'payment verification must not reset the login lock');
sql(`UPDATE fa_user_security SET failed_attempts=0,locked_until=0 WHERE user_id=${uid}`);
for (let i = 0; i < 5; i++) await api('/user/login', { account: mobile, password: 'wrong' });
r = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.notStrictEqual(r.code, 1, 'legacy login failures must lock the main login');
assert.match(r.msg, /15分钟/);
console.log('account security lockout integration passed');
} finally {
if (uid) {
sql(`DELETE FROM fa_user_token WHERE user_id=${uid}`);
sql(`DELETE FROM fa_user_security WHERE user_id=${uid}`);
sql(`DELETE FROM fa_user WHERE id=${uid} AND mobile='${mobile}'`);
}
}
})().catch(e => { console.error(e); process.exitCode = 1; });

查看文件

@@ -0,0 +1,59 @@
const assert = require('assert');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const db = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0];
const setting = key => (db.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim();
function sql(query) { return execFileSync(process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe', ['-h', setting('hostname'), '-P', setting('hostport'), '-u', setting('username'), '-D', setting('database'), '-N', '-e', query], { encoding: 'utf8', env: {...process.env, MYSQL_PWD: setting('password')} }).trim(); }
const host = process.env.TEST_HOST || 'http://yjyf:9560';
let cookie = '';
function request(route, data, token, html) { return new Promise((resolve, reject) => {
const body = data ? new URLSearchParams(data).toString() : undefined;
const headers = { ...(!html ? {'X-Requested-With': 'XMLHttpRequest'} : {}), ...(cookie ? {cookie} : {}), ...(token ? {token} : {}), ...(body ? {'content-type': 'application/x-www-form-urlencoded'} : {}) };
const req = http.request(host + route, { method: body ? 'POST' : 'GET', headers }, res => {
if (res.headers['set-cookie']) cookie = res.headers['set-cookie'].map(s => s.split(';')[0]).join('; ');
let text = ''; res.setEncoding('utf8'); res.on('data', x => text += x); res.on('end', () => resolve({status: res.statusCode, text}));
}); req.on('error', reject); req.end(body);
}); }
(async () => {
if (!process.env.TEST_ADMIN_PASSWORD) throw new Error('Set TEST_ADMIN_PASSWORD for local admin integration test');
let mobile, uid = 0, certId = 0;
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
try {
let response = await request('/api/auth/login', {mobile, password: 'TestPassword123!'});
let result = JSON.parse(response.text); assert.strictEqual(result.code, 1, result.msg); uid = Number(result.data.userinfo.id); const token = result.data.token;
result = JSON.parse((await request('/api/auth/selectIdentity', {user_type:'personal'}, token)).text); assert.strictEqual(result.code, 1, result.msg);
const image = `/uploads/test-enterprise-${uid}.png`;
sql(`INSERT INTO fa_attachment (user_id,category,filename,url,filesize,mimetype,uploadtime,storage) VALUES (${uid},'cert','test.png','${image}',10,'image/png',UNIX_TIMESTAMP(),'local')`);
result = JSON.parse((await request('/api/security/submitEnterpriseCert', {company_name:'Security Test Company',license_no:'123456789012345678',license_image:image}, token)).text); assert.strictEqual(result.code, 1, result.msg);
certId = Number(sql(`SELECT id FROM fa_user_enterprise_cert WHERE user_id=${uid}`));
response = await request('/s.php/index/login', null, null, true);
let csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf, 'admin login CSRF');
result = JSON.parse((await request('/s.php/index/login', {username: process.env.TEST_ADMIN_USER || 'admin', password: process.env.TEST_ADMIN_PASSWORD, __token__: csrf})).text); assert.strictEqual(result.code, 1, result.msg);
// Unselected accounts have a default user_type but must not appear under personal users.
sql(`UPDATE fa_user SET identity_selected=0 WHERE id=${uid}`);
response = await request('/s.php/user/user/index?filter=' + encodeURIComponent(JSON.stringify({user_type:'personal'})) + '&op=' + encodeURIComponent(JSON.stringify({user_type:'='})) + '&limit=1000');
result = JSON.parse(response.text); assert.ok(!result.rows.some(row => Number(row.id) === uid), 'unselected user excluded from personal filter');
sql(`UPDATE fa_user SET identity_selected=1 WHERE id=${uid}`);
response = await request('/s.php/merchant/index?view=certs&offset=0&limit=100'); assert.strictEqual(response.status, 200);
result = JSON.parse(response.text); assert.ok(result.rows.some(row => Number(row.id) === certId && row.user_type === 'personal'), 'personal user certification appears in admin');
// A normal page request yields the same CSRF token the audit form uses.
response = await request('/s.php/merchant/certificates', null, null, true);
assert.strictEqual(response.status, 200); assert.ok(response.text.includes('企业资质认证')); assert.ok(!response.text.includes('商家用户</a>'));
csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf, 'audit CSRF');
result = JSON.parse((await request('/s.php/merchant/index', {view:'audit_cert', id:certId, decision:'reject', audit_msg:'Test rejection', __token__:csrf})).text); assert.strictEqual(result.code, 1, result.msg);
result = JSON.parse((await request('/api/security/status', null, token)).text); assert.strictEqual(result.data.enterprise_cert.verify_status, 'reject');
assert.strictEqual(result.data.enterprise_cert.audit_msg, 'Test rejection');
result = JSON.parse((await request('/api/security/submitEnterpriseCert', {company_name:'Security Test Company',license_no:'123456789012345678',license_image:image}, token)).text); assert.strictEqual(result.code, 1, result.msg);
response = await request('/s.php/merchant/certificates', null, null, true);
assert.strictEqual(response.status, 200); assert.ok(response.text.includes('企业资质认证')); assert.ok(!response.text.includes('商家用户</a>'));
csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf);
result = JSON.parse((await request('/s.php/merchant/index', {view:'audit_cert', id:certId, decision:'pass', __token__:csrf})).text); assert.strictEqual(result.code, 1, result.msg);
result = JSON.parse((await request('/api/security/status', null, token)).text); assert.strictEqual(result.data.enterprise_cert.verify_status, 'pass');
result = JSON.parse((await request('/api/auth/profile', null, token)).text); assert.strictEqual(result.data.user_type, 'personal'); assert.strictEqual(result.data.is_merchant, false);
console.log('enterprise certification admin integration passed');
} finally {
if (uid) { sql(`DELETE FROM fa_user_security WHERE user_id=${uid}`); sql(`DELETE FROM fa_user_enterprise_cert WHERE user_id=${uid}`); sql(`DELETE FROM fa_attachment WHERE user_id=${uid} AND url='/uploads/test-enterprise-${uid}.png'`); sql(`DELETE FROM fa_user WHERE id=${uid} AND mobile='${mobile}'`); }
}
})().catch(e => { console.error(e); process.exitCode = 1; });

查看文件

@@ -0,0 +1,18 @@
<?php
// Integration test: one synthetic image in a unique COS key, removed in finally.
define('APP_PATH', __DIR__ . '/../server/application/');
require __DIR__ . '/../server/thinkphp/base.php';
\think\App::initCommon();
\think\Loader::addNamespace('Qcloud\\Cos', ROOT_PATH . 'addons/cos/library/Qcloud/Cos/');
$config = get_addon_config('cos');
$client = new \Qcloud\Cos\Client(['region'=>$config['region'], 'schema'=>'https', 'credentials'=>['secretId'=>$config['secretId'], 'secretKey'=>$config['secretKey']]]);
$key = 'cert/u999999999/codex-test-' . bin2hex(random_bytes(12)) . '.png';
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+cZ7kAAAAASUVORK5CYII=');
try {
$client->putObject(['Bucket'=>$config['bucket'], 'Key'=>$key, 'Body'=>$bytes]);
$result = \app\common\library\EnterpriseLicenseImage::read(['storage'=>'cos', 'url'=>'/' . $key, 'filesize'=>strlen($bytes)]);
if (!hash_equals(hash('sha256', $bytes), hash('sha256', $result))) throw new \RuntimeException('COS image content mismatch');
echo "COS enterprise image integration passed\n";
} finally {
$client->deleteObject(['Bucket'=>$config['bucket'], 'Key'=>$key]);
}

查看文件

@@ -0,0 +1,30 @@
<?php
$file = __DIR__ . '/../server/application/common/library/MasterOrderCredentials.php';
if (is_file($file)) require $file;
if (!class_exists('app\\common\\library\\MasterOrderCredentials')) {
fwrite(STDERR, "FAIL: order credential projection is missing\n");
exit(1);
}
use app\common\library\MasterOrderCredentials;
$skills = [
['master_id' => 1, 'skill_name' => '家具安装', 'status' => 'normal'],
['master_id' => 1, 'skill_name' => '家具安装', 'status' => 'normal'],
['master_id' => 1, 'skill_name' => '已停用', 'status' => 'hidden'],
['master_id' => 2, 'skill_name' => '卫浴安装', 'status' => 'normal'],
];
$certs = [
['master_id' => 1, 'cert_name' => '电工证', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => '2026-11-21'],
['master_id' => 1, 'cert_name' => '长期证', 'status' => 'pass', 'is_long_term' => 1, 'expire_date' => null],
['master_id' => 1, 'cert_name' => '过期证', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => '2026-11-20'],
['master_id' => 1, 'cert_name' => '待审证', 'status' => 'pending', 'is_long_term' => 1, 'expire_date' => null],
['master_id' => 2, 'cert_name' => '驳回证', 'status' => 'reject', 'is_long_term' => 1, 'expire_date' => null],
['master_id' => 2, 'cert_name' => '缺少期限', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => null],
];
$actual = MasterOrderCredentials::project([1, 2, 3], $skills, $certs, '2026-11-21');
$expected = [
1 => ['skills' => ['家具安装'], 'certificates' => ['电工证', '长期证']],
2 => ['skills' => ['卫浴安装'], 'certificates' => []],
3 => ['skills' => [], 'certificates' => []],
];
if ($actual !== $expected) throw new RuntimeException(var_export($actual, true));
echo "Master order credentials passed\n";

查看文件

@@ -0,0 +1,19 @@
<?php
$file = __DIR__ . '/../server/application/common/library/OrderQualification.php';
if (is_file($file)) require $file;
if (!class_exists('app\\common\\library\\OrderQualification')) { fwrite(STDERR, "FAIL: qualification policy missing\n"); exit(1); }
use app\common\library\OrderQualification;
$today = '2026-11-21';
$base = ['cert_name' => '电工证', 'cert_code' => 'electrician', 'is_custom' => 0, 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => $today];
function checkResult($expected, $actual, $name) { if ($actual !== $expected) throw new RuntimeException($name . ': ' . var_export($actual, true)); }
checkResult(true, OrderQualification::allows('', [], $today), 'no requirement');
checkResult(true, OrderQualification::allows('电工证', [$base], $today), 'valid through expiry date');
checkResult(false, OrderQualification::allows('焊工证', [$base], $today), 'different type');
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'pending'])], $today), 'pending');
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'reject'])], $today), 'rejected');
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['expire_date' => '2026-11-20'])], $today), 'expired');
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['expire_date' => null])], $today), 'missing expiry');
checkResult(true, OrderQualification::allows('电工证', [array_merge($base, ['is_long_term' => 1, 'expire_date' => null])], $today), 'long term');
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['is_custom' => 1, 'cert_code' => 'other'])], $today), 'custom not standard');
checkResult(true, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'reject']), $base], $today), 'one valid certificate');
echo "Order qualification tests passed\n";

查看文件

@@ -0,0 +1,50 @@
<?php
namespace app\api\controller {
class Base {
public $request;
protected function requireMaster() { return ['id' => 5, 'work_status' => 'on']; }
protected function uid() { return 7; }
protected function error($message) { throw new \RuntimeException($message); }
}
}
namespace think {
class Db {
public static $order;
public static $certs = [];
public static function name($name) { return new Query($name); }
}
class Query {
private $table;
public function __construct($table) { $this->table = $table; }
public function where(...$args) { return $this; }
public function field(...$args) { return $this; }
public function find() { return $this->table === 'order' ? Db::$order : null; }
public function select() { return Db::$certs; }
public function update($values) { throw new \RuntimeException('REACHED_GRAB_UPDATE'); }
public function insert($values) { throw new \RuntimeException('REACHED_QUOTE_INSERT'); }
}
}
namespace {
require __DIR__ . '/../server/application/common/library/OrderStatus.php';
require __DIR__ . '/../server/application/common/library/OrderQualification.php';
require __DIR__ . '/../server/application/api/controller/Master.php';
class RequestStub { public function post($key, $default = null) { return ['order_id' => 12, 'amount' => 100][$key] ?? $default; } }
$api = new \app\api\controller\Master();
$api->request = new RequestStub();
$base = ['id' => 12, 'user_id' => 8, 'master_id' => 0, 'status' => \app\common\library\OrderStatus::PENDING_ACCEPT, 'qual_req' => '电工证'];
function expectResult($api, $method, $expected) {
try { $api->$method(); throw new \RuntimeException('unexpected success'); }
catch (\RuntimeException $e) { if (strpos($e->getMessage(), $expected) === false) throw $e; }
}
foreach (['grab' => 'fixed', 'quote' => 'quote'] as $method => $type) {
\think\Db::$order = $base + ['price_type' => $type];
\think\Db::$certs = [];
expectResult($api, $method, '请先上传认证证书');
\think\Db::$certs = [['cert_name'=>'电工证', 'cert_code'=>'electrician', 'is_custom'=>0, 'status'=>'pass', 'is_long_term'=>1, 'expire_date'=>null]];
expectResult($api, $method, $method === 'grab' ? 'REACHED_GRAB_UPDATE' : 'REACHED_QUOTE_INSERT');
\think\Db::$order['qual_req'] = '';
\think\Db::$certs = [];
expectResult($api, $method, $method === 'grab' ? 'REACHED_GRAB_UPDATE' : 'REACHED_QUOTE_INSERT');
}
echo "Order qualification endpoint checks passed\n";
}

查看文件

@@ -0,0 +1,31 @@
import assert from 'assert';
import { beginPaymentSetup, finishPaymentSetup } from '../yjyf-app/utils/payment-setup.mjs';
function device(confirmed = true, fail = false) {
const events = [];
return { events, api: {
showModal(options) { events.push(['prompt', options.title]); options.success({confirm: confirmed}); },
navigateTo(options) { events.push(['navigateTo', options.url]); fail ? options.fail() : options.success(); },
redirectTo(options) { events.push(['redirectTo', options.url]); fail ? options.fail() : options.success(); },
navigateBack(options) { events.push(['navigateBack']); options.success(); },
}};
}
let d = device();
assert.equal(await beginPaymentSetup(d.api), true);
assert.deepEqual(d.events, [['prompt', '请先设置支付密码'], ['navigateTo', '/pages/mine/security?setupPayment=1']]);
d = device();
assert.equal(await beginPaymentSetup(d.api, 123), true);
assert.deepEqual(d.events[1], ['redirectTo', '/pages/mine/security?setupPayment=1&returnOrder=123']);
d = device(false);
assert.equal(await beginPaymentSetup(d.api, 123), false);
assert.equal(d.events.length, 1);
d = device(true, true);
await assert.rejects(beginPaymentSetup(d.api), /无法打开/);
d = device();
await finishPaymentSetup(d.api, '123');
assert.deepEqual(d.events, [['redirectTo', '/pages/order/detail?id=123']]);
d = device();
await finishPaymentSetup(d.api, '123&other=1');
assert.deepEqual(d.events, [['navigateBack']]);
console.log('payment setup navigation passed');

74
tests/user_identity_api.js 普通文件
查看文件

@@ -0,0 +1,74 @@
const assert = require('assert');
const { execFileSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const http = require('http');
const base = process.env.API_BASE || 'http://yjyf:9560/api';
const envText = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8');
const db = envText.split('[database]')[1].split(/\n\s*\[/)[0];
const setting = name => (db.match(new RegExp('^' + name + '\\s*=\\s*(.*)$', 'm')) || [])[1]?.trim();
const mysql = process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe';
function sql(query) {
return execFileSync(mysql, ['-h', setting('hostname'), '-P', setting('hostport'), '-u', setting('username'), '-D', setting('database'), '-N', '-e', query], { encoding: 'utf8', env: { ...process.env, MYSQL_PWD: setting('password') } }).trim();
}
async function api(route, data, token) {
return new Promise((resolve, reject) => {
const request = http.request(base + route, { method: data ? 'POST' : 'GET', headers: { ...(token ? { token } : {}), ...(data ? { 'content-type': 'application/x-www-form-urlencoded' } : {}) } }, response => {
let body = '';
response.setEncoding('utf8');
response.on('data', chunk => { body += chunk; });
response.on('end', () => { try { resolve(JSON.parse(body)); } catch (err) { reject(err); } });
});
request.on('error', reject);
request.end(data ? new URLSearchParams(data).toString() : undefined);
});
}
(async () => {
const mobiles = [];
try {
for (const kind of ['personal', 'merchant']) {
let mobile;
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
mobiles.push(mobile);
const login = await api('/auth/login', { mobile, password: 'TestPassword123!' });
assert.strictEqual(login.code, 1, login.msg);
const token = login.data.token;
assert.strictEqual(login.data.userinfo.identity_selected, false, 'new user must choose identity');
const invalid = await api('/auth/selectIdentity', { user_type: 'master' }, token);
assert.notStrictEqual(invalid.code, 1, 'only personal and merchant choices are accepted');
const beforeChoice = await api('/auth/login', { mobile, password: 'TestPassword123!' });
assert.strictEqual(beforeChoice.data.userinfo.identity_selected, false, 'unfinished selection survives a new login');
const prematureSave = await api('/auth/saveAccount', { nickname: 'Test identity' }, token);
assert.notStrictEqual(prematureSave.code, 1, 'account cannot be saved before selecting identity');
const select = await api('/auth/selectIdentity', { user_type: kind }, token);
assert.strictEqual(select.code, 1, select.msg);
assert.strictEqual(select.data.userinfo.user_type, kind);
assert.strictEqual(select.data.userinfo.identity_selected, true);
const again = await api('/auth/selectIdentity', { user_type: kind === 'personal' ? 'merchant' : 'personal' }, token);
assert.notStrictEqual(again.code, 1, 'identity cannot be changed');
const bypass = await api('/auth/saveAccount', { nickname: 'Test identity', user_type: kind === 'personal' ? 'merchant' : 'personal' }, token);
assert.notStrictEqual(bypass.code, 1, 'account save cannot change identity');
if (kind === 'merchant') {
const bills = await api('/merchant/bills', null, token);
assert.notStrictEqual(bills.code, 1, 'merchant identity does not grant certified merchant access');
assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_merchant WHERE user_id=${Number(login.data.userinfo.id)}`), '0', 'access must not create a certified merchant');
const save = await api('/auth/saveAccount', { nickname: 'Test identity', company_name: 'Example Company', legal_person: 'Test', legal_mobile: '13812345678', tech_mobile: '13912345678' }, token);
assert.strictEqual(save.code, 1, save.msg);
const profile = await api('/auth/profile', null, token);
assert.strictEqual(profile.data.company_name, 'Example Company');
assert.strictEqual(profile.data.legal_mobile, '13812345678');
assert.strictEqual(profile.data.is_merchant, false, 'identity does not create certified merchant');
}
const relogin = await api('/auth/login', { mobile, password: 'TestPassword123!' });
assert.strictEqual(relogin.data.userinfo.user_type, kind);
assert.strictEqual(relogin.data.userinfo.identity_selected, true);
}
console.log('identity API tests passed');
} finally {
for (const mobile of mobiles) {
sql(`DELETE s FROM fa_user_security s INNER JOIN fa_user u ON u.id=s.user_id WHERE u.mobile='${mobile}' AND u.username='${mobile}'`);
sql(`DELETE FROM fa_user WHERE mobile='${mobile}' AND username='${mobile}'`);
}
}
})().catch(err => { console.error(err); process.exitCode = 1; });

查看文件

@@ -0,0 +1,37 @@
<template>
<view v-if="visible" class="mask">
<view class="panel">
<text class="title">请输入支付密码</text>
<input v-model="password" class="input" type="number" password maxlength="6" focus placeholder="6位支付密码" />
<view class="actions"><button class="cancel" @tap="finish('')">取消</button><button class="confirm" @tap="submit">确认</button></view>
</view>
</view>
</template>
<script setup>
import { ref, onBeforeUnmount } from 'vue';
import api from '@/utils/api.js';
import { beginPaymentSetup } from '@/utils/payment-setup.mjs';
const visible = ref(false), password = ref('');
let resolvePrompt = null;
async function open(options = {}) {
const status = await api.securityStatus();
if (!status.has_payment_password) {
const navigated = await beginPaymentSetup(uni, options.createdOrderId);
throw Object.assign(new Error(navigated ? '正在设置支付密码' : '已取消设置支付密码'), {
handledToast: navigated, cancelled: !navigated, paymentSetupNavigation: navigated,
});
}
if (resolvePrompt) return '';
password.value = ''; visible.value = true;
return new Promise(resolve => { resolvePrompt = resolve; });
}
function finish(value) { visible.value = false; password.value = ''; const resolve = resolvePrompt; resolvePrompt = null; if (resolve) resolve(value); }
function submit() { if (!/^\d{6}$/.test(password.value)) { uni.showToast({ title: '请输入6位支付密码', icon: 'none' }); return; } finish(password.value); }
onBeforeUnmount(() => finish(''));
defineExpose({ open });
</script>
<style lang="scss" scoped>
@import '@/uni.scss';
.mask { position: fixed; inset: 0; z-index: 2000; display: flex; align-items: center; justify-content: center; padding: 48rpx; background: rgba(0,0,0,.5); }
.panel { width: 100%; padding: 40rpx; border-radius: 20rpx; background: $yjyf-bg-card; }.title { display: block; text-align: center; font-size: 32rpx; font-weight: 600; color: $yjyf-text-main; }.input { margin: 30rpx 0; height: 88rpx; text-align: center; background: $yjyf-bg-page; border-radius: 12rpx; }.actions { display: flex; gap: 20rpx; }.actions button { flex: 1; font-size: 28rpx; }.cancel { color: $yjyf-text-regular; background: $yjyf-bg-page; }.confirm { color: $yjyf-bg-card; background: $yjyf-gradient-primary; }
</style>

查看文件

@@ -213,6 +213,11 @@
</view>
<!-- 客户工单特别要求 -->
<view class="qualification-row" v-if="o.qual_req">
<text>资质要求:{{ o.qual_req }}</text>
<text v-if="!o.qualification_allowed" class="qualification-warning">暂无有效认证证书</text>
<text v-if="!o.qualification_allowed" class="qualification-link" @tap.stop="goCerts">去上传证书</text>
</view>
<view class="remark-row" v-if="o.remark">
<text class="remark-tag">工单要求</text>
<text class="remark-txt">{{ o.remark }}</text>
@@ -238,9 +243,10 @@
</view>
<view class="ft-btns">
<view v-if="!o.qualification_allowed" class="qualification-disabled"><text class="btn-txt">{{ o.price_type === 'quote' ? '暂不可报价' : '暂不可接单' }}</text></view>
<view
class="quote-btn clickable-hover"
v-if="o.price_type === 'quote'"
v-else-if="o.price_type === 'quote'"
@tap="goDetail(o)"
>
<text class="btn-txt">立即报价</text>
@@ -570,6 +576,9 @@
function goSkills() {
uni.navigateTo({ url: '/pages/master/skills' });
}
function goCerts() {
uni.navigateTo({ url: '/pages/master/certs' });
}
function openGrabConfirm(o) {
if (info.value && info.value.work_status === 'off') {
@@ -889,6 +898,10 @@
</script>
<style lang="scss" scoped>
.qualification-row { display: flex; flex-wrap: wrap; gap: 12rpx; margin-top: 16rpx; color: $yjyf-text-regular; font-size: $yjyf-font-sub; }
.qualification-warning { color: $yjyf-danger; }
.qualification-link { color: $yjyf-primary; }
.qualification-disabled { padding: 14rpx 24rpx; border-radius: $yjyf-radius-pill; background: $yjyf-text-disabled; }
@import '@/uni.scss';
.hall-view {

查看文件

@@ -227,6 +227,10 @@
</view>
</view>
<view class="menu-item clickable-hover" @tap="go('/pages/mine/security')">
<view class="mi-left"><image class="mi-ico" src="/static/icons/master/menu-account-security.svg" mode="aspectFit" /><text class="mi-title">账号安全</text></view>
<view class="mi-right"><image class="mi-arrow" src="/static/icons/arrow-right.svg" mode="aspectFit" /></view>
</view>
<view class="menu-item clickable-hover" @tap="openAgreementPicker">
<view class="mi-left">
<image class="mi-ico" src="/static/icons/master/menu-agreement.svg" mode="aspectFit" />
@@ -352,7 +356,7 @@
if (rejected > 0) {
return { text: `未通过 (${rejected})`, cls: 'is-danger' };
}
return { text: '认证可接资质要求订单', cls: 'is-warning' };
return { text: '上传证书展示专业资质', cls: 'is-warning' };
});
/**

查看文件

@@ -0,0 +1,34 @@
<template>
<view class="credentials">
<view class="credentials-row">
<text class="credentials-label">服务技能(师傅填写)</text>
<text class="credentials-value">{{ skillText }}</text>
</view>
<view class="credentials-row">
<text class="credentials-label">已认证证书</text>
<text class="credentials-value">{{ certText }}</text>
</view>
<text v-if="canExpand" class="credentials-toggle clickable-hover" @tap.stop="expanded = !expanded">{{ expanded ? '收起' : '查看全部' }}</text>
</view>
</template>
<script setup>
import { computed, ref } from 'vue';
const props = defineProps({
skills: { type: Array, default: () => [] },
certificates: { type: Array, default: () => [] }
});
const expanded = ref(false);
const canExpand = computed(() => props.skills.length > 3 || props.certificates.length > 3);
const display = (items, empty) => items.length ? (expanded.value ? items : items.slice(0, 3)).join('、') : empty;
const skillText = computed(() => display(props.skills, '暂无填写'));
const certText = computed(() => display(props.certificates, '暂无已认证证书'));
</script>
<style lang="scss" scoped>
.credentials { margin-top: 20rpx; }
.credentials-row { display: flex; align-items: flex-start; margin-top: 10rpx; font-size: $yjyf-font-sub; line-height: 1.5; }
.credentials-label { flex-shrink: 0; color: $yjyf-text-secondary; margin-right: 16rpx; }
.credentials-value { flex: 1; min-width: 0; color: $yjyf-text-regular; word-break: break-all; }
.credentials-toggle { display: block; margin-top: 8rpx; color: $yjyf-primary; font-size: $yjyf-font-sub; }
</style>

查看文件

@@ -103,6 +103,10 @@
<!-- 核心功能菜单 -->
<view class="card-panel">
<view class="menu-group">
<view class="menu-item clickable-hover" @tap="go('/pages/mine/security')">
<view class="menu-item-l"><image class="menu-ico" src="/static/icons/menu-account-security.svg" mode="aspectFit" /><text class="menu-txt">账号安全</text></view>
<view class="menu-item-r"><image class="arrow-ico" src="/static/icons/arrow-right.svg" mode="aspectFit" /></view>
</view>
<view class="menu-item clickable-hover" @tap="go('/pages/coupon/coupon?tab=center')">
<view class="menu-item-l">
<image class="menu-ico" src="/static/icons/menu-coupon.svg" mode="aspectFit" />
@@ -250,15 +254,7 @@
return !!(master.value && master.value.verify_status === 'pass');
});
const roleText = computed(() => {
const curRole = currentRole.value;
if (curRole === 'master' && master.value && master.value.verify_status === 'pass') {
return '认证师傅';
}
if (master.value && master.value.verify_status === 'pass') return '认证师傅';
if (master.value && master.value.verify_status === 'pending') return '师傅审核中';
return '个人用户';
});
const roleText = computed(() => user.value && user.value.user_type === 'merchant' ? '商家用户' : '个人用户');
const masterCard = computed(() => {
const m = master.value;

查看文件

@@ -187,6 +187,10 @@
"path": "pages/mine/account",
"style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" }
},
{
"path": "pages/mine/security",
"style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" }
},
{
"path": "pages/user/wallet",
"style": {

查看文件

@@ -22,21 +22,38 @@
<!-- 全局统一底部导航 (方案 A:单母页组件化调度,0ms 极速秒切) -->
<YjyfTabBar :current="activeTab" @change="onTabChange" />
<view v-if="showIdentityPicker" class="identity-mask">
<view class="identity-dialog">
<text class="identity-title">请选择用户类型</text>
<text class="identity-description">请选择您的使用身份,确认后不可自行修改</text>
<view class="identity-option" :class="{ selected: identityChoice === 'personal' }" @tap="identityChoice = 'personal'">
<text class="identity-option-title">个人用户</text><text class="identity-option-desc">家庭或个人使用</text>
</view>
<view class="identity-option" :class="{ selected: identityChoice === 'merchant' }" @tap="identityChoice = 'merchant'">
<text class="identity-option-title">商家用户</text><text class="identity-option-desc">商家或企业使用</text>
</view>
<button class="identity-confirm" :disabled="!identityChoice || selectingIdentity" @tap="confirmIdentity">{{ selectingIdentity ? '提交中...' : '确认选择' }}</button>
</view>
</view>
</view>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app';
import UserHomeView from '@/components/user/UserHomeView.vue';
import UserOrdersView from '@/components/user/UserOrdersView.vue';
import UserMessageView from '@/components/user/UserMessageView.vue';
import UserMineView from '@/components/user/UserMineView.vue';
import YjyfTabBar from '@/components/YjyfTabBar.vue';
import { isLogin, toLogin } from '@/utils/request.js';
import { isLogin, toLogin, getUser, setUser } from '@/utils/request.js';
import api from '@/utils/api.js';
import { getRole, setRole } from '@/utils/role.js';
import { useShare } from '@/utils/share.js';
const showIdentityPicker = ref(false);
const identityChoice = ref('');
const selectingIdentity = ref(false);
const activeTab = ref(0);
const initialOrderStatus = ref('all');
const visitedTabs = reactive({ 0: true, 1: false, 2: false, 3: false });
@@ -110,6 +127,11 @@
}
onLoad((query) => {
const currentUser = getUser();
if (isLogin() && currentUser && currentUser.identity_selected === false) {
setRole('user');
return;
}
// 已登录且当前为师傅身份时,冷启动自动跳转到师傅工作台界面
if (isLogin() && getRole() === 'master' && (!query || !query.forceUser)) {
uni.reLaunch({ url: '/pages/master/workbench' });
@@ -135,7 +157,37 @@
}
});
async function confirmIdentity() {
if (!identityChoice.value || selectingIdentity.value) return;
selectingIdentity.value = true;
try {
const res = await api.selectIdentity({ user_type: identityChoice.value });
setUser(res.userinfo);
showIdentityPicker.value = false;
} catch (e) {
// A response can be lost after the selection has been saved.
try {
const current = await api.profile();
if (current.identity_selected) {
setUser(current);
showIdentityPicker.value = false;
}
} catch (profileError) {}
} finally {
selectingIdentity.value = false;
}
}
onBackPress(() => showIdentityPicker.value);
onShow(() => {
const currentUser = getUser();
if (isLogin() && currentUser && currentUser.identity_selected === false) {
activeTab.value = 0;
showIdentityPicker.value = true;
setRole('user');
return;
}
if (isLogin() && getRole() === 'master') {
uni.reLaunch({ url: '/pages/master/workbench' });
return;
@@ -149,7 +201,19 @@
});
</script>
<style scoped>
<style lang="scss" scoped>
@import '@/uni.scss';
.identity-mask { position: fixed; inset: 0; z-index: 999; background: rgba(0,0,0,.5); display: flex; align-items: center; justify-content: center; padding: 48rpx; }
.identity-dialog { width: 100%; background: $yjyf-bg-card; border-radius: 24rpx; padding: 40rpx; display: flex; flex-direction: column; }
.identity-title { font-size: 36rpx; font-weight: 700; color: $yjyf-text-main; text-align: center; }
.identity-description { margin: 16rpx 0 32rpx; font-size: 25rpx; color: $yjyf-text-secondary; text-align: center; }
.identity-option { display: flex; flex-direction: column; padding: 24rpx; margin-bottom: 20rpx; border: 2rpx solid $yjyf-border-color; border-radius: 16rpx; }
.identity-option.selected { border-color: $yjyf-primary; background: $yjyf-primary-bg; }
.identity-option-title { font-size: 30rpx; font-weight: 600; color: $yjyf-text-main; }
.identity-option-desc { margin-top: 8rpx; font-size: 24rpx; color: $yjyf-text-secondary; }
.identity-confirm { width: 100%; margin-top: 12rpx; background: $yjyf-gradient-primary; color: $yjyf-bg-card; border-radius: 16rpx; font-size: 30rpx; }
.identity-confirm[disabled] { opacity: .5; }
.user-container-page {
height: 100vh;
overflow: hidden;

查看文件

@@ -280,6 +280,12 @@
setUser(res.userinfo);
syncUserData(res);
if (res.userinfo.identity_selected === false) {
loading.value = false;
setRole('user');
uni.reLaunch({ url: '/pages/index/index' });
return;
}
toast('登录成功');
setTimeout(() => {
loading.value = false;
@@ -330,6 +336,12 @@
setUser(res.userinfo);
syncUserData(res);
if (res.userinfo.identity_selected === false) {
loading.value = false;
setRole('user');
uni.reLaunch({ url: '/pages/index/index' });
return;
}
toast(res.is_new ? '欢迎加入优匠优服' : '登录成功');
setTimeout(() => {
loading.value = false;
@@ -344,7 +356,7 @@
/** 同步更新全局角色状态(师傅通过审核后下次登录默认直接进入师傅工作台) */
function syncUserData(res) {
const userinfo = (res && res.userinfo) || {};
const isMasterPass = Boolean(userinfo.is_master && userinfo.master);
const isMasterPass = Boolean(userinfo.is_master && userinfo.master && userinfo.master.verify_status === 'pass');
// 检查是否有特定指向业主端具体业务页面的重定向(排除首页、我的、登录页等通用页面)
const isExplicitUserTarget = redirectUrl && (
@@ -431,6 +443,7 @@
</script>
<style scoped>
.page {
min-height: 100vh;
background: #FFFFFF;

查看文件

@@ -138,6 +138,14 @@
</view>
</view>
<view class="card qualification-card" v-if="order.qual_req">
<text>资质要求:{{ order.qual_req }}</text>
<template v-if="!order.qualification_allowed">
<text class="qualification-warning">暂无有效认证证书,不能接单或报价</text>
<text class="qualification-link clickable-hover" @tap="goCerts">去上传证书</text>
</template>
</view>
<!-- 我的报价状态卡(已报价时展示) -->
<view class="card quote-state-card" v-if="order.my_quote">
<view class="card-head">
@@ -452,7 +460,7 @@
@tap="openQuoteDrawer"
>立即提交报价</view>
<view v-else class="b-btn disabled-solid">
{{ order.my_quote ? '已提交报价,等待客户选标' : '当前暂不可接单' }}
{{ order.my_quote ? '已提交报价,等待客户选标' : (!order.qualification_allowed ? '暂无有效认证证书' : '当前暂不可接单') }}
</view>
</view>
</template>
@@ -1211,6 +1219,9 @@
quoteForm.description = '';
showQuote.value = true;
}
function goCerts() {
uni.navigateTo({ url: '/pages/master/certs' });
}
async function submitQuote() {
if (submitting.value || !order.value) return;
@@ -1294,6 +1305,9 @@
</script>
<style lang="scss" scoped>
.qualification-card { display: flex; flex-wrap: wrap; gap: 12rpx; color: $yjyf-text-regular; font-size: $yjyf-font-sub; }
.qualification-warning { color: $yjyf-danger; }
.qualification-link { color: $yjyf-primary; }
@import '@/uni.scss';
.page {
min-height: 100vh;

查看文件

@@ -131,7 +131,7 @@
<view class="empty-box" v-else>
<image class="empty-img" src="/static/icons/empty-orders.svg" mode="aspectFit" />
<text class="empty-txt">暂无提现申请记录</text>
</view>
</view>
</template>
<!-- 钱包收支流水视图 -->
@@ -364,11 +364,14 @@
</view>
</view>
</view>
<YjyfPaymentPassword ref="paymentPasswordDialog" />
</view>
</template>
<script setup>
import YjyfPaymentPassword from '@/components/YjyfPaymentPassword.vue';
import { ref, computed } from 'vue';
const paymentPasswordDialog = ref(null);
import { onShow } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
import { getSafeWxCode, invokeMerchantTransferConfirm } from '@/utils/pay.js';
@@ -594,9 +597,12 @@
const amt = parsedWithdraw.value;
withdrawing.value = true;
try {
const paymentPassword = await paymentPasswordDialog.value.open();
if (!paymentPassword) return;
const wxCode = selectedChannel.value === 'wechat' ? await getSafeWxCode() : '';
const res = await api.masterWithdraw({
amount: amt,
payment_password: paymentPassword,
channel: selectedChannel.value,
account: selectedChannel.value === 'bank' ? bankAccount.value.trim() : '微信零钱',
wx_code: wxCode

查看文件

@@ -8,6 +8,10 @@
<image class="profile-avatar" :src="avatarPreview || '/static/icons/user-avatar.svg'" mode="aspectFill" />
<text class="avatar-action">{{ uploading ? '上传中...' : '更换' }}</text>
</view>
<view class="row">
<text class="label">用户类型</text>
<text class="val-txt">{{ form.user_type === 'merchant' ? '商家' : '家庭/个人' }}</text>
</view>
<!-- 用户昵称 -->
<view class="row">
<text class="label">用户昵称</text>
@@ -19,6 +23,12 @@
/>
</view>
<template v-if="form.user_type === 'merchant'">
<view class="row"><text class="label">公司名称</text><input class="input" v-model="form.company_name" placeholder="请输入公司名称" /></view>
<view class="row"><text class="label">法人姓名</text><input class="input" v-model="form.legal_person" placeholder="请输入法人姓名" /></view>
<view class="row"><text class="label">法人手机号</text><input class="input" type="number" maxlength="11" v-model="form.legal_mobile" placeholder="请输入法人手机号" /></view>
<view class="row"><text class="label">技术手机号</text><input class="input" type="number" maxlength="11" v-model="form.tech_mobile" placeholder="请输入技术手机号" /></view>
</template>
<!-- 联系号码与灰底提示说明(对标图三、图四) -->
<view class="row no-border">
<text class="label">联系号码</text>
@@ -73,6 +83,7 @@
const form = reactive({
user_type: 'personal',
nickname: '',
company_name: '', legal_person: '', legal_mobile: '', tech_mobile: '',
contact_address: '',
email: ''
});
@@ -95,6 +106,11 @@
rawMobile.value = data.mobile || '';
avatarPreview.value = data.avatar || '';
newAvatar.value = '';
form.user_type = data.user_type;
form.company_name = data.company_name || '';
form.legal_person = data.legal_person || '';
form.legal_mobile = data.legal_mobile || '';
form.tech_mobile = data.tech_mobile || '';
form.nickname = data.nickname || '';
form.contact_address = data.contact_address || '';
form.email = data.email || '';
@@ -105,6 +121,7 @@
return {
...(newAvatar.value ? { avatar: newAvatar.value } : {}),
nickname: form.nickname.trim(),
...(form.user_type === 'merchant' ? { company_name: form.company_name.trim(), legal_person: form.legal_person.trim(), legal_mobile: form.legal_mobile.trim(), tech_mobile: form.tech_mobile.trim() } : {}),
contact_address: form.contact_address.trim(),
email: form.email.trim()
};

查看文件

@@ -0,0 +1,142 @@
<template>
<view class="page">
<YjyfNavBar theme="white" title="账号安全" :border="true" :showBack="returnOrder ? true : null" :customBack="!!returnOrder" @back="leaveSetup" />
<view v-if="loaded" class="card">
<view class="row" @tap="openPassword('login')"><text>登录密码</text><view class="value">{{ status.has_login_password ? '修改' : '设置' }} <image class="arrow" src="/static/icons/arrow-right.svg" mode="aspectFit" /></view></view>
<view class="row" @tap="openPassword('payment')"><text>支付密码</text><view class="value">{{ status.has_payment_password ? '修改' : '设置' }} <image class="arrow" src="/static/icons/arrow-right.svg" mode="aspectFit" /></view></view>
<view class="row" @tap="openCert"><text>企业资质认证</text><view class="value">{{ certText }} <image class="arrow" src="/static/icons/arrow-right.svg" mode="aspectFit" /></view></view>
</view>
<view v-if="mode" class="mask">
<view class="sheet">
<view class="sheet-head"><text class="title">{{ sheetTitle }}</text><text class="close" @tap="close">取消</text></view>
<template v-if="mode === 'login'">
<input v-if="status.has_login_password" v-model="oldPassword" class="input" password placeholder="请输入原登录密码" />
<input v-model="newPassword" class="input" password maxlength="30" placeholder="新登录密码(6至30位)" />
<input v-model="confirmPassword" class="input" password maxlength="30" placeholder="再次输入新登录密码" />
<text v-if="!status.has_login_password" class="hint">请使用绑定的微信手机号验证身份。</text>
<!-- #ifdef MP-WEIXIN -->
<button v-if="!status.has_login_password" class="primary" open-type="getPhoneNumber" :disabled="busy" @getphonenumber="onPhoneVerify">验证手机号并设置</button>
<!-- #endif -->
<!-- #ifndef MP-WEIXIN -->
<text v-if="!status.has_login_password" class="hint">请在微信小程序中完成手机号验证后设置。</text>
<!-- #endif -->
<button v-if="status.has_login_password" class="primary" :disabled="busy" @tap="savePassword">确认修改</button>
</template>
<template v-else-if="mode === 'payment'">
<input v-if="status.has_payment_password" v-model="oldPassword" class="input" type="number" password maxlength="6" placeholder="请输入原支付密码" />
<input v-else-if="!status.has_payment_password" v-model="oldPassword" class="input" password placeholder="请输入登录密码以验证身份" />
<input v-model="newPassword" class="input" type="number" password maxlength="6" placeholder="设置6位支付密码" />
<input v-model="confirmPassword" class="input" type="number" password maxlength="6" placeholder="再次输入支付密码" />
<button class="primary" :disabled="busy" @tap="savePassword">确认</button>
</template>
<template v-else>
<text v-if="cert && cert.verify_status === 'reject'" class="hint">审核未通过:{{ cert.audit_msg }}</text>
<text class="hint">上传后将通过腾讯云识别营业执照,请核对识别信息后提交。</text>
<input v-model="companyName" class="input" placeholder="请输入企业名称" />
<input v-model="licenseNo" class="input" placeholder="请输入营业执照号码" maxlength="18" />
<input v-model="legalPerson" class="input" placeholder="请输入法人姓名(选填)" />
<view class="upload" @tap="chooseLicense"><image v-if="imagePreview" :src="imagePreview" mode="aspectFit" class="license"/><text>{{ licenseImage ? '重新上传营业执照' : '上传营业执照' }}</text></view>
<button class="primary" :disabled="busy" @tap="submitCert">提交审核</button>
</template>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed } from 'vue';
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app';
import YjyfNavBar from '@/components/YjyfNavBar.vue';
import api from '@/utils/api.js';
import { clearAuth } from '@/utils/request.js';
import { finishPaymentSetup } from '@/utils/payment-setup.mjs';
const loaded = ref(false), busy = ref(false), mode = ref('');
const returnOrder = ref('');
let setupFromPayment = false, setupOpened = false;
const status = ref({}), oldPassword = ref(''), newPassword = ref(''), confirmPassword = ref('');
const companyName = ref(''), licenseNo = ref(''), legalPerson = ref(''), licenseImage = ref(''), imagePreview = ref('');
const cert = computed(() => status.value.enterprise_cert || null);
const certText = computed(() => cert.value ? ({ pending: '审核中', pass: '已认证', reject: '未通过,可重提' }[cert.value.verify_status] || '') : '未认证');
const sheetTitle = computed(() => mode.value === 'login' ? '登录密码' : mode.value === 'payment' ? '支付密码' : '企业资质认证');
async function load() { try { status.value = await api.securityStatus(); loaded.value = true; } catch (e) {} }
function close() { if (busy.value) return; mode.value = ''; oldPassword.value = ''; newPassword.value = ''; confirmPassword.value = ''; }
function openPassword(which) { mode.value = which; }
function openCert() {
if (cert.value && cert.value.verify_status !== 'reject') { uni.showToast({ title: certText.value, icon: 'none' }); return; }
if (cert.value) { companyName.value = cert.value.company_name; licenseNo.value = cert.value.license_no; legalPerson.value = cert.value.legal_person; }
mode.value = 'cert';
}
function validPassword() {
const valid = mode.value === 'payment' ? /^\d{6}$/.test(newPassword.value) : /^\S{6,30}$/.test(newPassword.value);
if (!valid || newPassword.value !== confirmPassword.value) { uni.showToast({ title: '请检查两次输入的密码', icon: 'none' }); return false; }
return true;
}
async function onPhoneVerify(event) {
const code = event.detail && event.detail.code;
if (!code) { uni.showToast({ title: '未完成手机号验证', icon: 'none' }); return; }
await savePassword(code);
}
async function savePassword(phoneCode = '') {
if (typeof phoneCode !== 'string') phoneCode = '';
if (busy.value || !validPassword()) return;
busy.value = true;
try {
if (mode.value === 'login') {
await api.changeLoginPassword({ old_password: oldPassword.value, new_password: newPassword.value, phone_code: phoneCode });
clearAuth(); uni.showToast({ title: '请重新登录', icon: 'none' });
setTimeout(() => uni.reLaunch({ url: '/pages/login/login' }), 700); return;
}
const firstSetup = !status.value.has_payment_password;
if (!firstSetup) await api.changePaymentPassword({ old_password: oldPassword.value, new_password: newPassword.value });
else await api.setPaymentPassword({ login_password: oldPassword.value, new_password: newPassword.value });
busy.value = false; close(); uni.showToast({ title: '保存成功' });
if (setupFromPayment && firstSetup) {
try { await finishPaymentSetup(uni, returnOrder.value); } catch (e) { uni.showToast({ title: e.message, icon: 'none' }); }
} else await load();
} catch (e) {} finally { busy.value = false; }
}
function chooseLicense() { if (busy.value) return; uni.chooseImage({ count: 1, sizeType: ['compressed'], success: async res => {
busy.value = true; try {
const uploaded = await api.upload(res.tempFilePaths[0], 'cert'); licenseImage.value = uploaded.url; imagePreview.value = uploaded.fullurl || res.tempFilePaths[0];
try { const recognized = await api.recognizeEnterpriseLicense({ license_image: uploaded.url }); companyName.value = recognized.company_name; licenseNo.value = recognized.license_no; legalPerson.value = recognized.legal_person; }
catch (e) { /* Recognition errors are displayed by the request layer; manual entry remains available. */ }
} catch (e) {} finally { busy.value = false; }
} }); }
async function submitCert() {
if (busy.value) return;
if (!companyName.value.trim() || !licenseNo.value.trim() || !licenseImage.value) { uni.showToast({ title: '请填写企业信息并上传营业执照', icon: 'none' }); return; }
busy.value = true;
try { await api.submitEnterpriseCert({ company_name: companyName.value.trim(), license_no: licenseNo.value.trim(), legal_person: legalPerson.value.trim(), license_image: licenseImage.value }); busy.value = false; close(); await load(); uni.showToast({ title: '提交成功' }); } catch (e) {} finally { busy.value = false; }
}
async function leaveSetup() {
try { await finishPaymentSetup(uni, returnOrder.value); } catch (e) { uni.showToast({ title: e.message, icon: 'none' }); }
}
onLoad((options) => {
setupFromPayment = !!(options && options.setupPayment === '1');
const id = String((options && options.returnOrder) || '');
if (setupFromPayment && /^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id))) returnOrder.value = id;
});
onBackPress(() => {
if (!returnOrder.value) return false;
leaveSetup();
return true;
});
onShow(async () => {
await load();
if (!loaded.value || !setupFromPayment || setupOpened) return;
setupOpened = true;
if (status.value.has_payment_password) await leaveSetup();
else openPassword('payment');
});
</script>
<style lang="scss" scoped>
@import '@/uni.scss';
.page { min-height: 100vh; background: $yjyf-bg-page; }
.card { margin: 24rpx; padding: 0 28rpx; background: $yjyf-bg-card; border-radius: 20rpx; }
.row { min-height: 100rpx; display: flex; align-items: center; justify-content: space-between; border-bottom: 1rpx solid $yjyf-border-color; color: $yjyf-text-main; font-size: 30rpx; }
.row:last-child { border-bottom: 0; }.value { color: $yjyf-text-secondary; font-size: 26rpx; display: flex; align-items: center; }.arrow { width: 26rpx; height: 26rpx; margin-left: 10rpx; }
.mask { position: fixed; inset: 0; z-index: 1000; background: rgba(0,0,0,.5); display: flex; align-items: flex-end; }
.sheet { width: 100%; max-height: 90vh; overflow-y: auto; padding: 30rpx 30rpx calc(30rpx + env(safe-area-inset-bottom)); border-radius: 24rpx 24rpx 0 0; background: $yjyf-bg-card; }
.sheet-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24rpx; }.title { color: $yjyf-text-main; font-size: 32rpx; font-weight: 600; }.close { color: $yjyf-text-secondary; font-size: 28rpx; }
.input { height: 88rpx; padding: 0 20rpx; margin-bottom: 16rpx; background: $yjyf-bg-page; border-radius: 12rpx; font-size: 28rpx; }.hint { display: block; margin: 12rpx 0; color: $yjyf-text-secondary; font-size: 24rpx; }
.primary { margin-top: 22rpx; background: $yjyf-gradient-primary; color: $yjyf-bg-card; font-size: 30rpx; }.upload { display: flex; flex-direction: column; align-items: center; gap: 10rpx; padding: 24rpx; color: $yjyf-primary; border: 1rpx solid $yjyf-border-color; font-size: 26rpx; }.license { width: 300rpx; height: 180rpx; }
</style>

查看文件

@@ -226,11 +226,14 @@
@update:visible="showCreateRegion = $event"
@confirm="onCreateRegionDrawerConfirm"
/>
<YjyfPaymentPassword ref="paymentPasswordDialog" />
</view>
</template>
<script setup>
import YjyfPaymentPassword from '@/components/YjyfPaymentPassword.vue';
import { ref, reactive, watch, computed } from 'vue';
const paymentPasswordDialog = ref(null);
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js';
@@ -546,9 +549,10 @@
} catch (pe) {}
// 一口价或自主定价调起支付
const payment = await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType });
const payment = await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType }, () => paymentPasswordDialog.value.open({ createdOrderId }));
openOrderPaymentResult(createdOrderId, payment, true);
} catch (e) {
if (e && e.paymentSetupNavigation) { submitting.value = false; return; }
if (createdOrderId) {
if (!e || !e.unsupportedEnv) {
const reason = (e && e.message) ? `订单已创建(${e.message})` : '订单已创建,请在详情页完成支付';

查看文件

@@ -183,6 +183,7 @@
<text class="call-txt">拨打电话</text>
</view>
</view>
<MasterCredentials :skills="master.skills" :certificates="master.certificates" />
</view>
<!-- ==================== 业务联动:现场增项补差价待支付 ==================== -->
@@ -213,6 +214,7 @@
</view>
<text class="q-amt">¥{{ q.amount }}</text>
</view>
<MasterCredentials :skills="q.skills" :certificates="q.certificates" />
<text class="q-desc" v-if="q.description">{{ q.description }}</text>
<view class="q-foot">
<text class="q-expire">有效期至 {{ q.expire_text }}</text>
@@ -319,7 +321,7 @@
<view class="cs-btn clickable-hover" @tap="contactService">
<image class="cs-icon" src="/static/icons/customer-service-gray.svg" mode="aspectFit" />
<text class="cs-label">客服</text>
</view>
</view>
<!-- 按钮动作组合 (与对标图一致) -->
<view class="action-btns-wrap">
@@ -424,15 +426,19 @@
</view>
</view>
<YjyfServicePopup :visible="servicePopupVisible" @update:visible="servicePopupVisible = $event" />
<YjyfPaymentPassword ref="paymentPasswordDialog" />
</view>
</template>
<script setup>
import YjyfPaymentPassword from '@/components/YjyfPaymentPassword.vue';
import { ref, computed } from 'vue';
const paymentPasswordDialog = ref(null);
import { formatServiceItems } from '@/utils/order-service-items.mjs';
import { onLoad, onShow } from '@dcloudio/uni-app';
import YjyfNavBar from '@/components/YjyfNavBar.vue';
import YjyfServicePopup from '@/components/YjyfServicePopup.vue';
import MasterCredentials from '@/components/order/MasterCredentials.vue';
import api from '@/utils/api.js';
import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js';
@@ -668,7 +674,7 @@
return;
}
}
const payment = await executeOrderWxPay(api.orderChooseQuote, { order_id: orderId, quote_id: q.id, pay_type: payType });
const payment = await executeOrderWxPay(api.orderChooseQuote, { order_id: orderId, quote_id: q.id, pay_type: payType }, () => paymentPasswordDialog.value.open());
if (payment.out_trade_no) {
openOrderPaymentResult(orderId, payment, true);
} else {
@@ -701,7 +707,7 @@
actionBusy.value = false;
return;
}
const payment = await executeOrderWxPay(api.orderPayDiff, { order_id: orderId, pay_type: payType });
const payment = await executeOrderWxPay(api.orderPayDiff, { order_id: orderId, pay_type: payType }, () => paymentPasswordDialog.value.open());
openOrderPaymentResult(orderId, payment, true);
} catch (e) {
if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) {
@@ -745,7 +751,7 @@
actionBusy.value = true;
try {
const payment = await executeOrderWxPay(api.orderPay, { order_id: orderId, pay_type: payType });
const payment = await executeOrderWxPay(api.orderPay, { order_id: orderId, pay_type: payType }, () => paymentPasswordDialog.value.open());
openOrderPaymentResult(orderId, payment, true);
} catch (e) {
if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) {

查看文件

@@ -154,7 +154,7 @@
<image class="dc-icon" src="/static/icons/add-env.svg" mode="aspectFit" />
<text class="dc-txt gray">安装环境图</text>
<text class="dc-sub gray">(非必填)</text>
</view>
</view>
</template>
<!-- 4. 紧跟末尾的橙色帮助问号图标 -->
@@ -1084,12 +1084,15 @@
</scroll-view>
</view>
</view>
<YjyfPaymentPassword ref="paymentPasswordDialog" />
</view>
</template>
<script setup>
import YjyfPaymentPassword from '@/components/YjyfPaymentPassword.vue';
import { serviceAddons } from '@/utils/productPricing.js';
import { ref, reactive, computed } from 'vue';
const paymentPasswordDialog = ref(null);
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import api from '@/utils/api.js';
import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js';
@@ -2594,9 +2597,10 @@
openOrderPaymentResult(createdOrderId, await executeOrderWxPay(api.orderPay, {
order_id: createdOrderId,
pay_type: (selectedPayType.value === 'balance' && isBalanceSufficient.value) ? 'balance' : 'wechat'
}), true);
}, () => paymentPasswordDialog.value.open({ createdOrderId })), true);
}
} catch (e) {
if (e && e.paymentSetupNavigation) { submitting.value = false; return; }
if (createdOrderId) {
if (!e || !e.unsupportedEnv) {
const reason = (e && e.message) ? `订单已创建(${e.message})` : '订单已创建,请在详情页完成支付';

查看文件

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none"><path d="M24 5 9 11v11c0 9 5.8 16.3 15 21 9.2-4.7 15-12 15-21V11L24 5Z" stroke="#F0710D" stroke-width="3"/><circle cx="24" cy="23" r="3" fill="#F0710D"/><path d="M24 26v5" stroke="#F0710D" stroke-width="3" stroke-linecap="round"/></svg>

之后

宽度:  |  高度:  |  大小: 309 B

查看文件

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" fill="none"><path d="M24 4 8 10v12c0 10 6.6 17.5 16 22 9.4-4.5 16-12 16-22V10L24 4Z" stroke="#F0710D" stroke-width="3" stroke-linejoin="round"/><rect x="17" y="21" width="14" height="11" rx="2" stroke="#F0710D" stroke-width="3"/><path d="M20 21v-3a4 4 0 0 1 8 0v3" stroke="#F0710D" stroke-width="3" stroke-linecap="round"/></svg>

之后

宽度:  |  高度:  |  大小: 390 B

查看文件

@@ -16,6 +16,13 @@ export default {
wxPhoneLogin: (data) => post('/auth/wxPhoneLogin', data, { silent: true }),
switchRole: (data) => post('/auth/switchRole', data),
profile: () => get('/auth/profile'),
selectIdentity: (data) => post('/auth/selectIdentity', data),
securityStatus: () => get('/security/status'),
changeLoginPassword: (data) => post('/security/changeLoginPassword', data),
setPaymentPassword: (data) => post('/security/setPaymentPassword', data),
changePaymentPassword: (data) => post('/security/changePaymentPassword', data),
submitEnterpriseCert: (data) => post('/security/submitEnterpriseCert', data),
recognizeEnterpriseLicense: (data) => post('/security/recognizeEnterpriseLicense', data),
saveAccount: (data) => post('/auth/saveAccount', data),
/* ---------- 用户钱包与充值 ---------- */

查看文件

@@ -61,8 +61,13 @@ export function getSafeWxCode() {
* @param {Object} params 业务入参(如 { order_id } 或 { order_id, quote_id })
* @returns {Promise<Object>}
*/
export async function executeOrderWxPay(createPayApiFn, params = {}) {
export async function executeOrderWxPay(createPayApiFn, params = {}, promptPaymentPassword) {
const payload = Object.assign({}, params);
if (payload.pay_type === 'balance') {
if (typeof promptPaymentPassword !== 'function') throw new Error('支付密码输入不可用');
payload.payment_password = await promptPaymentPassword();
if (!payload.payment_password) throw Object.assign(new Error('支付已取消'), { cancelled: true });
}
// 纯余额支付无需向微信换取登录凭证 code,直接请求后端原子核销入账
if (payload.pay_type !== 'balance') {

查看文件

@@ -0,0 +1,28 @@
/** Guide the user to set a payment password, without initiating a transaction. */
export async function beginPaymentSetup(device, createdOrderId = '') {
const orderId = String(createdOrderId || '');
if (orderId && (!/^[1-9]\d*$/.test(orderId) || !Number.isSafeInteger(Number(orderId)))) {
throw new Error('订单信息无效,无法打开支付密码设置');
}
const confirmed = await new Promise((resolve) => {
device.showModal({ title: '请先设置支付密码', content: '设置后将返回当前页面,请再次确认支付或提现。', confirmText: '去设置', success: (res) => resolve(!!res.confirm), fail: () => resolve(false) });
});
if (!confirmed) return false;
const url = '/pages/mine/security?setupPayment=1' + (orderId ? '&returnOrder=' + orderId : '');
await new Promise((resolve, reject) => {
const action = orderId ? 'redirectTo' : 'navigateTo';
device[action]({ url, success: resolve, fail: () => reject(new Error('无法打开支付密码设置,请稍后重试')) });
});
return true;
}
/** Return to the originating page, or to an already-created order. */
export function finishPaymentSetup(device, returnOrder = '') {
const orderId = String(returnOrder || '');
const valid = /^[1-9]\d*$/.test(orderId) && Number.isSafeInteger(Number(orderId));
return new Promise((resolve, reject) => {
const options = { success: resolve, fail: () => reject(new Error('返回页面失败,请手动返回')) };
if (valid) device.redirectTo({ ...options, url: '/pages/order/detail?id=' + orderId });
else device.navigateBack(options);
});
}