123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625 |
- <?php
- // +----------------------------------------------------------------------
- // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
- // +----------------------------------------------------------------------
- // | Author: 萤火科技 <admin@yiovo.com>
- // +----------------------------------------------------------------------
- declare (strict_types=1);
- namespace app\store\model;
- use app\common\library\helper;
- use app\common\model\ShopIdentity;
- use app\common\model\Shops as ShopModel;
- use app\common\model\user\CommissionsDetail;
- use Exception;
- use think\facade\Db;
- use think\facade\Log;
- use app\common\model\chef\ChefAreas as RegionModel;
- use app\store\model\user\BonusHistory;
- use app\common\model\store\Setting as SettingModel;
- use app\store\model\user\CommissionSteps;
- use app\common\enum\Setting as SettingEnum;
- use app\store\model\Order as OrderModel;
- /**
- * 门店模型
- * Class Goods
- * @package app\api\model
- */
- class Shops extends ShopModel
- {
- /**
- * 隐藏字段
- * @var array
- */
- public $hidden = [
- 'update_time',
- 'is_delete'
- ];
- // 追加字段
- protected $append = ['region'];
- public function getRegionAttr($value, $data)
- {
- $regionNames = $this->getRegionNames($data);
- return "{$regionNames['province']}{$regionNames['city']}";
- }
- public function getRegion($info)
- {
- if (empty($info))return '';
- $regionNames = $this->getRegionNames($info->toArray());
- return "{$regionNames['province']}{$regionNames['city']}{$regionNames['region']}";
- }
- /**
- * 获取省市区名称
- * @param array $data
- * @return mixed
- */
- private function getRegionNames(array $data)
- {
- static $dataset = [];
- $id = $data[$this->getPk()];
- if (!isset($dataset[$id])) {
- $dataset[$id] = [
- 'province' => RegionModel::getNameById($data['province_id']??0),
- 'city' => RegionModel::getNameById($data['city_id']??0),
- 'region' => RegionModel::getNameById($data['region_id']??0),
- ];
- }
- return $dataset[$id];
- }
- public static function getList($conditions){
- $model = new self();
- $from = 1633017600 ;$to = time();
- if ($conditions and count($conditions)){
- foreach ($conditions as $key=>$c){
- if ($key == 'is_delete'){
- $model = $model->where($key,$c);
- }
- if ($key == "shop_id" && $c > 0){
- $model = $model->where($key,$c);
- }
- if ($key == "shop_name" && trim($c,' ')){
- $model = $model->whereLike($key,'%'.$c.'%');
- }
- if ($key == 'contact_mobile' && trim($c,' ')){
- $model = $model->whereLike($key,'%'.$c.'%');
- }
- if ($key == "region_id" && $c>0 && trim($c)){
- $model = $model->where($key,$c);
- }
- if ($key == "city_id" && $c>0 && trim($c)){
- $model = $model->where($key,$c);
- }
- if ($key == "province_id" && $c>0 && trim($c)){
- $model = $model->where($key,$c);
- }
- if ($key =='betweenTime'){
- Log::debug("bt::".json_encode($c));
- if (isset($c[0]) && $c[0] && isset($c[1]) && $c[1]){
- $times = between_time($c);
- $from = $times['start_time'];
- $to = $times['end_time'] + 86400;
- }
- }
- }
- if ($from && $to){
- $model = $model->whereBetweenTime('create_time',$from,$to);
- }
- }
- $model = $model->withCount(['sellers' => function($query) {
- $query->where('role',\app\api\model\User::SHOP_SELLER);
- }])
- /* ->withSum('storeSales','total_price')
- ->withSum('storeSalesSub','distributor_total_money')*/
- ->withSum(['storeCommission'=>function($query){
- $query->where('clearing_status',1);
- }],'clearing_money')
- ->withCount(['shopConsumers'=>function($query) {
- $query->whereIn('role',[\app\api\model\User::NORMAL_USER,\app\api\model\User::COMMISSION_USER]);
- }]);
- $res = $model->order('shop_id','desc')->paginate(15)->toArray();
- return $res;
- }
- public static function shopBossUserId($shopId){
- $shop = self::where('shop_id',$shopId)->find();
- return $shop?$shop->boss_user_id:0;
- }
- public static function shopMgUserId($shopId){
- $shop = self::where('shop_id',$shopId)->find();
- return $shop?$shop->manager_user_id:0;
- }
- /**
- * 店员统计
- * @return \think\model\relation\HasMany
- */
- public function sellers(): \think\model\relation\HasMany
- {
- return $this->hasMany(User::class,'shop_id','shop_id');
- }
- /**
- * 店铺销售额
- * @return \think\model\relation\HasMany
- */
- public function storeSales(): \think\model\relation\HasMany
- {
- return $this->hasMany(OrderGoods::class,'shop_id','shop_id');
- }
- /**
- * 店铺销售额
- * @return \think\model\relation\HasMany
- */
- public function storeSalesSub(): \think\model\relation\HasMany
- {
- return $this->hasMany(OrderGoods::class,'shop_id','shop_id');
- }
- /**
- * 统计店铺总佣金
- * @return \think\model\relation\HasMany
- */
- public function storeCommission(): \think\model\relation\HasMany
- {
- return $this->hasMany(CommissionsDetail::class,'shop_id','shop_id');
- }
- /**
- * 门店关联消费者
- * @return \think\model\relation\HasMany
- */
- public function shopConsumers(): \think\model\relation\HasMany
- {
- return $this->hasMany(User::class,'bind_shop_id','shop_id');
- }
- /**
- * 门店关联门店身份
- * @return \think\model\relation\HasMany
- */
- public function shopIdentity(): \think\model\relation\HasMany
- {
- return $this->hasMany(ShopIdentity::class,'shop_id','shop_id');
- }
- /**
- * @param $data
- * @param bool $needShopId
- * @return bool|array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function add($data,$needShopId =false){
- if (isset($data['boss_mobile']) && $data['boss_mobile'] && isset($data['manager_mobile']) && $data['manager_mobile'] && ($data['boss_mobile'] == $data['manager_mobile'])){
- Log::error('boss:'.$data['boss_mobile'].',manager:'.$data['manager_mobile']);
- $this->error = '店老板与店长手机号不能一样哦';
- return false;
- }
- // 店老板不能同时在其他门店担任职务 不能是分销员(除老板身份外)
- if (!empty($data['boss_mobile'])) {
- $bossOld = User::where('mobile', $data['boss_mobile'])->find();
- if ($bossOld && $bossOld['role'] > User::SHOP_BOSS){
- $this->error = '同一账号不支持多种身份哦';
- return false;
- }
- if ($bossOld){
- $data['boss_nick_name'] = $bossOld['nick_name'];
- }
- }
- // 店长不能同时在其他门店担任职务 不能是分销员
- if (!empty($data['manager_mobile']) && User::where('mobile', $data['manager_mobile'])->where('role', '>', User::NORMAL_USER)
- ->where('role', '<=', User::COMMISSION_USER)->find()) {
- $this->error = '同一账号不支持多种身份';
- return false;
- }
- $manager_user_id = 0;
- Db::startTrans();
- try {
- $model = new self();
- $model->shop_name = $data['shop_name']??"";
- $model->addr = $data['addr']??"";
- $model->contact = $data['contact'] ?? '';
- $model->contact_mobile = $data['contact_mobile'] ?? '';
- $model->province_id = $data['province_id']??0;
- $model->city_id = $data['city_id']??0;
- $model->region_id = $data['region_id']??0;
- $model->detail = $data['detail']??'';
- $model->is_virtual = $data['is_virtual']??0;
- $model->save();
- $shopId = $model->shop_id;
- Log::error("add shop_id::".json_encode($shopId));
- if (!empty($data['is_virtual']) && $data['is_virtual'] == Shops::SHOP_TYPE_VIRTUAL) { // 虚拟门店 @v1.3.6
- // 生成虚拟的店老板手机号
- $boss_mobile = User::makeVirtualMobile(1);
- if (!$boss_mobile) {
- $this->error = '店老板手机号存在,请重试';
- return false;
- }
- $data['boss_mobile'] = $boss_mobile;
- $data['boss_nick_name'] = User::makeVirtualName('系统店老板');
- $boss_user_id = User::createUserByMobile($data['boss_nick_name'],$data['boss_mobile'],$shopId,User::SHOP_BOSS);
- // 生成虚拟的默认店员手机号
- $staff_mobile = User::makeVirtualMobile(2);
- if (!$staff_mobile) {
- $this->error = '店员手机号存在,请重试';
- return false;
- }
- $staf_nick_name = User::makeVirtualName('系统店员');;
- $staff_user_id = User::createUserByMobile($staf_nick_name,$staff_mobile,$shopId,User::SHOP_SELLER);
- $model->contact = User::makeVirtualName('系统店面联系人');
- $model->contact_mobile = User::makeVirtualMobile(3);
- } else { // 原有逻辑
- $boss_user_id = User::createUserByMobile($data['boss_nick_name'],$data['boss_mobile'],$shopId,User::SHOP_BOSS, $shopId);
- if ($boss_user_id === false){
- throw new \Exception('系统繁忙', 500);
- }
- if (isset($data['manager_mobile']) && $data['manager_mobile']){
- $managerNickname = $data['manager_nick_name']??$data['manager_mobile'];
- $manager_user_id = User::createUserByMobile($managerNickname,$data['manager_mobile'],$shopId,User::SHOP_MG, $shopId);
- if ($manager_user_id === false){
- throw new \Exception('系统繁忙', 500);
- }
- }
- }
- Log::error('boss_user::'.json_encode($boss_user_id));
- Log::error('manager_user_id::'.json_encode($manager_user_id));
- $model->boss_user_id = $boss_user_id;
- $model->manager_user_id = $manager_user_id;
- $model->save();
- Db::commit();
- if ($needShopId){
- return ['shop_id'=>$shopId,'boss_user_id'=>$boss_user_id,'manager_user_id'=>$manager_user_id,'boss_nick_name'=>$data['boss_nick_name']];
- }
- return true;
- } catch (\Exception $e){
- Db::rollback();
- Log::error(__METHOD__.$e->getMessage());
- $this->error = $e->getMessage();
- return false;
- }
- }
- public static function detail($id){
- return self::with(['bossUser'=>function($query){
- $query->field('user_id,nick_name,mobile');
- },'mgUser'=>function($query){
- $query->field('user_id,nick_name,mobile');
- }, 'shopIdentity' => function($query) {
- $query->field('shop_id,role_id,fc_percent');
- }])->find($id);
- }
- public function bossUser(){
- return $this->hasOne(User::class, 'user_id','boss_user_id');
- }
- public function mgUser(){
- return $this->hasOne(User::class, 'user_id','manager_user_id');
- }
- /**
- * 编辑门店
- * @param $data
- * @return bool|int
- */
- public function edit($data){
- Db::startTrans();
- try {
- $shop = self::find($data['shop_id']);
- $shop->shop_name = $data['shop_name'];
- $shop->addr = $data['addr']??"";
- $shop->contact = $data['contact']??'';
- $shop->contact_mobile = $data['contact_mobile'];
- $shop->province_id = $data['province_id']??0;
- $shop->city_id = $data['city_id']??0;
- $shop->region_id = $data['region_id']??0;
- $shop->detail = $data['detail']??'';
- $shop->save();
- Db::commit();
- return true;
- }catch (\Exception $e){
- Db::rollback();
- Log::error(__METHOD__.',变更shop_id::'.$data['shop_id'].','.$e->getMessage());
- $this->error = $e->getMessage();
- return false;
- }
- }
- /**
- * 设置门店自提开关
- */
- public function setPickup(array $data){
- $this->is_pickup = $data['is_pickup'];
- return $this->save();
- }
- public function shopPerform($shopId,$from,$to): array
- {
- $res = self::field('shop_id,create_time')
- ->withCount(['straightUsersCnt'=>function($query) use ($from,$to){
- $query->whereBetweenTime('create_time',$from,$to);
- }])
- /* ->withCount(['recOrdersCnt'=>function($query) use ($from,$to){
- $query->whereBetweenTime('create_time',$from,$to);
- }])
- ->withSum(['recOrdersCnt'=>function($query) use ($from,$to){
- $query->whereBetweenTime('create_time',$from,$to);
- }],'total_pay_price')*/
- ->withSum(['commissionTotal'=>function($query) use ($from,$to){
- $query->where('clearing_status',1)->whereBetweenTime('create_time',$from,$to);
- }],'clearing_money')->where('shop_id',$shopId)->find()->toArray();
- $staff = User::where('shop_id',$shopId)->column('user_id');
- $res['straight_users_cnt_count'] = User::whereIn('upper_user_id',$staff)->where('bind_shop_id',$shopId)->count();
- //$res['rec_orders_cnt_sum'] = $this->getRecOrdersAllSum($shopId,$from,$to);
- $res['rec_orders_cnt_sum'] = OrderGoods::sumShopGiveOutOrder($shopId,$from,$to);
- $res['rec_orders_cnt_count'] = $this->getRecOrdersAllCnt($shopId,$from,$to);
- $res['shop_bonus'] = BonusHistory::bonusAmount($shopId, 2); // 店内
- return $res;
- }
- public function straightUsersCnt(){
- return $this->hasMany(User::class,'bind_shop_id','shop_id');
- }
- public function recOrdersCnt(){
- return $this->hasMany(OrderGoods::class,'shop_id','shop_id');
- }
- public function commissionTotal(){
- return $this->hasMany(CommissionsDetail::class,'shop_id','shop_id');
- }
- /**
- * 单店铺的销售额
- * @param $shopId
- * @param $from
- * @param $to
- * @return float
- */
- /* public function getRecOrdersAllSum($shopId,$from,$to){
- $orderGoodsId = CommissionsDetail::where('shop_id',$shopId)->whereBetweenTime('create_time',$from,$to)
- ->column('order_goods_id');
- $orderGoodsId = array_unique($orderGoodsId);
- $temp = helper::bcsub(OrderGoods::whereIn('order_goods_id',$orderGoodsId)->whereBetweenTime('create_time',$from,$to)
- ->sum('total_price'),OrderGoods::whereIn('order_goods_id',$orderGoodsId)->whereBetweenTime('create_time',$from,$to)
- ->sum('distributor_total_money'),4);
- return helper::bcsub($temp ,OrderGoods::whereIn('order_goods_id',$orderGoodsId)->whereBetweenTime('create_time',$from,$to)
- ->sum('coupon_money'),4);
- }*/
- /**
- * 单店铺的订单数量
- * @param $shopId
- * @param $from
- * @param $to
- * @return int
- */
- public function getRecOrdersAllCnt($shopId,$from,$to){
- $orderIds = CommissionsDetail::where('shop_id',$shopId)->whereBetweenTime('create_time',$from,$to)
- ->column('order_id');
- return count(array_unique($orderIds));
- }
- /**
- * 顾客上级是店员时,推广费用最大占比
- * 推广费用最大占比 = 顾客购买优惠比例 + 店员最高阶梯佣金比例 + 店内其他身份最高阶梯佣金比例+门店日常佣金总比例
- *
- * 顾客上级是分销员时,推广费用最大占比
- * 推广费用最大占比 = 顾客购买优惠比例 + 一级佣金比例 + 二级佣金比例
- */
- public function getRecMaxPercent($shopId) {
- $distributor_percent = SettingModel::getItem(SettingEnum::DISTRIBUTOR)['shopping_discount']; // 顾客购买优惠比例
- $shop = self::detail($shopId);
- $staff_max_percent = CommissionSteps::where('shop_id', $shopId)->where('role', User::SHOP_SELLER)->max('bonus_ratio') ?? 0;
- $boss_max_percent = CommissionSteps::where('shop_id', $shopId)->where('role', User::SHOP_BOSS)->max('bonus_ratio') ?? 0;
- $manager_max_percent = CommissionSteps::where('shop_id', $shopId)->where('role', User::SHOP_MG)->max('bonus_ratio') ?? 0;
- $chef_max_percent = CommissionSteps::where('shop_id', $shopId)->where('role', User::SHOP_CHEF)->max('bonus_ratio') ?? 0;
- $chef_count = User::where('role', User::SHOP_CHEF)->where('shop_id', $shopId)->count();
- // 厨师佣金百分比
- $chef_percent = ShopIdentity::where('shop_id', $shopId)->where('role_id', User::SHOP_CHEF)->value('fc_percent') ?? 0;
- $chef_percent_total = $chef_count * $chef_percent;
- // 门店日常佣金百分比
- $shop_percent_total = $shop['staff_percent'] + $shop['manager_percent'] + $shop['boss_percent'] + $chef_percent_total;
- $distributorGradeSetting = SettingModel::getItem(SettingEnum::DISTRIBUTOR_GRADE)['distributor'][2];
- $distributorStepSetting = SettingModel::getItem(SettingEnum::DISTRIBUTOR_STEP)['distributor'][1];
- $staff_rec_max_percent = $distributor_percent + $staff_max_percent + $boss_max_percent + $manager_max_percent + $chef_max_percent + $shop_percent_total;
- $commission_rec_max_percent = $distributor_percent + $distributorGradeSetting['first_commission'] + $distributorGradeSetting['second_commission'] + $distributorStepSetting['bonus_ratio'];
- return [$staff_rec_max_percent, $commission_rec_max_percent];
- }
- //日基础数据统计模块
- public function monthlyBonusTotalMoney(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusExpr(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusGoods(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusPay(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusCoupon(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusOrder(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusBoss(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusMg(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- public function monthlyBonusSel(){
- return $this->hasMany(ShopsDailySalesSt::class,'shop_id','shop_id');
- }
- //关联月度奖励金统计模块
- public function monthBonusTotal(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusBossTotal(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusBoss(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusMgTotal(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusMg(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusSellerTotal(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- public function monthBonusSellerl(){
- return $this->hasMany(ShopsMonthlyBonusSt::class,'shop_id','shop_id');
- }
- //获取门店销售及佣金统计
- public function getSaleList($conditions){
-
- $model = new Shops();
- $from = 1633017600;
- $to = time();
- $city_id_arr = [];
- $regin = new RegionModel;
- if ($conditions and count($conditions)){
- foreach ($conditions as $key=>$c){
-
- if ($key == "shop_name" && trim($c,' ')){
- $model = $model->whereLike($key,'%'.$c.'%');
- }
- if($key=='city_name' && trim($c,' ')){
- $city_id_arr = $regin->where('name','like','%'.$c.'%')->where('level',2)->column("id");
- }
- if ($key =='betweenTime'){
- if (isset($c[0]) && $c[0] && isset($c[1]) && $c[1]){
- $times = between_time_format($c);
- $from = $times['start_time'];
- $to = $times['end_time'];
- }
- }
- }
- }
- if($city_id_arr){
- $model = $model->where("city_id",'in',$city_id_arr);
- }
- $model = $model->with(['storeCommission'=>function($query) use ($from,$to){
- $query->where('clearing_status','in',[0,1])->whereBetweenTime('order_create_time',$from,$to);
- }]);
- $order = new OrderModel;
- $list = $model->order('shop_id','desc')->paginate(15)->each(function($item)use ($order){
- $order_id_arr = [];
- $order_amount = 0;
-
- $boss_amount = 0;
- $boss_amount_js = 0;
- $dz_amount = 0;
- $dz_amount_js = 0;
- $dy_amount = 0;
- $dy_amount_js = 0;
-
- foreach($item['storeCommission'] as $r){
- $order_id_arr[] = $r['order_id'];
- if($r['role']==2){ //店老板
- $boss_amount += $r['clearing_money'];
- if($r['clearing_status']==1){
- $boss_amount_js +=$r['clearing_money'];
- }
- }
- if($r['role']==3){ //店长
- $dz_amount +=$r['clearing_money'];
- if($r['clearing_status']==1){
- $dz_amount_js +=$r['clearing_money'];
- }
- }
- if($r['role']==4){ //店员
- $dy_amount +=$r['clearing_money'];
- if($r['clearing_status']==1){
- $dy_amount_js +=$r['clearing_money'];
- }
- $order_amount +=$r['order_sale_volume'];
- }
- }
- $item['boss_amount'] = helper::bcadd($boss_amount,0,2);
- $item['boss_amount_js'] = helper::bcadd($boss_amount_js,0,2);
- $item['dz_amount'] = helper::bcadd($dz_amount,0,2);
- $item['dz_amount_js'] = helper::bcadd($dz_amount_js,0,2);
- $item['dy_amount'] = helper::bcadd($dy_amount,0,2);
- $item['dy_amount_js'] = helper::bcadd($dy_amount_js,0,2);
- $order_id_arr = array_unique($order_id_arr);
- $item['order_id_arr'] = $order_id_arr;
- $item['order_cnt'] = count($order_id_arr);
- $item['order_amount'] = helper::bcadd($order_amount,0,2);
- })->toArray();
- return $list;
- }
- }
|