UserBillRepository.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author xaboy
  6. * @day 2020-05-07
  7. *
  8. *
  9. */
  10. namespace app\common\repositories\user;
  11. use app\common\dao\BaseDao;
  12. use app\common\dao\user\UserBillDao;
  13. use app\common\enum\user\UserBillEnum;
  14. use app\common\model\user\UserBill;
  15. use app\common\repositories\BaseRepository;
  16. use app\common\repositories\store\order\StoreOrderRepository;
  17. use app\entity\data\user\UserBillEntity;
  18. use app\entity\data\user\UserEntity;
  19. use app\utils\ArrayUtil;
  20. use think\db\exception\DbException;
  21. use think\exception\ValidateException;
  22. use think\facade\Cache;
  23. use think\facade\Db;
  24. use think\Model;
  25. /**
  26. * Class UserBillRepository
  27. * @package app\common\repositories\user
  28. * @author xaboy
  29. * @day 2020-05-07
  30. * @mixin UserBillDao
  31. */
  32. class UserBillRepository extends BaseRepository
  33. {
  34. /**
  35. * @var UserBillDao
  36. */
  37. protected $dao;
  38. /**
  39. * UserBillRepository constructor.
  40. * @param UserBillDao $dao
  41. */
  42. public function __construct(UserBillDao $dao)
  43. {
  44. $this->dao = $dao;
  45. }
  46. public function userList($where, $uid, $page, $limit)
  47. {
  48. $where['uid'] = $uid;
  49. $query = $this->dao->search($where)->order('create_time DESC')
  50. ->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
  51. $query->whereLike('status', $where['status']);
  52. });
  53. $count = $query->count();
  54. $list = $query->setOption('field', [])->field('bill_id,pm,title,number,balance,mark,create_time,status,order_sn,mer_id')->page($page, $limit)->select();
  55. return compact('count', 'list');
  56. }
  57. public function getList($where, $page, $limit)
  58. {
  59. if ($where["city"]){
  60. if ($where["city"] == '直辖区') {
  61. $city_id = Db::name("user_city")->where("city_name", $where["province"])->value("city_id");
  62. } else {
  63. $city_id = Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
  64. }
  65. $where['city_id'] = $city_id;
  66. unset($where["city"]);
  67. }
  68. $query = $this->dao->searchJoin($where)->order('a.create_time DESC');
  69. $count = $query->count();
  70. $list = $query->page($page, $limit)->select();
  71. $order_type = 1;
  72. // dump($list);
  73. // return 1;
  74. $souxufee = systemConfig('yanglao');
  75. foreach ($list as &$v){
  76. if ($v["source"]==1) {
  77. $vorder_merchant=Db::name("order_merchant")->where(["out_trade_no"=>$v["order_sn"]])->find();
  78. $v["mer_id"]=$vorder_merchant["mer_id"];
  79. //消费金额
  80. $v["total_price"]=$vorder_merchant["money"];
  81. //可分佣金总额
  82. $v["extension_one"]=$vorder_merchant["available"];
  83. //分账给服务商的钱
  84. $v["service_money"]=$vorder_merchant["service_money"];
  85. //养老金
  86. $v["pension"]=$vorder_merchant["pension"];
  87. //刷卡手续费
  88. $v["swipe_fee"]=$vorder_merchant["swipe_fee"];
  89. $v["uid"]=$vorder_merchant["uid"];
  90. if ($vorder_merchant["uid"] > 0) {
  91. $users=Db::name("user")->where("uid",$vorder_merchant["uid"])->field("nickname,phone")->find();
  92. $v["nickname"]=$users["nickname"];
  93. $v["phone"]=$users["phone"];
  94. } else {
  95. $v["nickname"]=$vorder_merchant["nickname"]."【".($vorder_merchant["trade_type"]=="WX"?"微信用户":"支付宝用户")."】";
  96. $v["phone"]=$vorder_merchant["pay_user_id"];
  97. }
  98. } else {
  99. if(strpos($v['order_sn'],'channel') !== false || strpos($v['order_sn'],'sIC') !== false ){
  100. //渠道商
  101. $channel_order = Db::name('channel_order') -> where('order_no',$v['order_sn']) -> find();
  102. $v["mer_id"]='';
  103. $v["total_price"]=$channel_order["pay_price"];
  104. $v["extension_one"]=0;
  105. $users=Db::name("user")->where("uid",$channel_order["uid"])->field("nickname,phone")->find();
  106. $v["nickname"]=$users["nickname"];
  107. $v["phone"]=$users["phone"];
  108. $v["uid"]=$channel_order["uid"];
  109. $v['mer_name'] = '开通渠道商';
  110. $order_type = 2;
  111. }elseif (strpos($v['order_sn'],'annual') !== false || strpos($v['order_sn'],'sIM') !== false ){
  112. //商户
  113. $annual_cost_order=Db::name('merchant_annual_cost_order')-> where('order_no',$v['order_sn'])->find();
  114. $v["mer_id"]='';
  115. $v["total_price"]=$annual_cost_order["pay_price"];
  116. $v["extension_one"]=0;
  117. $users=Db::name("user")->where("uid",$annual_cost_order["uid"])->field("nickname,phone")->find();
  118. $v["nickname"]=$users["nickname"];
  119. $v["phone"]=$users["phone"];
  120. $v["uid"]=$annual_cost_order["uid"];
  121. $v['mer_name'] = '开通商户';
  122. $order_type = 2;
  123. }else{
  124. if(strpos($v['order_sn'],'sIO') !== false){
  125. $v["mer_id"]='';
  126. $v["total_price"]=strpos($v['mark'],'金卡') !== false ? '999' : '399';
  127. $order_type = 2;
  128. }else{
  129. $store_order=Db::name("store_order")->where("order_sn",$v["order_sn"])->find();
  130. $v["mer_id"]=$store_order["mer_id"];
  131. $v["total_price"]=$store_order["total_price"];
  132. $v["extension_one"]=$store_order["extension_one"];
  133. $users=Db::name("user")->where("uid",$store_order["uid"])->field("nickname,phone")->find();
  134. $v["nickname"]=$users["nickname"];
  135. $v["phone"]=$users["phone"];
  136. $v["uid"]=$store_order["uid"];
  137. }
  138. }
  139. $v["pension"]=Db::name('user_bill')
  140. ->where('commission_type',5)
  141. ->where("order_sn",$v["order_sn"])
  142. ->value('number');
  143. $v["swipe_fee"]=Db::name('admin_bill')
  144. ->where('type',1)
  145. ->where('status',1)
  146. ->where("order_sn",$v["order_sn"])
  147. ->value('number');
  148. //服务商分账的钱
  149. $service_money = bcsub($v["extension_one"], $v["pension"], 2);
  150. // $service_money=bcmul($v["total_price"],0.05,2);
  151. $v["service_money"]=$service_money;
  152. }
  153. $user_bill=Db::name("user_bill")
  154. ->alias('a')
  155. ->join('User b', 'a.uid = b.uid')
  156. ->field('a.bill_id,a.pm,a.title,a.number,a.balance,a.mark,a.create_time,a.status,b.nickname,b.phone,a.uid,a.order_sn,a.source,identity')
  157. ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
  158. ->select();
  159. $admin_bill=Db::name("admin_bill")->where("order_sn",$v["order_sn"])->select();
  160. foreach ($admin_bill as $q){
  161. $q["nickname"]="平台";
  162. $q["phone"]="---------";
  163. $user_bill[]=$q;
  164. }
  165. if ($v["uid"]==0){
  166. $user_bill[]=[
  167. "nickname"=>"注:该用户未绑定app,未给到养老金",
  168. "mark"=>$v["pension"]
  169. ];
  170. }
  171. $v["datalist"]=$user_bill;
  172. $mer =Db::name("merchant")->where("mer_id",$v["mer_id"])->find();
  173. $v["mer_name"]=$mer["mer_name"];
  174. if($order_type == 1){
  175. $mer_mory=bcsub(bcsub($v["total_price"],$v["extension_one"],2),$v["swipe_fee"],2);
  176. $user_bill[]=[
  177. "identity"=>4,
  178. "nickname"=>$mer["mer_name"],
  179. "phone"=>$mer["mer_phone"],
  180. "number"=>$mer_mory,
  181. "mark"=>"用户到店支付成功消费".$v["total_price"]."元,商家货款".$mer_mory
  182. ];
  183. }
  184. if($order_type == 1){
  185. $countcommission=Db::name("user_bill")
  186. ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
  187. ->where("commission_type","<>",5)
  188. ->sum("number");
  189. $jieyu=bcsub($v["service_money"],$countcommission,2);
  190. $user_bill[]=[
  191. "nickname"=>"平台",
  192. "phone"=>"----------",
  193. "number"=>$jieyu,
  194. "mark"=>"分账给服务商的钱".$v["service_money"]."元,结余".$jieyu
  195. ];
  196. $v['pingtai'] = $jieyu;
  197. }else{
  198. $countcommission=Db::name("user_bill")
  199. ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
  200. ->sum("number");
  201. $v["extension_one"] = $countcommission;
  202. $jieyu=bcsub($v["total_price"],$countcommission,2);
  203. $user_bill[]=[
  204. "nickname"=>"平台",
  205. "phone"=>"----------",
  206. "number"=>$jieyu,
  207. "mark"=>"总佣金+养老金:".$countcommission."元,结余".$jieyu
  208. ];
  209. $v['pingtai'] = $jieyu;
  210. //服务商分账的钱
  211. $service_money = bcsub($v["extension_one"], $v["pension"], 2);
  212. $v["service_money"]=$service_money;
  213. }
  214. }
  215. unset($v);
  216. $c = UserBill::getDB() -> count();
  217. $userBill = json_decode(Cache::get('userBill'),true);
  218. // dump($userBill);
  219. if(isset($userBill['count']) && $userBill['count'] == $c){
  220. $total1_query = [];
  221. $cardLists = $userBill['query'];
  222. }else{
  223. $total1_query = UserBill::getDB()
  224. ->alias('a')
  225. ->join('order_merchant b', 'a.order_sn = b.out_trade_no')
  226. ->join('merchant_intention c', 'a.mer_id = c.mer_id')
  227. ->field("b.money,b.available,b.service_money,b.pension,b.swipe_fee")
  228. ->where('a.source', 1)
  229. ->where("a.status",1)
  230. ->where("a.type_shop",0)
  231. ->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
  232. $query->where('a.type', $where['type']);
  233. })
  234. ->when(isset($where['user_time']) && $where['user_time'] !== '', function ($query) use ($where) {
  235. getModelTime($query, $where['user_time'], 'a.create_time');
  236. })
  237. ->when(isset($where['city_id']) && $where['city_id'], function ($query) use ($where) {
  238. $query->where('c.city_id', $where['city_id']);
  239. })
  240. ->when(isset($where['keyword']) && $where['keyword'] !== '', function ($query) use ($where) {
  241. $query->whereLike('c.mer_name', "%{$where['keyword']}%");
  242. })
  243. ->group("a.order_sn")
  244. ->cursor();
  245. $total1_price = 0;
  246. $total1_extension_one = 0;
  247. $total1_service_money = 0;
  248. $total1_pension = 0;
  249. $total1_swipe_fee = 0;
  250. foreach ($total1_query as $total1) {
  251. $total1_price += $total1['money'];
  252. $total1_extension_one += $total1['available'];
  253. $total1_service_money += $total1['service_money'];
  254. $total1_pension += $total1['pension'];
  255. $total1_swipe_fee += $total1['swipe_fee'];
  256. }
  257. $cardLists=[
  258. ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_price, 0, 2), 'field'=>'元', 'name'=> '消费总额' ],
  259. ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_extension_one, 0, 2), 'field'=>'元', 'name'=> '可分佣总额' ],
  260. ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_service_money, 0, 2), 'field'=>'元', 'name'=> '分给服务商的金额' ],
  261. ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_pension, 0, 2), 'field'=>'元', 'name'=> '养老金' ],
  262. ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_swipe_fee, 0, 2), 'field'=>'元', 'name'=> '刷卡手续费' ],
  263. ];
  264. $userBill1['count'] = $c;
  265. $userBill1['query'] = $cardLists;
  266. Cache::set('userBill',json_encode($userBill1));
  267. }
  268. return compact('count', 'list', 'cardLists', 'total1_query');
  269. }
  270. /*平台收益记录*/
  271. public function getAdminList($where, $page, $limit)
  272. {
  273. $query = Db::name("admin_bill")->alias('a')->join('User b', 'a.link_id = b.uid')
  274. ->field('a.*,b.nickname,b.account')
  275. ->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
  276. $query->where('a.type', $where['type']);
  277. })->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
  278. getModelTime($query, $where['date'], 'a.create_time');
  279. })->when(isset($where['keyword']) && $where['keyword'] !== '', function ($query) use ($where) {
  280. $query->whereLike('a.order_sn|b.nickname|b.account', "%{$where['keyword']}%");
  281. });
  282. $query = $query->order('a.create_time DESC');
  283. $count = $query->count();
  284. $list = $query->page($page, $limit)->select();
  285. $cardLists=[];
  286. // $cardLists=[
  287. // ['className'=> 'el-icon-s-goods', 'count'=>$count1, 'field'=>'个', 'name'=> '平台收入' ],
  288. // ['className'=> 'el-icon-s-goods', 'count'=>$count2, 'field'=>'个', 'name'=> '审核中' ],
  289. // ['className'=> 'el-icon-s-goods', 'count'=>$count3, 'field'=>'个', 'name'=> '未通过' ],
  290. // ];
  291. return compact('count', 'list','cardLists');
  292. }
  293. /**
  294. * @param int $uid
  295. * @param string $category
  296. * @param string $type
  297. * @param int $pm
  298. * @param array $data
  299. * @return BaseDao|Model
  300. * @author xaboy
  301. * @day 2020-05-07
  302. */
  303. public function bill(int $uid, string $category, string $type, int $pm, array $data)
  304. {
  305. $data['category'] = $category;
  306. $data['type'] = $type;
  307. $data['uid'] = $uid;
  308. $data['pm'] = $pm;
  309. $bill = $this->dao->create($data);
  310. // if($category == 'now_money'){
  311. // $tempData = ['tempCode' => 'USER_BALANCE_CHANGE','id' => $bill->bill_id];
  312. // Queue::push(SendTemplateMessageJob::class,$tempData);
  313. // }
  314. return $bill;
  315. }
  316. /**
  317. * @param int $uid
  318. * @param string $category
  319. * @param string $type
  320. * @param array $data
  321. * @return BaseDao|Model
  322. * @author xaboy
  323. * @day 2020-05-07
  324. */
  325. public function incBill(int $uid, string $category, string $type, array $data)
  326. {
  327. return $this->bill($uid, $category, $type, 1, $data);
  328. }
  329. /**
  330. * @param int $uid
  331. * @param string $category
  332. * @param string $type
  333. * @param array $data
  334. * @return BaseDao|Model
  335. * @author xaboy
  336. * @day 2020-05-07
  337. */
  338. public function decBill(int $uid, string $category, string $type, array $data)
  339. {
  340. return $this->bill($uid, $category, $type, 0, $data);
  341. }
  342. /**
  343. * 添加 bill 数据
  344. * @param int $uid
  345. * @param int $commissionType
  346. * @param int $pm
  347. * @param float $number
  348. * @param string $category
  349. * @param string $type
  350. * @param string $source
  351. * @param int $orderType
  352. * @param int $typeShop
  353. * @param int $orderId
  354. * @param string $mark
  355. * @param string $title
  356. * @return UserBillEntity
  357. */
  358. public function addUserBill(int $uid, int $commissionType, int $pm, float $number, string $category, string $type, string $source, int $orderType, int $typeShop = 0, int $orderId = 0, string $mark = '', string $title = ''): UserBillEntity
  359. {
  360. $orderSn = '';
  361. $merId = 0;
  362. if ($typeShop == UserBillEnum::TYPE_SHOP['Platform']['code']) {
  363. /** @var StoreOrderRepository $storeOrderRepository */
  364. $storeOrderRepository = app()->make(StoreOrderRepository::class);
  365. $storeOrderEntity = $storeOrderRepository->getStoreOrderEntityByOrderId($orderId);
  366. if (empty($storeOrderEntity->getOrderId())) {
  367. throw new ValidateException('未查询到订单信息');
  368. }
  369. $orderId = $storeOrderEntity->getOrderId();
  370. $orderSn = $storeOrderEntity->getOrderSn();
  371. $merId = $storeOrderEntity->getMerId();
  372. }
  373. /** @var UserBillEntity $userBillEntity */
  374. $userBillEntity = UserBillEntity::newInstance();
  375. $userBillEntity->setUid($uid)
  376. ->setLinkId($orderId)
  377. //UserBillEnum::PM['INCOME']['code']
  378. ->setPm($pm)
  379. ->setTitle($title ?: ArrayUtil::getEnumNameByCode($commissionType, UserBillEnum::COMMISSION_TYPE))
  380. ->setCategory($category)
  381. ->setType($type)
  382. ->setNumber($number)
  383. ->setMark($mark)
  384. ->setStatus(UserBillEnum::STATUS['PENDING']['code'])
  385. ->setCommissionType($commissionType)
  386. ->setOrderSn($orderSn)
  387. ->setTypeShop($typeShop)
  388. ->setMerId($merId)
  389. // UserBillEnum::SOURCE['ONLINE']['code']
  390. ->setSource($source)
  391. ->setOrderType($orderType)
  392. ->setIsRedBrokerage(UserBillEnum::IS_RED_BROKERAGE['NORMAL']['code'])
  393. ->setGzc(UserBillEnum::GZC_STATUS['NOT_ENTERED']['code'])
  394. ->setIsGzc(UserBillEnum::IS_GZC['NOT_STARTED']['code']);
  395. return $this->createByEntity($userBillEntity);
  396. }
  397. /**
  398. * 写入 数据
  399. * @param UserBillEntity $userBillEntity
  400. * @return UserBillEntity
  401. */
  402. public function createByEntity(UserBillEntity $userBillEntity): UserBillEntity
  403. {
  404. $result = $this->dao->create($userBillEntity->toUnderlineArray())->toArray();
  405. /** @var UserBillEntity $entity */
  406. $entity = UserBillEntity::newInstance($result);
  407. return $entity;
  408. }
  409. /**
  410. * @param int $billId
  411. * @return UserBillEntity
  412. */
  413. public function getUserBillEntityByBillId(int $billId): UserBillEntity
  414. {
  415. $entityList = $this->getUserBillEntityListByBillIdList([$billId]);
  416. $entity = array_shift($entityList);
  417. if ($entity instanceof UserBillEntity) {
  418. return $entity;
  419. } else {
  420. /** @var UserBillEntity */
  421. return UserBillEntity::newInstance();
  422. }
  423. }
  424. /**
  425. * 获取Bill实体集合 根据 Id集合
  426. * @param array $billIdList
  427. * @return UserBillEntity[]
  428. */
  429. public function getUserBillEntityListByBillIdList(array $billIdList): array
  430. {
  431. return $this->dao->getUserBillEntityListByBillIdList($billIdList);
  432. }
  433. /**
  434. * 获取Bill实体集合 根据 订单类型 订单Id集合 待结算状态
  435. * @param string $typeShop
  436. * @param array $orderIdList
  437. * @return UserBillEntity[]
  438. */
  439. public function getUserBillEntityListByOrderIdListAndPending(string $typeShop, array $orderIdList): array
  440. {
  441. return $this->dao->getUserBillEntityListByOrderIdListAndPending($typeShop, $orderIdList);
  442. }
  443. /**
  444. * 将 账单 记录设置为生效状态 并对用户的 对应 字段进行增减
  445. * @param array $idList
  446. * @return UserBillEntity
  447. */
  448. public function executeByIdList(array $idList): UserBillEntity
  449. {
  450. $userBillEntityList = $this->getUserBillEntityListByBillIdList($idList);
  451. if (!empty($userBillEntityList)) {
  452. $userIdList = array_map(function ($userBillEntity) {
  453. return $userBillEntity->getUid();
  454. }, $userBillEntityList);
  455. /** @var UserEntity[] $userEntityList */
  456. $userEntityList = [];
  457. $userEntityMapByUid = [];
  458. if (!empty($userIdList)) {
  459. /** @var UserRepository $userRepository */
  460. $userRepository = app()->make(UserRepository::class);
  461. $userEntityList = $userRepository->getUserEntityListByUidList($userIdList);
  462. $userEntityMapByUid = array_map(function ($userEntity) {
  463. }, $userEntityList);
  464. }
  465. foreach ($userBillEntityList as $userBillEntity) {
  466. if (empty($userBillEntity->getBillId()) || empty($userBillEntity->getUid())) {
  467. throw new ValidateException('无效的账单记录');
  468. }
  469. if (!empty($userBillEntity->getTakeTime())) {
  470. throw new ValidateException('该账单记录已更新,请勿重复操作');
  471. }
  472. $userEntity = $userRepository->getUserEntityByUid($userBillEntity->getUid());
  473. if (empty($userEntity->getUid())) {
  474. throw new ValidateException('未查询到用户信息');
  475. }
  476. if ($userBillEntity->getType() == UserBillEnum::COMMISSION_TYPE['DIRECT_REFERRAL']['code']) {
  477. // 直推奖
  478. $surplus = bcsub($userEntity->getVr(), $userBillEntity->getNumber(), 2);
  479. if ($surplus < 0.00) {
  480. throw new ValidateException('用户VR不足');
  481. }
  482. } else {
  483. $surplus = bcadd($userEntity->getVr(), $userBillEntity->getNumber(), 2);
  484. }
  485. try {
  486. $userBillEntity
  487. ->setSurplus($surplus)
  488. ->setSettlementTime(date('Y-m-d H:i:s'));
  489. $userRepository->update($userEntity->getUid(), ['vr' => $surplus]);
  490. $this->dao->update($userBillEntity->getId(), [
  491. 'surplus' => $userBillEntity->getSurplus(),
  492. 'settlement_time' => $userBillEntity->getSettlementTime()
  493. ]);
  494. } catch (DbException $e) {
  495. }
  496. }
  497. }
  498. return $userBillEntity;
  499. }
  500. }