From b71980dd6b35faa5708ca6a67a77d1fdd993cafa Mon Sep 17 00:00:00 2001 From: MiAn Date: Sat, 21 Nov 2026 15:37:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E6=A8=A1=E5=9D=97=E5=8F=8A=E8=B5=84=E8=B4=A8?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增账号安全页面及支付密码验证组件 - 新增用户类型选择流程及商家资质管理 - 新增订单资质校验逻辑,师傅需满足订单证书要求 - 新增企业资质认证相关数据库表及接口 - 优化用户列表展示,区分个人与商家用户类型 --- db/migrate_account_security_lockout.sql | 19 +++ db/migrate_enterprise_admin_menus.sql | 8 + db/schema_account_security.sql | 23 +++ db/schema_user_identity.sql | 8 + server/application/admin/controller/Home.php | 2 +- .../admin/controller/MasterCert.php | 2 +- .../application/admin/controller/Merchant.php | 56 +++++++ server/application/admin/controller/Order.php | 3 + .../admin/controller/user/User.php | 25 +-- .../application/admin/view/common/meta.html | 3 + server/application/admin/view/home/index.html | 4 +- .../admin/view/merchant/certificates.html | 8 + .../admin/view/merchant/index.html | 5 +- .../admin/view/user/user/detail.html | 30 ++++ .../admin/view/user/user/index.html | 8 +- server/application/api/controller/Auth.php | 70 +++++---- server/application/api/controller/Base.php | 10 ++ server/application/api/controller/Master.php | 19 ++- .../application/api/controller/Merchant.php | 47 +----- server/application/api/controller/Order.php | 26 ++++ .../application/api/controller/Security.php | 133 ++++++++++++++++ server/application/api/controller/User.php | 46 +----- .../common/library/AccountSecurity.php | 56 +++++++ server/application/common/library/Auth.php | 12 +- .../common/library/EnterpriseLicenseImage.php | 44 ++++++ .../common/library/MasterOrderCredentials.php | 29 ++++ .../common/library/OrderQualification.php | 31 ++++ server/public/assets/js/backend/merchant.js | 38 ++++- server/public/assets/js/backend/user/user.js | 5 +- tests/account_security_api.js | 123 +++++++++++++++ tests/account_security_lockout.js | 60 ++++++++ tests/enterprise_cert_admin.js | 59 ++++++++ tests/enterprise_ocr_cos.php | 18 +++ tests/master_order_credentials.php | 30 ++++ tests/order_qualification.php | 19 +++ tests/order_qualification_endpoints.php | 50 ++++++ tests/payment_setup_navigation.mjs | 31 ++++ tests/user_identity_api.js | 74 +++++++++ yjyf-app/components/YjyfPaymentPassword.vue | 37 +++++ yjyf-app/components/master/MasterHallView.vue | 15 +- .../components/master/MasterWorkbenchView.vue | 6 +- .../components/order/MasterCredentials.vue | 34 +++++ yjyf-app/components/user/UserMineView.vue | 14 +- yjyf-app/pages.json | 4 + yjyf-app/pages/index/index.vue | 70 ++++++++- yjyf-app/pages/login/login.vue | 15 +- yjyf-app/pages/master/detail.vue | 16 +- yjyf-app/pages/master/wallet.vue | 8 +- yjyf-app/pages/mine/account.vue | 17 +++ yjyf-app/pages/mine/security.vue | 142 ++++++++++++++++++ yjyf-app/pages/order/create.vue | 6 +- yjyf-app/pages/order/detail.vue | 14 +- yjyf-app/pages/order/quick.vue | 8 +- .../icons/master/menu-account-security.svg | 1 + .../static/icons/menu-account-security.svg | 1 + yjyf-app/utils/api.js | 7 + yjyf-app/utils/pay.js | 7 +- yjyf-app/utils/payment-setup.mjs | 28 ++++ 58 files changed, 1515 insertions(+), 169 deletions(-) create mode 100644 db/migrate_account_security_lockout.sql create mode 100644 db/migrate_enterprise_admin_menus.sql create mode 100644 db/schema_account_security.sql create mode 100644 db/schema_user_identity.sql create mode 100644 server/application/admin/view/merchant/certificates.html create mode 100644 server/application/api/controller/Security.php create mode 100644 server/application/common/library/AccountSecurity.php create mode 100644 server/application/common/library/EnterpriseLicenseImage.php create mode 100644 server/application/common/library/MasterOrderCredentials.php create mode 100644 server/application/common/library/OrderQualification.php create mode 100644 tests/account_security_api.js create mode 100644 tests/account_security_lockout.js create mode 100644 tests/enterprise_cert_admin.js create mode 100644 tests/enterprise_ocr_cos.php create mode 100644 tests/master_order_credentials.php create mode 100644 tests/order_qualification.php create mode 100644 tests/order_qualification_endpoints.php create mode 100644 tests/payment_setup_navigation.mjs create mode 100644 tests/user_identity_api.js create mode 100644 yjyf-app/components/YjyfPaymentPassword.vue create mode 100644 yjyf-app/components/order/MasterCredentials.vue create mode 100644 yjyf-app/pages/mine/security.vue create mode 100644 yjyf-app/static/icons/master/menu-account-security.svg create mode 100644 yjyf-app/static/icons/menu-account-security.svg create mode 100644 yjyf-app/utils/payment-setup.mjs diff --git a/db/migrate_account_security_lockout.sql b/db/migrate_account_security_lockout.sql new file mode 100644 index 0000000..71fdd59 --- /dev/null +++ b/db/migrate_account_security_lockout.sql @@ -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 ; diff --git a/db/migrate_enterprise_admin_menus.sql b/db/migrate_enterprise_admin_menus.sql new file mode 100644 index 0000000..49ca916 --- /dev/null +++ b/db/migrate_enterprise_admin_menus.sql @@ -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; diff --git a/db/schema_account_security.sql b/db/schema_account_security.sql new file mode 100644 index 0000000..a122dab --- /dev/null +++ b/db/schema_account_security.sql @@ -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='用户企业资质认证'; diff --git a/db/schema_user_identity.sql b/db/schema_user_identity.sql new file mode 100644 index 0000000..7bec423 --- /dev/null +++ b/db/schema_user_identity.sql @@ -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; diff --git a/server/application/admin/controller/Home.php b/server/application/admin/controller/Home.php index 9a85bf9..f0f78c7 100644 --- a/server/application/admin/controller/Home.php +++ b/server/application/admin/controller/Home.php @@ -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(); diff --git a/server/application/admin/controller/MasterCert.php b/server/application/admin/controller/MasterCert.php index 0e72743..f6f7b3d 100644 --- a/server/application/admin/controller/MasterCert.php +++ b/server/application/admin/controller/MasterCert.php @@ -144,7 +144,7 @@ class MasterCert extends Backend ? "技能证书审核通过({$certName})" : "技能证书审核未通过({$certName})"; $msgContent = $status === 'pass' - ? "您上传的「{$certName}」已通过平台审核,可正常承接对应资质要求的工单。" + ? "您上传的「{$certName}」已通过平台审核,有效期内可向相关订单用户展示。" : ("您上传的「{$certName}」未通过审核,原因:" . ($auditMsg !== '' ? $auditMsg : '照片不清晰或证件不符合要求,请重新上传。')); Db::name('message')->insert([ diff --git a/server/application/admin/controller/Merchant.php b/server/application/admin/controller/Merchant.php index 5ef49e8..970b905 100644 --- a/server/application/admin/controller/Merchant.php +++ b/server/application/admin/controller/Merchant.php @@ -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(); } diff --git a/server/application/admin/controller/Order.php b/server/application/admin/controller/Order.php index c213fcd..41b7e71 100644 --- a/server/application/admin/controller/Order.php +++ b/server/application/admin/controller/Order.php @@ -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('当前工单已由该师傅承接,无需重复指派'); diff --git a/server/application/admin/controller/user/User.php b/server/application/admin/controller/user/User.php index 10e8eee..6c4db90 100755 --- a/server/application/admin/controller/user/User.php +++ b/server/application/admin/controller/user/User.php @@ -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, diff --git a/server/application/admin/view/common/meta.html b/server/application/admin/view/common/meta.html index 9c5222e..ee3d151 100755 --- a/server/application/admin/view/common/meta.html +++ b/server/application/admin/view/common/meta.html @@ -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"; + } diff --git a/server/application/admin/view/home/index.html b/server/application/admin/view/home/index.html index 1a1045d..c643daa 100644 --- a/server/application/admin/view/home/index.html +++ b/server/application/admin/view/home/index.html @@ -448,13 +448,13 @@ - +
-
商家待审核
+
企业资质待审核
企业资质核验
diff --git a/server/application/admin/view/merchant/certificates.html b/server/application/admin/view/merchant/certificates.html new file mode 100644 index 0000000..c8916e2 --- /dev/null +++ b/server/application/admin/view/merchant/certificates.html @@ -0,0 +1,8 @@ +
+
企业资质认证

个人用户和商家用户均可提交企业资质认证;认证不会改变用户类型。

+
+
diff --git a/server/application/admin/view/merchant/index.html b/server/application/admin/view/merchant/index.html index 550890f..a7ca605 100644 --- a/server/application/admin/view/merchant/index.html +++ b/server/application/admin/view/merchant/index.html @@ -1,8 +1,8 @@
- {:build_heading(null,FALSE)} + 企业业务档案及旧资质记录
+ diff --git a/server/application/admin/view/user/user/detail.html b/server/application/admin/view/user/user/detail.html index f63adea..f87b6ff 100644 --- a/server/application/admin/view/user/user/detail.html +++ b/server/application/admin/view/user/user/detail.html @@ -35,12 +35,16 @@
{$row.nickname|default=$row.username|htmlentities} {if $row.status=='normal'}正常{else/}已停用{/if} + {if !$row.identity_selected}待选择用户类型{elseif $row.user_type=='merchant'/}商家用户{else/}个人用户{/if} {if !empty($masterProfile) && $masterProfile.verify_status=='pass'} 认证师傅:{$masterProfile.realname|htmlentities} {/if} {if !empty($merchantProfile) && $merchantProfile.verify_status=='pass'} 关联企业:{$merchantProfile.name|htmlentities} {/if} + {if !empty($enterpriseCert)} + 企业资质:{if $enterpriseCert.verify_status=='pass'}已认证{elseif $enterpriseCert.verify_status=='pending'/}审核中{else/}未通过{/if} + {/if}
账号: {$row.username|htmlentities}  |  @@ -66,6 +70,32 @@
+ {if !empty($enterpriseCert)} +
+
企业资质认证
+
+ + + +
企业名称{$enterpriseCert.company_name|htmlentities}营业执照号码{$enterpriseCert.license_no|htmlentities}
法人姓名{$enterpriseCert.legal_person|default='未填写'|htmlentities}审核结果{if $enterpriseCert.verify_status=='pass'}已通过{elseif $enterpriseCert.verify_status=='pending'/}待审核{else/}已驳回:{$enterpriseCert.audit_msg|htmlentities}{/if}
+
+
+ {/if} + + {if $row.identity_selected && $row.user_type=='merchant'} +
+
商家用户资料
+
+ + + + + +
公司名称{$row.company_name|default='未填写'|htmlentities}法人姓名{$row.company_legal_person|default='未填写'|htmlentities}
法人手机号{$row.company_legal_mobile|default='未填写'|htmlentities}技术手机号{$row.company_tech_mobile|default='未填写'|htmlentities}
+
+
+ {/if} +
diff --git a/server/application/admin/view/user/user/index.html b/server/application/admin/view/user/user/index.html index dbf9654..1779620 100755 --- a/server/application/admin/view/user/user/index.html +++ b/server/application/admin/view/user/user/index.html @@ -1,5 +1,11 @@
- {:build_heading()} +
用户列表

查看个人用户、商家用户及其独立的师傅身份。

+ +
diff --git a/server/application/api/controller/Auth.php b/server/application/api/controller/Auth.php index 61ac1bd..b332e2c 100644 --- a/server/application/api/controller/Auth.php +++ b/server/application/api/controller/Auth.php @@ -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) diff --git a/server/application/api/controller/Base.php b/server/application/api/controller/Base.php index b87b53e..717b208 100644 --- a/server/application/api/controller/Base.php +++ b/server/application/api/controller/Base.php @@ -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) { diff --git a/server/application/api/controller/Master.php b/server/application/api/controller/Master.php index ccd4dfa..48d3c21 100644 --- a/server/application/api/controller/Master.php +++ b/server/application/api/controller/Master.php @@ -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, diff --git a/server/application/api/controller/Merchant.php b/server/application/api/controller/Merchant.php index f57eb10..9d2e928 100644 --- a/server/application/api/controller/Merchant.php +++ b/server/application/api/controller/Merchant.php @@ -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; } diff --git a/server/application/api/controller/Order.php b/server/application/api/controller/Order.php index cb024a3..dac7020 100644 --- a/server/application/api/controller/Order.php +++ b/server/application/api/controller/Order.php @@ -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); diff --git a/server/application/api/controller/Security.php b/server/application/api/controller/Security.php new file mode 100644 index 0000000..3f3e208 --- /dev/null +++ b/server/application/api/controller/Security.php @@ -0,0 +1,133 @@ +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('营业执照识别暂不可用,请手动填写'); + } + } +} diff --git a/server/application/api/controller/User.php b/server/application/api/controller/User.php index ed5db9c..e7c0ee5 100755 --- a/server/application/api/controller/User.php +++ b/server/application/api/controller/User.php @@ -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('暂不支持找回密码'); } /** diff --git a/server/application/common/library/AccountSecurity.php b/server/application/common/library/AccountSecurity.php new file mode 100644 index 0000000..7b3e990 --- /dev/null +++ b/server/application/common/library/AccountSecurity.php @@ -0,0 +1,56 @@ +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; + } +} diff --git a/server/application/common/library/Auth.php b/server/application/common/library/Auth.php index 03200a4..d02168f 100755 --- a/server/application/common/library/Auth.php +++ b/server/application/common/library/Auth.php @@ -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; } diff --git a/server/application/common/library/EnterpriseLicenseImage.php b/server/application/common/library/EnterpriseLicenseImage.php new file mode 100644 index 0000000..2181bb4 --- /dev/null +++ b/server/application/common/library/EnterpriseLicenseImage.php @@ -0,0 +1,44 @@ + 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; + } +} diff --git a/server/application/common/library/MasterOrderCredentials.php b/server/application/common/library/MasterOrderCredentials.php new file mode 100644 index 0000000..65108f1 --- /dev/null +++ b/server/application/common/library/MasterOrderCredentials.php @@ -0,0 +1,29 @@ + 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; + } +} diff --git a/server/application/common/library/OrderQualification.php b/server/application/common/library/OrderQualification.php new file mode 100644 index 0000000..6953925 --- /dev/null +++ b/server/application/common/library/OrderQualification.php @@ -0,0 +1,31 @@ +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')); + } +} diff --git a/server/public/assets/js/backend/merchant.js b/server/public/assets/js/backend/merchant.js index 049e291..eff20aa 100644 --- a/server/public/assets/js/backend/merchant.js +++ b/server/public/assets/js/backend/merchant.js @@ -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') ? '通过 驳回' : ''; }} + ]] + }); + $('#certs-refresh').on('click', function () { certsTable.bootstrapTable('refresh'); }); + + }, add: function () { Controller.api.bindevent(); }, diff --git a/server/public/assets/js/backend/user/user.js b/server/public/assets/js/backend/user/user.js index eedfeff..9da2c2e 100644 --- a/server/public/assets/js/backend/user/user.js +++ b/server/public/assets/js/backend/user/user.js @@ -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 '' + b.label + ''; + var cls = b.type === 'master' ? 'warning' : (b.type === 'merchant' || b.type === 'merchant_user' ? 'primary' : (b.type === 'member' ? 'info' : 'default')); + return '' + $('
').text(b.label).html() + ''; }).join(''); } }, diff --git a/tests/account_security_api.js b/tests/account_security_api.js new file mode 100644 index 0000000..2372e46 --- /dev/null +++ b/tests/account_security_api.js @@ -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; }); diff --git a/tests/account_security_lockout.js b/tests/account_security_lockout.js new file mode 100644 index 0000000..7e10d39 --- /dev/null +++ b/tests/account_security_lockout.js @@ -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; }); diff --git a/tests/enterprise_cert_admin.js b/tests/enterprise_cert_admin.js new file mode 100644 index 0000000..bf81902 --- /dev/null +++ b/tests/enterprise_cert_admin.js @@ -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('商家用户')); + 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('商家用户')); + 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; }); diff --git a/tests/enterprise_ocr_cos.php b/tests/enterprise_ocr_cos.php new file mode 100644 index 0000000..d87568c --- /dev/null +++ b/tests/enterprise_ocr_cos.php @@ -0,0 +1,18 @@ +$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]); +} diff --git a/tests/master_order_credentials.php b/tests/master_order_credentials.php new file mode 100644 index 0000000..fd53bfb --- /dev/null +++ b/tests/master_order_credentials.php @@ -0,0 +1,30 @@ + 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"; diff --git a/tests/order_qualification.php b/tests/order_qualification.php new file mode 100644 index 0000000..ba4bf8d --- /dev/null +++ b/tests/order_qualification.php @@ -0,0 +1,19 @@ + '电工证', '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"; diff --git a/tests/order_qualification_endpoints.php b/tests/order_qualification_endpoints.php new file mode 100644 index 0000000..4bf560f --- /dev/null +++ b/tests/order_qualification_endpoints.php @@ -0,0 +1,50 @@ + 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"; +} diff --git a/tests/payment_setup_navigation.mjs b/tests/payment_setup_navigation.mjs new file mode 100644 index 0000000..095b885 --- /dev/null +++ b/tests/payment_setup_navigation.mjs @@ -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'); diff --git a/tests/user_identity_api.js b/tests/user_identity_api.js new file mode 100644 index 0000000..60da12e --- /dev/null +++ b/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; }); diff --git a/yjyf-app/components/YjyfPaymentPassword.vue b/yjyf-app/components/YjyfPaymentPassword.vue new file mode 100644 index 0000000..4144d6a --- /dev/null +++ b/yjyf-app/components/YjyfPaymentPassword.vue @@ -0,0 +1,37 @@ + + + diff --git a/yjyf-app/components/master/MasterHallView.vue b/yjyf-app/components/master/MasterHallView.vue index 7845117..62f1af9 100644 --- a/yjyf-app/components/master/MasterHallView.vue +++ b/yjyf-app/components/master/MasterHallView.vue @@ -213,6 +213,11 @@ + + 资质要求:{{ o.qual_req }} + 暂无有效认证证书 + 去上传证书 + 工单要求 {{ o.remark }} @@ -238,9 +243,10 @@ + {{ o.price_type === 'quote' ? '暂不可报价' : '暂不可接单' }} 立即报价 @@ -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 @@ diff --git a/yjyf-app/components/user/UserMineView.vue b/yjyf-app/components/user/UserMineView.vue index 08aa6d8..7e82440 100644 --- a/yjyf-app/components/user/UserMineView.vue +++ b/yjyf-app/components/user/UserMineView.vue @@ -103,6 +103,10 @@ + + 账号安全 + + @@ -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; diff --git a/yjyf-app/pages.json b/yjyf-app/pages.json index d9b428b..8b4eda5 100644 --- a/yjyf-app/pages.json +++ b/yjyf-app/pages.json @@ -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": { diff --git a/yjyf-app/pages/index/index.vue b/yjyf-app/pages/index/index.vue index 91db0fa..928b5c1 100644 --- a/yjyf-app/pages/index/index.vue +++ b/yjyf-app/pages/index/index.vue @@ -22,21 +22,38 @@ + + + 请选择用户类型 + 请选择您的使用身份,确认后不可自行修改 + + 个人用户家庭或个人使用 + + + 商家用户商家或企业使用 + + + + - diff --git a/yjyf-app/pages/order/create.vue b/yjyf-app/pages/order/create.vue index db43cea..5f49ab8 100644 --- a/yjyf-app/pages/order/create.vue +++ b/yjyf-app/pages/order/create.vue @@ -226,11 +226,14 @@ @update:visible="showCreateRegion = $event" @confirm="onCreateRegionDrawerConfirm" /> +