Files
2026-09-01 22:15:50 +08:00

338 lines
11 KiB
PHP

<?php
declare (strict_types=1);
namespace app\store\model;
use app\common\model\UserCoupon as UserCouponModel;
use app\common\service\Order as OrderService;
use app\store\model\GoodsCoupon as GoodsCouponModel;
use app\store\model\store\UserRole;
use think\Session;
use app\common\model\Merchant as MerchantModel;
use app\store\model\Goods as GoodsModel;
use app\store\model\GoodsSku as GoodsSkuModel;
use app\store\model\User as FrontUserModel;
use app\store\model\store\User as UserModel;
use app\store\model\merchant\BalanceLog as BalanceLogModel;
use app\common\model\merchant\MerchantOrder as MerchantOrderModel;
use app\store\service\store\User as StoreUserService;
use app\common\enum\merchant\balanceLog\Scene as SceneEnum;
use app\common\library\helper;
// 生成订单
use app\store\model\Coupon as CouponModel;
/**
* 商户模型
* Class StoreUser
* @package app\store\model
*/
class Merchant extends MerchantModel
{
// 充值类型枚举: 余额
const RECHARGE_TYPE_BALANCE = 'balance';
/**
* 获取商户列表
* @param array $data
* @return \think\Paginator
* @throws \think\exception\DbException
*/
public function getList($data = [])
{
return $this->with(['referrer'])
->order(['create_time' => 'desc'])
->where($data)
->paginate(15);
}
/**
* 新增记录
* @param $data
* @param array $user
* @return bool|false|int
* @throws \think\exception\DbException
*/
public function add($data, $user = [])
{
if (empty($data['name'])) {
$this->error = '请填写商户名称';
return false;
}
if (floatval($user['level']) >= 3) {
$this->error = '你没有创建代理商的权限';
return false;
}
$this->startTrans();
try {
$data['orgNo'] = $this->createNo();
$data['appKey'] = $this->suiji(30);
$data['store_user_id'] = $user['store_user_id'];
$data['parent_merchant_id'] = $user['merchant_id'];
$data['level'] = floatval($user['level']) + 1;
$data['store_id'] = self::$storeId;
$data = array_merge($data, $this->secretKey());
$this->save($data);
//创建商户登录账号
$userModel = new UserModel();
$newData['user_name'] = $data['name'];
$newData['password'] = encryption_hash('123456');
$newData['real_name'] = $data['name'];
$newData['status'] = 1;
$newData['is_super'] = 0;
$newData['store_id'] = self::$storeId;
//账号层级
$newData['level'] = $data['level'];
$newData['merchant_id'] = $this->merchant_id;
$userModel->save($newData);
// 新增角色关系记录
UserRole::increased((int)$userModel['store_user_id'], [10014]);
$this->commit();
return true;
} catch (\Exception $e) {
$this->error = $e->getMessage();
$this->rollback();
return false;
}
}
/*返回随机数*/
public function suiji($digit=12){
$a = "abcdefghijklmnopqrstuvwxyz";
$x = strlen($a)-1;
$html = "";
for($i=1;$i<=$digit;$i++) {
$rand = rand(1,$x);
$html .= substr($a,$rand,1);
if($i == 1){//某些语言变量首字母不能是数字
$a .= "0123456789";
$x = strlen($a)-1;
}
}
return $html;
}
/*返回随机数*/
public function secretKey(){
// 生成 RSA 密钥对
$config = array(
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
$keyPair = openssl_pkey_new($config);
// 提取私钥
openssl_pkey_export($keyPair, $privateKey);
// 提取公钥
$keyDetails = openssl_pkey_get_details($keyPair);
$publicKey = $keyDetails['key'];
return ['privateKey'=>base64_encode($privateKey), 'publicKey'=>base64_encode($publicKey)];
}
/** 生成编号
* @param $prefix
* @return string
*/
public static function createNo($prefix = 'S'): string
{
return $prefix . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
/**
* 更新记录
* @param array $data
* @return bool
* @throws \think\exception\DbException
*/
public function edit($data)
{
if (empty($data['name'])) {
$this->error = '请填写商户名称';
return false;
}
$this->startTrans();
try {
// 更新管理员记录
$this->save($data);
$this->commit();
return true;
} catch (\Exception $e) {
$this->error = $e->getMessage();
$this->rollback();
return false;
}
}
/**
* 软删除
* @return false|int
*/
public function setDelete()
{
return $this->delete();
}
/**
* 用户数据统计
* @param $user
* @param $get
* @return \think\Paginator
* @throws \think\exception\DbException
*/
public function getMerchantStatistics($user,$get = [])
{
$filter = [];
if($user['is_super'] == 0){
$merchant_idArr = $user['merchant_id']?json_decode($user['merchant_id'],true):[];
$filter[] = ['a.merchant_id', 'in', $merchant_idArr];
}
if(isset($get['name'])){
$filter[] = ['a.name', 'like', '%'.$get['name'].'%'];
}
$times = [];
if(isset($get['betweenTime'])) {
$times = between_time($get['betweenTime']);
}
$and = "";
if(isset($times['start_time'])){
$and .= " and create_time >= '".$times['start_time']."' ";
}
if(isset($times['end_time'])){
$and .= " and create_time < '".($times['end_time'] + 86400)."' ";
}
$and2 = " and create_time >= '".strtotime(date('Y-m-d'))."' and create_time < '".strtotime(date('Y-m-d').' 23:59:59')."' ";
return $this->alias('a')
->field('a.*, (select IFNULL(sum(amount),0) from yoshop_order where merchant_id = a.merchant_id and order_status = 20 '.$and.') as amount, (select IFNULL(sum(amount),0) from yoshop_order where merchant_id = a.merchant_id and order_status = 20 '.$and2.') as today')
->order(['a.create_time' => 'desc'])
->where($filter)
->paginate(15);
}
/**
* 商户充值
* @param string $target 充值类型
* @param array $data 表单数据
* @return bool
*/
public function recharge(string $target, array $data)
{
// 当前操作人用户名
$storeUserName = StoreUserService::getLoginInfo()['user']['user_name'];
if ($target === self::RECHARGE_TYPE_BALANCE) {
return $this->rechargeToBalance($storeUserName, $data['balance']);
}
return false;
}
/**
* 商户充值:余额
* @param string $storeUserName
* @param array $data
* @return bool
*/
private function rechargeToBalance(string $storeUserName, array $data)
{
if (!isset($data['money']) || $data['money'] === '' || $data['money'] < 0) {
$this->error = '请输入正确的金额';
return false;
}
// 判断充值方式,计算最终金额
if ($data['mode'] === 'inc') {
$diffMoney = $data['money'];
} elseif ($data['mode'] === 'dec') {
$diffMoney = -$data['money'];
} else {
$diffMoney = helper::bcsub($data['money'], $this['balance']);
}
// 更新记录
$this->transaction(function () use ($storeUserName, $data, $diffMoney) {
// 更新账户余额
static::setIncBalance((int)$this['merchant_id'], (float)$diffMoney);
// 新增余额变动记录
BalanceLogModel::add(SceneEnum::ADMIN, [
'merchant_id' => $this['merchant_id'],
'money' => (float)$diffMoney,
'remark' => $data['remark'],
], [$storeUserName]);
});
return true;
}
/**
* 代理商发券
* @param array $data 表单数据
* @return bool
*/
public function sendCoupon(array $data)
{
return $this->sendCouponAction($data);
}
/**
* 代理商发券 执行
* @param array $data
* @return bool
*/
private function sendCouponAction(array $data)
{
if (!isset($data['goods_id']) || $data['goods_id'] === '' || $data['goods_id'] < 0) {
$this->error = '请选择发券商品';
return false;
}
$goods = GoodsModel::detail($data['goods_id']);
if(empty($goods['goods_id'] ?? '')){
$this->error = '对应发券商品不存在';
return false;
}
if($goods['oilCardType'] != 'coupon'){
$this->error = '此商品不是优惠券商品';
return false;
}
if (!isset($data['phone']) || $data['phone'] === '' || $data['phone'] < 0) {
$this->error = '请输入用户手机号';
return false;
}
$user = FrontUserModel::detail(['mobile' => $data['phone']]);
if(empty($user['user_id'] ?? '')){
$this->error = '未找到此手机号对应的用户';
return false;
}
// 更新记录
$this->transaction(function () use ($data, $goods, $user) {
// 生成发券记录
MerchantOrderModel::add([
'order_no' => $this->orderNo(),
'order_type' => 'coupon',
'order_status' => 30,
'total_price' => $goods['goods_price_max'],
'order_price' => $goods['goods_price_max'],
'goods_id' => $goods['goods_id'],
'user_id' => $user['user_id'],
'merchant_id' => $this['merchant_id'],
'admin_remark' => $data['remark'] ?? '',
]);
// 发放优惠券
$coupons = GoodsCouponModel::getCouponList($goods['goods_id'])->toArray();
if($coupons && is_array($coupons)) {
foreach ($coupons as $item) {
$coupon = CouponModel::detail($item['coupon_id']);
for ($i=0;$i<$item['send_num'];$i++){
$userCouponModel = new UserCouponModel();
$userCouponModel->add($user['user_id'], $coupon);
}
}
}
});
return true;
}
/**
* 生成订单号
* @return string
*/
public function orderNo(): string
{
return OrderService::createOrderNo();
}
}