MCommissionCalculate.Class.php 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. <?php
  2. namespace JinDouYun\Model\Commission;
  3. use Mall\Framework\Core\ErrorCode;
  4. use Mall\Framework\Core\ResultWrapper;
  5. use Mall\Framework\Core\StatusCode;
  6. use JinDouYun\Dao\Commission\DCommissionFlow;
  7. use JinDouYun\Controller\Common\Logger;
  8. use JinDouYun\Dao\Commission\DCommissionOrder;
  9. use JinDouYun\Dao\Customer\DCustomer;
  10. use JinDouYun\Dao\Goods\DGoods;
  11. use JinDouYun\Dao\Order\DOrderGoods;
  12. use JinDouYun\Dao\Order\DOrderIndex;
  13. use JinDouYun\Dao\Commission\DCommissionBusinessman;
  14. use JinDouYun\Dao\Commission\DCommissionGoods;
  15. use JinDouYun\Dao\Commission\DCommissionGoodsStatistics;
  16. use JinDouYun\Dao\Order\DOrder;
  17. use JinDouYun\Dao\Commission\DCommissionOrderIndex;
  18. /**
  19. * Description:分销计算
  20. * Class MCommissionCalculate
  21. * @package JinDouYun\Model\Commission
  22. */
  23. class MCommissionCalculate
  24. {
  25. /**
  26. * @var array 插入分销商品记录表的数据
  27. */
  28. private $insert = [];
  29. /**
  30. * @var DCommissionOrder
  31. */
  32. private $objDCommissionOrder;
  33. /**
  34. * @var integer
  35. */
  36. private $onlineUserId;
  37. /**
  38. * @var integer
  39. */
  40. private $onlineEnterpriseId;
  41. /**
  42. * @var DCustomer
  43. */
  44. private $objDCustomer;
  45. /**
  46. * @var MCommissionSetting
  47. */
  48. private $objMCommissionSetting;
  49. /**
  50. * @var DOrderIndex
  51. */
  52. private $objDOrderIndex;
  53. /**
  54. * @var integer
  55. */
  56. private $cutTable = 200000;
  57. /**
  58. * @var DOrderGoods
  59. */
  60. private $objDOrderGoods;
  61. /**
  62. * @var DGoods
  63. */
  64. private $objDGoods;
  65. /**
  66. * @var DCommissionGoods
  67. */
  68. private $objDCommissionGoods;
  69. /**
  70. * @var int 4:优惠前计算 5:实际支付金额
  71. */
  72. private $mode;
  73. /**
  74. * @var array 级别对应标示映射
  75. */
  76. private static $levelMap = [
  77. 1 => 'oneRate',
  78. 2 => 'twoRate',
  79. 3 => 'threeRate',
  80. 'oneRate' => 1,
  81. 'twoRate' => 2,
  82. 'threeRate' => 3
  83. ];
  84. /**
  85. * @var DCommissionBusinessman
  86. */
  87. private $objDCommissionBusinessman;
  88. /**
  89. * @var MCommissionBusinessman
  90. */
  91. private $objMCommissionBusinessman;
  92. /**
  93. * @var int 平台设置分销层级
  94. */
  95. private $level;
  96. /**
  97. * @var MCommissionGrade
  98. */
  99. private $objMCommissionGrade;
  100. /**
  101. * @var array 需要检测是否达到升级条件的userCenterId
  102. */
  103. private $needUserCenterIds = [];
  104. /**
  105. * @var array 所有等级条件别名
  106. */
  107. private $allAliasCondition = [];
  108. /**
  109. * @var DCommissionGoodsStatistics
  110. */
  111. private $objDCommissionGoodsStatistics;
  112. /**
  113. * @var DOrder
  114. */
  115. private $objDOrder;
  116. /**
  117. * @var DCommissionOrderIndex
  118. */
  119. private $objDCommissionOrderIndex;
  120. /**
  121. * @var DCommissionFlow
  122. */
  123. private $objDCommissionFlow;
  124. /**
  125. * @var array 分销设置
  126. */
  127. private $setting;
  128. /**
  129. * @var array 当前订单信息
  130. */
  131. private $orderData;
  132. /**
  133. * @var array 当前订单商品
  134. */
  135. private $orderGoods;
  136. /**
  137. * @var int 是否开启自购
  138. */
  139. private $isRetSelf;
  140. /**
  141. * MCommissionCalculate constructor.
  142. * @param $onlineEnterpriseId
  143. * @param $onlineUserId
  144. * @throws \Exception
  145. */
  146. public function __construct($onlineEnterpriseId, $onlineUserId)
  147. {
  148. $this->onlineUserId = $onlineUserId;
  149. $this->onlineEnterpriseId = $onlineEnterpriseId;
  150. $this->objDCommissionOrder = new DCommissionOrder();
  151. $this->objDCommissionOrder->setTable('qianniao_commission_order_' . $this->onlineEnterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3));
  152. $this->objDCustomer = new DCustomer();
  153. $this->objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
  154. $this->objMCommissionSetting = new MCommissionSetting($this->onlineEnterpriseId, $this->onlineUserId);
  155. $this->objDOrderIndex = new DOrderIndex();
  156. $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId);
  157. $this->objDOrderGoods = new DOrderGoods();
  158. $this->objDOrder = new DOrder();
  159. $this->objDGoods = new DGoods();
  160. $this->objDGoods->setTable('qianniao_goods_' . $this->onlineEnterpriseId);
  161. $this->objDCommissionGoods = new DCommissionGoods();
  162. $this->objDCommissionGoods->setTable('qianniao_commission_goods_' . $this->onlineEnterpriseId);
  163. $this->objDCommissionBusinessman = new DCommissionBusinessman();
  164. $this->objDCommissionBusinessman->setTable('qianniao_commission_businessman_' . $this->onlineEnterpriseId);
  165. $this->objMCommissionBusinessman = new MCommissionBusinessman($this->onlineEnterpriseId, $this->onlineUserId);
  166. $this->objMCommissionGrade = new MCommissionGrade($this->onlineEnterpriseId, $this->onlineUserId);
  167. $this->objDCommissionGoodsStatistics = new DCommissionGoodsStatistics();
  168. $this->objDCommissionGoodsStatistics->setTable('qianniao_commission_goods_statistics_'.$this->onlineEnterpriseId);
  169. $this->objDCommissionOrderIndex = new DCommissionOrderIndex();
  170. $this->objDCommissionOrderIndex->setTable('qianniao_commission_order_index_'.$this->onlineEnterpriseId);
  171. $this->objDCommissionFlow = new DCommissionFlow();
  172. $this->objDCommissionFlow->setTable('qianniao_commission_flow_'.$this->onlineEnterpriseId);
  173. $this->needUserCenterIds = [];
  174. }
  175. /**
  176. * 增加分销商品的销量以及分销金额
  177. * @throws \Exception
  178. */
  179. public function __destruct()
  180. {
  181. //todo
  182. //在这里判断分销商是否达到升级条件,进行升级
  183. // TODO: Implement __destruct() method.
  184. if (!empty($this->insert)) self::incrCommissionGoods($this->insert);//增加销量
  185. if (!empty($this->orderData)){
  186. $result = $this->objMCommissionBusinessman->outSetStatistics(
  187. $this->orderData['userCenterId'],
  188. [
  189. 'skuIds' => array_column($this->orderGoods,'skuId'),
  190. 'statistics'=>[
  191. 'auditOrderTotal' => 1,
  192. 'auditTotalMoney' => $this->orderData['payAmount']
  193. ]
  194. ]
  195. );
  196. if (!$result->isSuccess()){
  197. Logger::logs(E_USER_ERROR,'分销商',__CLASS__,__LINE__,$result->getData());
  198. }
  199. }
  200. //if (!empty($this->needUserCenterIds)) self::upgrade();//升级
  201. }
  202. /**
  203. * Doc: (des="创建分销")
  204. * User: XMing
  205. * Date: 2020/7/23
  206. * Time: 10:46 上午
  207. * @param int $customerId
  208. * @param int $orderId
  209. * @return ResultWrapper
  210. * @throws \Exception
  211. */
  212. public function createCommission(int $customerId, int $orderId)
  213. {
  214. // 查询买家是否有上级,和买家是否是分销商
  215. $customer = $this->objDCustomer->get(['id' => $customerId], 'isCommission,commissionPath');
  216. if ($customer === false) {
  217. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  218. }
  219. if (empty($customer)) {
  220. return ResultWrapper::fail('未查询到客户', ErrorCode::$paramError);
  221. }
  222. // 获取订单索引数据
  223. $orderIndex = $this->objDOrderIndex->get(['id' => $orderId], 'userCenterId,no');
  224. if ($orderIndex === false) {
  225. return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
  226. }
  227. if (empty($orderIndex)) {
  228. return ResultWrapper::fail('未查询到指定订单', ErrorCode::$paramError);
  229. }
  230. // 切表
  231. $fix = ceil($orderIndex['userCenterId'] / $this->cutTable);
  232. $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix);
  233. $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix);
  234. // 获取订单数据
  235. $orderData = $this->objDOrder->get(['id'=>$orderId],'id,payAmount,userCenterId,customerId');
  236. if ($orderData === false){
  237. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  238. }
  239. if (empty($orderData)) {
  240. return ResultWrapper::fail('订单数据为空', ErrorCode::$paramError);
  241. }
  242. $this->orderData = $orderData;
  243. // 查询订单商品数据
  244. $orderGoods = $this->objDOrderGoods->select(['orderId' => $orderId], 'goodsId,skuId,totalMoney,buyNum,vipDiscount,preferential,goodsName,shopName,unitName,specGroup,goodsImages');
  245. if ($orderGoods === false) {
  246. return ResultWrapper::fail($this->objDOrderGoods->error(), ErrorCode::$dberror);
  247. }
  248. if (empty($orderGoods)) {
  249. return ResultWrapper::fail('订单商品数据为空', ErrorCode::$paramError);
  250. }
  251. $this->orderGoods = $orderGoods;
  252. // 判断当前客户是否是分销商
  253. $isCommission = $customer['isCommission'];//是否是分销商 5->分销商 4->不是分销商
  254. $retPath = $customer['commissionPath'];//分销商关系
  255. if ($isCommission == StatusCode::$delete && empty($retPath)) {
  256. return ResultWrapper::success('不符合分销条件');
  257. }
  258. // 查询分销设置数据
  259. $settingResult = $this->objMCommissionSetting->getSetting(true);
  260. if (!$settingResult->isSuccess()) {
  261. return ResultWrapper::fail($settingResult->getData(), $settingResult->getErrorCode());
  262. }
  263. $setting = $settingResult->getData();
  264. if (!isset($setting['mode'])) {
  265. return ResultWrapper::fail('分销佣金计算方式未设置', ErrorCode::$paramError);
  266. }
  267. $this->setting = $setting;
  268. $isRetSelf = $setting['self']; // 自动返佣
  269. $this->mode = $setting['mode']; // 佣金计算方式
  270. $this->level = $setting['level'];//分销等级 三级分销
  271. $this->isRetSelf = $isRetSelf;
  272. //组装订单商品数据数据
  273. $commonData = [
  274. 'orderId' => $orderId,
  275. 'orderNo' => $orderIndex['no'],
  276. 'userCenterId' => $orderIndex['userCenterId'],
  277. 'customerId' => $customerId
  278. ];
  279. foreach ($orderGoods as &$item) {
  280. $item = array_merge($item, $commonData);
  281. }
  282. $selfOrderInsert = [];
  283. // 如果当前客户是分销商且开启自购返佣
  284. if ($isCommission == StatusCode::$standard && $isRetSelf == StatusCode::$standard) {
  285. empty($this->needUserCenterIds) && $this->needUserCenterIds = [];
  286. $this->needUserCenterIds = array_merge($this->needUserCenterIds, [$orderIndex['userCenterId']]);
  287. $selfRetCommission = self::selfRetCommission($orderIndex['userCenterId'], $customerId, $orderGoods);
  288. if (!$selfRetCommission->isSuccess()) {
  289. return ResultWrapper::fail($selfRetCommission->getData(), $selfRetCommission->getErrorCode());
  290. }
  291. $selfOrderInsert = $selfRetCommission->getData();
  292. }
  293. // 给上级返佣
  294. $retOrderInsert = [];
  295. if (!empty($retPath) && $this->level != 0) {
  296. // 所有上级的usercenterid集合
  297. $retPathArr = array_values(json_decode($retPath, true));
  298. empty($this->needUserCenterIds) && $this->needUserCenterIds = [];
  299. $this->needUserCenterIds = array_merge($this->needUserCenterIds, $retPathArr);
  300. $iterRetCommissionResult = self::iterRetCommission($retPathArr, $orderGoods);
  301. if (!$iterRetCommissionResult->isSuccess()) {
  302. return ResultWrapper::fail($iterRetCommissionResult->getData(), $iterRetCommissionResult->getErrorCode());
  303. }
  304. $retOrderInsert = $iterRetCommissionResult->getData();
  305. }
  306. $insert = array_merge($selfOrderInsert, $retOrderInsert);
  307. if (empty($insert)) {
  308. return ResultWrapper::success('没有需要记录的数据');
  309. }
  310. $updateOrderData = self::updateOrderData($selfOrderInsert,$retOrderInsert);//订单佣金拓展字段
  311. $commissionOrderIndex = self::commissionIndexData($selfOrderInsert,$retOrderInsert,$orderData['payAmount']);//分销订单索引数据
  312. $updateCommissionResult = self::updateCommission($insert);//计算分销商的变动数据
  313. if (!$updateCommissionResult->isSuccess()) {
  314. return ResultWrapper::fail($updateCommissionResult->getData(), $updateCommissionResult->getErrorCode());
  315. }
  316. $updateCommission = $updateCommissionResult->getData();
  317. $statisticsDataResult = self::saveBusinessmanStatistics($commissionOrderIndex,$orderData['payAmount']);//计算要回写的数据
  318. if (!$statisticsDataResult->isSuccess()){
  319. return ResultWrapper::fail($statisticsDataResult->getData(),$statisticsDataResult->getErrorCode());
  320. }
  321. $statisticsData = $statisticsDataResult->getData();//要回写的数据
  322. /***************************************写记录start*************************************************************/
  323. $this->objDCommissionOrder->beginTransaction();
  324. foreach ($updateCommission as $key => $value) {
  325. $update = $this->objDCommissionBusinessman->update([
  326. 'waitMoney' => $value['waitMoney'],
  327. 'updateTime' => $value['updateTime']
  328. ], ['userCenterId' => $value['userCenterId']]);
  329. if ($update === false) {
  330. $this->objDCommissionOrder->rollBack();
  331. return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror);
  332. }
  333. }
  334. $insert = self::insertSort($insert);
  335. $result = $this->objDCommissionOrder->insert($insert, true);
  336. if ($result === false) {
  337. $this->objDCommissionOrder->rollBack();
  338. return ResultWrapper::fail($this->objDCommissionOrder->error(), ErrorCode::$dberror);
  339. }
  340. //回写订单索引表
  341. $updateIndex = $this->objDOrderIndex->update(
  342. [
  343. 'isCommission'=> StatusCode::$standard,
  344. 'commissionData' => json_encode($updateOrderData),
  345. 'updateTime' => time()
  346. ],
  347. ['id' => $orderId]
  348. );
  349. if ($updateIndex === false){
  350. $this->objDCommissionOrder->rollBack();
  351. return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror);
  352. }
  353. //写订单表
  354. $updateOrder = $this->objDOrder->update([
  355. 'isCommission'=> StatusCode::$standard,
  356. 'commissionData' => json_encode($updateOrderData),
  357. 'updateTime' => time()
  358. ],['id' => $orderId]);
  359. if ($updateOrder === false){
  360. $this->objDCommissionOrder->rollBack();
  361. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  362. }
  363. //分销订单索引数据
  364. $commissionOrderIndex = self::insertSort($commissionOrderIndex);
  365. $commissionOrderIndex = $this->objDCommissionOrderIndex->insert($commissionOrderIndex,true);
  366. if ($commissionOrderIndex === false){
  367. $this->objDCommissionOrder->rollBack();
  368. return ResultWrapper::fail($this->objDCommissionOrderIndex->error(),ErrorCode::$dberror);
  369. }
  370. //回写数据
  371. foreach ($statisticsData as $userCenterId => $row){
  372. $outSetStatisticsResult = $this->objMCommissionBusinessman->outSetStatistics($userCenterId,$row);
  373. if (!$outSetStatisticsResult->isSuccess()){
  374. $this->objDCommissionOrder->rollBack();
  375. }
  376. }
  377. $this->objDCommissionOrder->commit();
  378. $this->insert = $insert;
  379. return ResultWrapper::success("操作成功");
  380. }
  381. /**
  382. * Doc: (des="分销订单主索引表")
  383. * User: XMing
  384. * Date: 2020/7/30
  385. * Time: 11:38 上午
  386. * @param array $selfOrderInsert
  387. * @param array $retOrderInsert
  388. * @param $payAmount
  389. * @return array
  390. */
  391. private function commissionIndexData(array $selfOrderInsert,array $retOrderInsert,$payAmount)
  392. {
  393. $commissionIndexMap = [];
  394. //自购返佣
  395. if (!empty($selfOrderInsert)){
  396. //将数据按照订单级别合并
  397. $retMoney = array_sum(array_column($selfOrderInsert,'retMoney'));
  398. $commissionIndexMap[] = [
  399. 'userCenterId' => $selfOrderInsert[0]['userCenterId'],
  400. 'customerId' => $selfOrderInsert[0]['customerId'],
  401. 'orderId' => $selfOrderInsert[0]['orderId'],
  402. 'orderNo' => $selfOrderInsert[0]['orderNo'],
  403. 'payAmount' => $payAmount,
  404. 'retUserCenterId' => $selfOrderInsert[0]['retUserCenterId'],
  405. 'retCustomerId' => $selfOrderInsert[0]['retCustomerId'],
  406. 'retMoney' => $retMoney,
  407. 'retLevel' => $selfOrderInsert[0]['retLevel'],
  408. 'retGrade' => $selfOrderInsert[0]['retGrade']
  409. ];
  410. }
  411. //三级返佣
  412. if (!empty($retOrderInsert)){
  413. $oneRetMoney = 0;
  414. $twoRetMoney = 0;
  415. $threeRetMoney = 0;
  416. foreach ($retOrderInsert as $item){
  417. $common[$item['retLevel']] = [
  418. 'userCenterId' => $item['userCenterId'],
  419. 'customerId' => $item['customerId'],
  420. 'orderId' => $item['orderId'],
  421. 'orderNo' => $item['orderNo'],
  422. 'payAmount' => $payAmount,
  423. 'retUserCenterId' => $item['retUserCenterId'],
  424. 'retCustomerId' => $item['retCustomerId'],
  425. 'retLevel' => $item['retLevel'],
  426. 'retGrade' => $item['retGrade']
  427. ];
  428. switch ($item['retLevel']){
  429. case self::$levelMap['oneRate']:
  430. $oneRetMoney = bcadd($oneRetMoney,$item['retMoney'],2);
  431. break;
  432. case self::$levelMap['twoRate']:
  433. $twoRetMoney = bcadd($twoRetMoney,$item['retMoney'],2);
  434. break;
  435. case self::$levelMap['threeRate']:
  436. $threeRetMoney = bcadd($threeRetMoney,$item['retMoney'],2);
  437. break;
  438. }
  439. }
  440. //一级
  441. if ($oneRetMoney != 0){
  442. $common[self::$levelMap['oneRate']]['retMoney'] = $oneRetMoney;
  443. $commissionIndexMap[] = $common[self::$levelMap['oneRate']];
  444. }
  445. //二级
  446. if($twoRetMoney != 0){
  447. $common[self::$levelMap['twoRate']]['retMoney'] = $twoRetMoney;
  448. $commissionIndexMap[] = $common[self::$levelMap['twoRate']];
  449. }
  450. //三级
  451. if ($threeRetMoney != 0){
  452. $common[self::$levelMap['threeRate']]['retMoney'] = $threeRetMoney;
  453. $commissionIndexMap[] = $common[self::$levelMap['threeRate']];
  454. }
  455. }
  456. Logger::logs(E_USER_ERROR,'分销订单索引数据',__CLASS__,__LINE__,$commissionIndexMap);
  457. return $commissionIndexMap;
  458. }
  459. /**
  460. * Doc: (des="对插入的二维数组进行排序")
  461. * User: XMing
  462. * Date: 2020/7/30
  463. * Time: 2:42 下午
  464. * @param array $data
  465. * @return array
  466. */
  467. private function insertSort(array $data)
  468. {
  469. foreach ($data as &$value){
  470. ksort($value);
  471. }
  472. return $data;
  473. }
  474. /**
  475. * Doc: (des="回写订单的分销状态,记录订单分销数据json")
  476. * User: XMing
  477. * Date: 2020/7/29
  478. * Time: 6:57 下午
  479. * @param array $selfOrderInsert
  480. * @param array $retOrderInsert
  481. * @example
  482. * isCommission 是否是分销订单 5是 4否
  483. * @return array
  484. *
  485. */
  486. private function updateOrderData(array $selfOrderInsert,array $retOrderInsert)
  487. {
  488. $commissionMap=[];
  489. //自购返佣
  490. if (!empty($selfOrderInsert)){
  491. $retMoney = array_sum(array_column($selfOrderInsert,'retMoney'));
  492. $commissionMap['self'] = [
  493. 'retLevel' => 1,
  494. 'retMoney' => $retMoney,
  495. 'retCustomerId' => $selfOrderInsert[0]['customerId'],
  496. 'retUserCenterId' => $selfOrderInsert[0]['userCenterId'],
  497. ];
  498. }
  499. //三级返佣
  500. if(!empty($retOrderInsert)){
  501. $oneRetMoney = 0;
  502. $twoRetMoney = 0;
  503. $threeRetMoney = 0;
  504. foreach ($retOrderInsert as $item){
  505. switch ($item['retLevel']){
  506. case self::$levelMap['oneRate']:
  507. $oneRetMoney = bcadd($oneRetMoney,$item['retMoney'],2);
  508. //一级返佣
  509. $commissionMap['oneRet'] = [
  510. 'retLevel' => self::$levelMap['oneRate'],
  511. 'retMoney' => $oneRetMoney,
  512. 'retCustomerId' => $item['retCustomerId'],
  513. 'retUserCenterId' => $item['retUserCenterId']
  514. ];
  515. break;
  516. case self::$levelMap['twoRate']:
  517. //二级
  518. $twoRetMoney = bcadd($twoRetMoney,$item['retMoney'],2);
  519. $commissionMap['twoRet'] = [
  520. 'retLevel' => self::$levelMap['twoRate'],
  521. 'retMoney' => $twoRetMoney,
  522. 'retCustomerId' => $item['retCustomerId'],
  523. 'retUserCenterId' => $item['retUserCenterId']
  524. ];
  525. break;
  526. case self::$levelMap['threeRate']:
  527. //三级
  528. $threeRetMoney = bcadd($threeRetMoney,$item['retMoney'],2);
  529. $commissionMap['threeRet'] = [
  530. 'retLevel' => self::$levelMap['threeRate'],
  531. 'retMoney' => $threeRetMoney,
  532. 'retCustomerId' => $item['retCustomerId'],
  533. 'retUserCenterId' => $item['retUserCenterId']
  534. ];
  535. break;
  536. }
  537. }
  538. }
  539. return $commissionMap;
  540. }
  541. /**
  542. * Doc: (des="计算分销商的更新数据")
  543. * User: XMing
  544. * Date: 2020/7/24
  545. * Time: 10:21 上午
  546. * @param array $data
  547. * @return ResultWrapper
  548. */
  549. private function updateCommission(array $data)
  550. {
  551. //查询分销商记录
  552. $allRetUserCenterIds = [];
  553. $changeMap = [];
  554. foreach ($data as $item) {
  555. $allRetUserCenterIds[] = $item['retUserCenterId'];
  556. $changeMap[$item['retUserCenterId']][] = $item['retMoney'];
  557. }
  558. $businessmanResult = self::getCommissionBusinessman($allRetUserCenterIds);
  559. if (!$businessmanResult->isSuccess()){
  560. return ResultWrapper::fail($businessmanResult->getData(),$businessmanResult->getErrorCode());
  561. }
  562. $businessman = $businessmanResult->getData();
  563. $update = [];
  564. foreach ($businessman as $row) {
  565. $oldWaitMoney = $row['waitMoney'];//原金额
  566. //获取当前用户变动金额
  567. $changeMoney = array_sum($changeMap[$row['userCenterId']]);//变动金额
  568. $newWaitMoney = bcadd($oldWaitMoney, $changeMoney, 2);//变动后金额
  569. $update[] = [
  570. 'userCenterId' => $row['userCenterId'],
  571. 'waitMoney' => $newWaitMoney,
  572. 'updateTime' => time(),//变动时间
  573. ];
  574. }
  575. if (!empty($update)){
  576. Logger::logs(E_USER_ERROR,'分销商更新数据',__CLASS__,__LINE__,$update);
  577. }
  578. return ResultWrapper::success($update);
  579. }
  580. /**
  581. * Doc: (des="获取分销商的信息集合")
  582. * User: XMing
  583. * Date: 2020/7/31
  584. * Time: 11:30 上午
  585. * @param array $allRetUserCenterIds
  586. * @param string $fields
  587. * @return ResultWrapper
  588. *
  589. */
  590. private function getCommissionBusinessman(array $allRetUserCenterIds,string $fields='id,userCenterId,balance,totalMoney,waitMoney')
  591. {
  592. $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allRetUserCenterIds], $fields);
  593. if ($businessman === false) {
  594. return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror);
  595. }
  596. return ResultWrapper::success($businessman);
  597. }
  598. /**
  599. * Doc: (des="分销数据的回写")
  600. * User: XMing
  601. * Date: 2020/7/28
  602. * Time: 3:23 下午
  603. * @param array $data 分销返佣的数据
  604. * @param float $payAmount
  605. * @example
  606. * @return ResultWrapper
  607. */
  608. private function saveBusinessmanStatistics(array $data,float $payAmount)
  609. {
  610. //demo
  611. /**$params = [
  612. 'balance' => 100.00, //余额
  613. 'waitMoney' => 100.00, //待入账金额
  614. 'withdraw' => 100.00, //已提现金额
  615. 'statistics' => [
  616. 'orderMoney' => 100.00, //分销订单总额
  617. 'orderNum' => 100, //分销订单总数
  618. 'oneOrderMoney' => 100.00, //一级分销订单总额
  619. 'oneOrderNum' => 100, //一级分销订单总数
  620. 'selfOrderMoney' => 100.00, //自购订单总额
  621. 'selfOrderNum' => 100, //自购订单总数
  622. 'sub' => 100, //下线人数
  623. 'subBusinessman' => 100, //下线分销商人数
  624. 'oneSub' => 100, //一级下线人数
  625. 'oneSubBusinessman' => 100, //一级下线分销商
  626. 'totalMoney' => 100.00, //累计佣金
  627. ],
  628. ];*/
  629. $allRetUserCenterIds = [];
  630. $changeMap = [];
  631. foreach ($data as $item) {
  632. $allRetUserCenterIds[] = $item['retUserCenterId'];
  633. $changeMap[$item['retUserCenterId']][] = $item['retMoney'];
  634. }
  635. $businessmanResult = self::getCommissionBusinessman($allRetUserCenterIds);
  636. if (!$businessmanResult->isSuccess()){
  637. return ResultWrapper::fail($businessmanResult->getData(),$businessmanResult->getErrorCode());
  638. }
  639. $businessman = $businessmanResult->getData();
  640. $businessmanMap = [];
  641. foreach ($businessman as $value){
  642. $businessmanMap[$value['userCenterId']] = $value;
  643. }
  644. $arrayMap = [];
  645. foreach ($data as $key => $item){
  646. if (!isset($businessmanMap[$item['retUserCenterId']])){
  647. return ResultWrapper::fail('分销商数据映射失败',ErrorCode::$paramError);
  648. }
  649. $oldTotalMoney = $businessmanMap[$item['retUserCenterId']]['totalMoney'];
  650. $arrayMap[$item['retUserCenterId']] = [
  651. 'totalMoney' => bcadd($oldTotalMoney,$item['retMoney']),
  652. 'statistics' => [
  653. 'orderMoney' => $payAmount,
  654. 'orderNum' => 1,
  655. ],
  656. ];//公共数据
  657. switch ($key){
  658. case 'self':
  659. //自购
  660. $arrayMap[$item['retUserCenterId']]['statistics']['selfOrderMoney'] = $payAmount;
  661. $arrayMap[$item['retUserCenterId']]['statistics']['selfOrderNum'] = 1;
  662. break;
  663. case 'oneRet':
  664. //一级
  665. $arrayMap[$item['retUserCenterId']]['statistics']['oneOrderMoney'] = $payAmount;
  666. $arrayMap[$item['retUserCenterId']]['statistics']['oneOrderNum'] = 1;
  667. break;
  668. case 'twoRet':
  669. //二级
  670. break;
  671. case 'threeRet':
  672. //三级
  673. break;
  674. }
  675. }
  676. if (!empty($arrayMap)){
  677. Logger::logs(E_USER_ERROR,'回写数据',__CLASS__,__LINE__,$arrayMap);
  678. }
  679. return ResultWrapper::success($arrayMap);
  680. }
  681. /**
  682. * 上级返佣方法
  683. * @param array $retPathArr 所有上级的usercenterIds
  684. * @param array $orderGoodsData 订单商品数据
  685. * @return ResultWrapper
  686. */
  687. private function iterRetCommission(array $retPathArr, array $orderGoodsData)
  688. {
  689. $retGoodsResult = self::getGoodsRule($orderGoodsData);
  690. if (!$retGoodsResult->isSuccess()) {
  691. return ResultWrapper::fail($retGoodsResult->getData(), $retGoodsResult->getErrorCode());
  692. }
  693. $retGoods = $retGoodsResult->getData();
  694. $defaultGoods = $retGoods['defaultGoods']; // 默认返佣规则商品
  695. $defineGoods = $retGoods['defineGoods']; // 自定义佣金规则商品
  696. // 获取分销商等级和等级对应的佣金规则
  697. $gradeResult = self::getGradeRuleBySelect($retPathArr);
  698. if (!$gradeResult->isSuccess()) {
  699. return ResultWrapper::fail($gradeResult->getData(), $gradeResult->getErrorCode());
  700. }
  701. $gradeRule = $gradeResult->getData();//分销商等级佣金比例规则
  702. //$retLevel 当前被返佣分销商所处级别1-3
  703. //$retUserCenterId 当前被返佣分销商的用户id
  704. $defaultInsert = [];
  705. $defineInsert = [];
  706. foreach ($retPathArr as $index => $retUserCenterId) {
  707. // 如果开启自购返佣,上一级从第二集开始返佣
  708. if($this->isRetSelf == StatusCode::$standard){
  709. $retLevel = (int)$index + 2;
  710. }else{
  711. $retLevel = (int)$index + 1;
  712. }
  713. // 如果当前分销层级大于后台设置的分销层级则不计算佣金
  714. if ($retLevel > $this->level) {
  715. continue;
  716. }
  717. // 当前路径中的用户id不是分销商,不进行返佣,进入下一级别
  718. if (!isset($gradeRule[$retUserCenterId])) {
  719. continue;
  720. }
  721. $grade = $gradeRule[$retUserCenterId]['grade'];//被返佣用户等级1-10
  722. $retCustomerId = $gradeRule[$retUserCenterId]['customerId'];//被返佣客户id
  723. //1.处理默认分销商品
  724. if (!empty($defaultGoods)) {
  725. $rate = $gradeRule[$retUserCenterId][self::$levelMap[$retLevel]];//当前等级当前等级比例
  726. if (empty($rate)) {
  727. //比率为0
  728. continue;
  729. }
  730. $rate = bcdiv($rate, 100);
  731. //生成数据
  732. $defaultResult = self::createDefaultOrder($defaultGoods, $rate, $grade, $retUserCenterId, $retCustomerId, $retLevel, StatusCode::$delete);
  733. $defaultInsert = array_merge($defaultInsert, $defaultResult);//合并每次的结果
  734. }
  735. //2.处理自定义分销商品
  736. if (!empty($defineGoods)) {
  737. $defineResult = self::createDefineOrder($defineGoods, $grade, $retUserCenterId, $retCustomerId, $retLevel, StatusCode::$delete);
  738. $defineInsert = array_merge($defineInsert, $defineResult);
  739. }
  740. }
  741. $return = array_merge($defaultInsert, $defineInsert);//合并最终数据
  742. return ResultWrapper::success($return);
  743. }
  744. /**
  745. * @param array $data 订单商品数据
  746. * @param int $userCenterId 自购分销商用户id
  747. * @param int $customerId 自购分销商客户id
  748. * @return ResultWrapper 返回数据为自购返佣记录数据
  749. */
  750. private function selfRetCommission(int $userCenterId, int $customerId, array $orderGoodsData)
  751. {
  752. $retGoodsResult = self::getGoodsRule($orderGoodsData);
  753. if (!$retGoodsResult->isSuccess()) {
  754. return ResultWrapper::fail($retGoodsResult->getData(), $retGoodsResult->getErrorCode());
  755. }
  756. $retGoodsResult = $retGoodsResult->getData();
  757. $defaultGoods = $retGoodsResult['defaultGoods']; // 默认佣金规则的商品
  758. $defineGoods = $retGoodsResult['defineGoods']; // 单独设置佣金规则的商品
  759. // 获取分销商等级佣金规则
  760. $gradeResult = self::getGradeRuleBySelect([$userCenterId]);
  761. if (!$gradeResult->isSuccess()) {
  762. return ResultWrapper::fail($gradeResult->getData(), $gradeResult->getErrorCode());
  763. }
  764. $gradeRule = $gradeResult->getData();
  765. $selfGradeRule = isset($gradeRule[$userCenterId]) ? $gradeRule[$userCenterId] : [];//分销商的等级佣金规则
  766. if (empty($selfGradeRule)) {
  767. return ResultWrapper::fail('获取分销等级规则为空', ErrorCode::$paramError);
  768. }
  769. $grade = $selfGradeRule['grade'];//自购分销商等级0-10
  770. //默认分销佣金商品
  771. $defaultInsert = [];
  772. if (!empty($defaultGoods)) {
  773. //自购分销商的等级佣金比率
  774. $rate = $this->isRetSelf == StatusCode::$delete ? 0 : bcdiv($selfGradeRule['oneRate'], 100);//自购使用一级分销商的比率,将比率换算成浮点数
  775. $defaultInsert = self::createDefaultOrder($defaultGoods, $rate, $grade, $userCenterId, $customerId, 1, StatusCode::$standard);//自购返佣数据
  776. }
  777. // 单独设置佣金规则的商品
  778. $defineInsert = [];
  779. if (!empty($defineGoods)) {
  780. $defineInsert = self::createDefineOrder($defineGoods, $grade, $userCenterId, $customerId, 1, StatusCode::$standard);
  781. }
  782. $insert = array_merge($defaultInsert, $defineInsert);
  783. return ResultWrapper::success($insert);
  784. }
  785. /**
  786. * 计算单独设置佣金规则商品
  787. * @param array $data 单独设置佣金规则的商品数据
  788. * @param int $grade 被返佣分销商的等级1-10
  789. * @param int $retUserCenterId 被返佣分销商用户id
  790. * @param int $retCustomerId 被返佣分销商客户id
  791. * @param int $retLevel 被返佣分销商的级别1-3
  792. * @param int $isSelf 是否自购返佣 5是 4否
  793. *
  794. * @return array
  795. */
  796. private function createDefineOrder(array $data, int $grade, int $retUserCenterId, int $retCustomerId, int $retLevel, int $isSelf)
  797. {
  798. $insert = [];
  799. foreach ($data as $item) {
  800. $amount = 0;
  801. switch ($this->mode) {
  802. case StatusCode::$standard: // 实际支付金额
  803. $amount = bcsub($item['totalMoney'], bcadd($item['vipDiscount'], $item['preferential']), 2);
  804. break;
  805. case StatusCode::$delete: // 商品折扣价
  806. $amount = bcsub($item['totalMoney'], $item['preferential'],2);
  807. break;
  808. }
  809. $oneRate = isset($item['rule'][$grade][self::$levelMap[$retLevel]]) ? $item['rule'][$grade][self::$levelMap[$retLevel]] : 0;//自购一级佣金比例
  810. if (empty($oneRate)) {
  811. continue;
  812. }
  813. $retRate = 0; // 佣金计算百分比
  814. if($item['retType'] == StatusCode::$standard){ // 返佣方式百分比
  815. $oneRate = bcdiv($oneRate, 100);
  816. $retMoney = bcmul($amount, $oneRate, 2);
  817. $retRate = bcmul($oneRate, 100);
  818. }else{ // 返佣方式固定金额
  819. $retMoney = bcmul($oneRate, $item['buyNum'], 2);
  820. }
  821. //是自购订单但是未开启自购
  822. if ($isSelf == StatusCode::$standard && $this->isRetSelf == StatusCode::$delete){
  823. $retMoney = 0;
  824. }
  825. $insert[] = [
  826. 'userCenterId' => $item['userCenterId'],
  827. 'customerId' => $item['customerId'],
  828. 'orderId' => $item['orderId'],
  829. 'orderNo' => $item['orderNo'],
  830. 'goodsId' => $item['goodsId'],
  831. 'skuId' => $item['skuId'],
  832. 'goodsPrice' => $item['totalMoney'],
  833. 'retUserCenterId' => $retUserCenterId,
  834. 'retCustomerId' => $retCustomerId,
  835. 'retMoney' => $retMoney,
  836. 'retLevel' => $retLevel, //级别1-3
  837. 'retGrade' => $grade, //等级1-10,
  838. 'retRate' => $retRate,
  839. 'buyNum' => $item['buyNum'],
  840. 'goodsName' => $item['goodsName'],
  841. 'shopName' => $item['shopName'],
  842. 'unitName' => $item['unitName'],
  843. 'specGroup' => $item['specGroup'],
  844. 'goodsImages' => $item['goodsImages'],
  845. 'isSelf' => $isSelf
  846. ];
  847. }
  848. return $insert;
  849. }
  850. /**
  851. * Doc: (des="生成默认佣金流水记录数据")
  852. * User: XMing
  853. * Date: 2020/7/23
  854. * Time: 4:45 下午
  855. * @param array $data 分销商品数据
  856. * @param string $rate 被返佣分销商所处等级级别比率
  857. * @param int $grade 被返佣分销商的等级1-10
  858. * @param int $retUserCenterId 被返佣分销商用户id
  859. * @param int $retCustomerId 被返佣分销商客户id
  860. * @param int $retLevel 被返佣人所处级别1-3
  861. * @param int $isSelf 是否自购返佣 5是 4否
  862. * @return array
  863. */
  864. private function createDefaultOrder(array $data, string $rate, int $grade, int $retUserCenterId, int $retCustomerId, int $retLevel, int $isSelf)
  865. {
  866. $insert = [];
  867. foreach ($data as $item) {
  868. $amount = 0;
  869. switch ($this->mode) {
  870. case StatusCode::$standard:
  871. //实际支付金额
  872. $amount = bcsub($item['totalMoney'], bcadd($item['vipDiscount'], $item['preferential']), 2);
  873. break;
  874. case StatusCode::$delete:
  875. $amount = bcsub($item['totalMoney'], $item['preferential'],2);
  876. break;
  877. }
  878. $retMoney = bcmul($amount, $rate, 2);
  879. $insert[] = [
  880. 'userCenterId' => $item['userCenterId'],
  881. 'customerId' => $item['customerId'],
  882. 'orderId' => $item['orderId'],
  883. 'orderNo' => $item['orderNo'],
  884. 'goodsId' => $item['goodsId'],
  885. 'skuId' => $item['skuId'],
  886. 'goodsPrice' => $item['totalMoney'],
  887. 'retUserCenterId' => $retUserCenterId,
  888. 'retCustomerId' => $retCustomerId,
  889. 'retMoney' => $retMoney,
  890. 'retLevel' => $retLevel,//级别1-3
  891. 'retGrade' => $grade,//等级1-10,
  892. 'retRate' => bcmul($rate, 100),
  893. 'buyNum' => $item['buyNum'],
  894. 'goodsName' => $item['goodsName'],//
  895. 'shopName' => $item['shopName'],//
  896. 'unitName' => $item['unitName'],//
  897. 'specGroup' => $item['specGroup'],//
  898. 'goodsImages' => $item['goodsImages'],//
  899. 'isSelf' => $isSelf
  900. ];
  901. }
  902. return $insert;
  903. }
  904. /**
  905. * 批量获取指定用户的分销商等级
  906. * @param array $params 分销商的userCenterIds
  907. * @return ResultWrapper
  908. */
  909. private function getGradeRuleBySelect(array $params)
  910. {
  911. $commissionBusinessmanResult = $this->objMCommissionBusinessman->getBusinessmanGrade($params);
  912. if (!$commissionBusinessmanResult->isSuccess()) {
  913. return ResultWrapper::fail($commissionBusinessmanResult->getData(), $commissionBusinessmanResult->getErrorCode());
  914. }
  915. return ResultWrapper::success($commissionBusinessmanResult->getData());
  916. }
  917. /**
  918. * 处理单独设置佣金的商品
  919. * @param array $orderGoods 订单商品
  920. * @return ResultWrapper
  921. */
  922. private function getGoodsRule(array $orderGoods)
  923. {
  924. // 提取所有订单商品id并映射
  925. $goodsIds = [];
  926. $orderGoodsMap = [];
  927. foreach ($orderGoods as $goods) {
  928. $goodsIds[] = $goods['goodsId'];
  929. $orderGoodsMap[$goods['goodsId']] = $goods;
  930. }
  931. // 获取商品是否参与分销是否单独有设置比率
  932. $goodsData = $this->objDGoods->select(['id' => $goodsIds], 'id,isJoinCommission,isDefine,retType');
  933. if ($goodsData === false) {
  934. return ResultWrapper::fail($this->objDGoods->error(), ErrorCode::$dberror);
  935. }
  936. if (empty($goodsData)) {
  937. return ResultWrapper::fail('获取商品分销设置失败', ErrorCode::$paramError);
  938. }
  939. // 过滤不参加分销的,并且筛选自定义佣金比例商品
  940. $defineGoods = []; // 自定义佣金商品集合
  941. $deleteGoods = []; // 不参与分销的商品集合
  942. $defaultGoods = []; // 默认佣金商品集合
  943. foreach ($goodsData as $key => $datum) {
  944. $orderGoodsMap[$datum['id']]['retType'] = $datum['retType'];
  945. // 未参与分销商品
  946. if ($datum['isJoinCommission'] == StatusCode::$delete) {
  947. $deleteGoods[] = array_merge($deleteGoods, $orderGoodsMap[$datum['id']]);
  948. unset($orderGoodsMap[$datum['id']]);
  949. continue;
  950. }
  951. // 自定义佣金商品
  952. if ($datum['isDefine'] == StatusCode::$standard) {
  953. $defineGoods[] = array_merge($defineGoods, $orderGoodsMap[$datum['id']]);
  954. unset($orderGoodsMap[$datum['id']]);
  955. continue;
  956. }
  957. //剩下的都是默认的佣金配置
  958. $defaultGoods[] = array_merge($defaultGoods, $orderGoodsMap[$datum['id']]);
  959. }
  960. // 自定义佣金商品不为空
  961. if (!empty($defineGoods)) {
  962. $skuIds = [];
  963. foreach ($defineGoods as $item) {
  964. $skuIds[] = $item['skuId'];
  965. }
  966. // 查询单独设置佣金的商品设置内容
  967. $commissionGoods = $this->objDCommissionGoods->select(['skuId' => $skuIds, 'deleteStatus' => StatusCode::$standard], 'commissionRule,goodsId,skuId');
  968. if ($commissionGoods === false) {
  969. return ResultWrapper::fail($this->objDCommissionGoods->error(), ErrorCode::$dberror);
  970. }
  971. if (empty($commissionGoods)) {
  972. return ResultWrapper::fail('获取自定义商品佣金比例为空', ErrorCode::$paramError);
  973. }
  974. $commissionGoodsMap = [];
  975. foreach ($commissionGoods as $item) {
  976. $commissionGoodsMap[$item['skuId']] = empty($item['commissionRule']) ? [] : json_decode($item['commissionRule'], true);
  977. }
  978. foreach ($defineGoods as $key => $item) {
  979. $defineGoods[$key]['rule'] = isset($commissionGoodsMap[$item['skuId']]) ? $commissionGoodsMap[$item['skuId']] : [];
  980. }
  981. }
  982. $return = [
  983. 'defaultGoods' => $defaultGoods,
  984. 'defineGoods' => $defineGoods
  985. ];
  986. return ResultWrapper::success($return);
  987. }
  988. /**
  989. * Doc: (des="检测是否达到升级的条件")
  990. * User: XMing
  991. * Date: 2020/7/25
  992. * Time: 9:49 上午
  993. */
  994. public function upgrade()
  995. {
  996. //test-demo
  997. /*$this->needUserCenterIds = [
  998. 168, 169, 140
  999. ];*/
  1000. //获取分销商的等级
  1001. //需要检测是否升级的用户id
  1002. if (empty($this->needUserCenterIds)) {
  1003. return ResultWrapper::success('没有需要升级的分销商');
  1004. }
  1005. //获取所有等级
  1006. $gradeConditionResult = $this->objMCommissionGrade->getAllGradeCondition(['type' => StatusCode::$delete]);
  1007. if (!$gradeConditionResult->isSuccess()){
  1008. return ResultWrapper::fail($gradeConditionResult->getData(),$gradeConditionResult->getErrorCode());
  1009. }
  1010. $gradeCondition = $gradeConditionResult->getData();
  1011. if (empty($gradeCondition)){
  1012. return ResultWrapper::fail('等级条件未配置',ErrorCode::$paramError);
  1013. }
  1014. $this->allAliasCondition = array_column($gradeCondition,'key');
  1015. //获取这批用户的当前等级
  1016. $commissionBusinessmanResult = $this->objMCommissionBusinessman->getBusinessmanGrade($this->needUserCenterIds);
  1017. if (!$commissionBusinessmanResult->isSuccess()) {
  1018. return ResultWrapper::fail($commissionBusinessmanResult->getData(), $commissionBusinessmanResult->getErrorCode());
  1019. }
  1020. $commissionBusinessman = $commissionBusinessmanResult->getData();
  1021. //查询等级升级条件
  1022. $gradeUpgradeConditionAllResult = $this->objMCommissionGrade->getAllGrade();
  1023. if (!$gradeUpgradeConditionAllResult->isSuccess()) {
  1024. return ResultWrapper::fail($gradeUpgradeConditionAllResult->getData(), $gradeUpgradeConditionAllResult->getErrorCode());
  1025. }
  1026. $gradeUpgradeConditionAll = $gradeUpgradeConditionAllResult->getData();
  1027. $gradeUpgradeConditionMap = [];//等级对应升级条件
  1028. foreach ($gradeUpgradeConditionAll as $item) {
  1029. $gradeUpgradeConditionMap[$item['grade']] = $item;
  1030. }
  1031. $allUserCenterIds = [];
  1032. foreach ($commissionBusinessman as $userCenterId => $value) {
  1033. $nextGrade = (int)$value['grade'] + 1;
  1034. $commissionBusinessman[$userCenterId]['nextCondition'] = [];
  1035. if (!isset($gradeUpgradeConditionMap[$nextGrade])) {
  1036. unset($commissionBusinessman[$userCenterId]);
  1037. continue;
  1038. }
  1039. $commissionBusinessman[$userCenterId]['nextCondition'] = $gradeUpgradeConditionMap[$nextGrade]['upgradeConditionInfo'];
  1040. $commissionBusinessman[$userCenterId]['nextGrade'] = $nextGrade;
  1041. $commissionBusinessman[$userCenterId]['upgradeMode'] = $gradeUpgradeConditionMap[$nextGrade]['upgradeMode'];//是否需要满足所有条件 5是 4否
  1042. $commissionBusinessman[$userCenterId]['nextGradeId'] = $gradeUpgradeConditionMap[$nextGrade]['id'];//是否需要满足所有条件 5是 4否
  1043. $allUserCenterIds[] = $userCenterId;
  1044. }
  1045. if (empty($commissionBusinessman)) {
  1046. return ResultWrapper::success('没有需要升级的分销商');
  1047. }
  1048. //获取分销商的统计数据
  1049. $statisticsResult = self::statisticsData($allUserCenterIds);
  1050. if (!$statisticsResult->isSuccess()) {
  1051. return ResultWrapper::fail($statisticsResult->getData(), $statisticsResult->getErrorCode());
  1052. }
  1053. $statisticsData = $statisticsResult->getData();
  1054. if (empty($statisticsData)){
  1055. return ResultWrapper::fail('获取分销商统计数据为空',ErrorCode::$paramError);
  1056. }
  1057. $upgradeData = [];//需要升级的分销商数据
  1058. foreach ($commissionBusinessman as $userCenterId => $item){
  1059. //获取分销商统计数据
  1060. if (!isset($statisticsData[$userCenterId])){
  1061. continue;
  1062. }
  1063. $commissionData = $statisticsData[$userCenterId];
  1064. $upgradeBool = self::checkCommissionConditionGrad($item['nextCondition'],$commissionData,$item['upgradeMode']);
  1065. if ($upgradeBool == false){
  1066. //不满足条件
  1067. continue;
  1068. }
  1069. //升级
  1070. $upgradeData[] = [
  1071. 'id' => $item['businessmanId'],
  1072. 'userCenterId' => $item['userCenterId'],
  1073. 'grade' => $item['nextGrade'],
  1074. 'gradeId' => $item['nextGradeId'],
  1075. 'updateTime' => time()
  1076. ];
  1077. }
  1078. //操作数据库
  1079. if(empty($upgradeData)){
  1080. return ResultWrapper::success('没有需要升级的分销商');
  1081. }
  1082. $this->objDCommissionBusinessman->beginTransaction();
  1083. foreach ($upgradeData as $datum){
  1084. $update = $this->objDCommissionBusinessman->update([
  1085. 'grade' => $datum['grade'],
  1086. 'gradeId' => $datum['gradeId'],
  1087. 'updateTime' => $datum['updateTime']
  1088. ],[ 'userCenterId' => $datum['userCenterId']]);
  1089. if ($update === false){
  1090. $this->objDCommissionBusinessman->rollBack();
  1091. return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror);
  1092. }
  1093. }
  1094. $this->objDCommissionBusinessman->commit();
  1095. Logger::logs(E_USER_ERROR,'升级的数据',__CLASS__,__LINE__,$upgradeData);
  1096. return ResultWrapper::success('操作成功');
  1097. }
  1098. /**
  1099. * Doc: (des="判断分销商是否满足对应条件")
  1100. * User: XMing
  1101. * Date: 2020/7/25
  1102. * Time: 3:37 下午
  1103. * @param array $nextCondition 升到下一级所需要的条件
  1104. * @param array $commissionData 分销商的统计数据
  1105. * @param int $upgradeMode 是否需要满足所有条件 4:否 5:是
  1106. * @return boolean
  1107. * 升级 => true
  1108. */
  1109. private function checkCommissionConditionGrad(array $nextCondition,array $commissionData,int $upgradeMode)
  1110. {
  1111. $num = count($nextCondition);
  1112. $meet = 0;//满足条件的数目
  1113. foreach ($nextCondition as $item){
  1114. $data = isset($commissionData[$item['key']]) ? $commissionData[$item['key']] : 0;
  1115. if ($data >= $item['value']){
  1116. //满足条件
  1117. if ($upgradeMode == StatusCode::$delete){
  1118. //满足任意条件即可
  1119. return true;
  1120. }
  1121. $meet = $meet + 1;
  1122. }
  1123. }
  1124. //不符合升级条件
  1125. if ($meet == 0){
  1126. return false;
  1127. }
  1128. //满足 4任意条件 / 5全部条件
  1129. switch ($upgradeMode){
  1130. case StatusCode::$delete:
  1131. //满足一个条件即可
  1132. if ($meet > 0) return true;
  1133. break;
  1134. case StatusCode::$standard:
  1135. if ($meet == $num) return true;
  1136. break;
  1137. }
  1138. return false;
  1139. }
  1140. /**
  1141. * Doc: (des="统计分销商的数据")
  1142. * User: XMing
  1143. * Date: 2020/7/25
  1144. * Time: 3:30 下午
  1145. *
  1146. * orderMoney 分销订单总额
  1147. * orderNum 分销订单总数
  1148. * oneOrderMoney 一级分销订单总额
  1149. * oneOrderNum 一级分销订单总数
  1150. * selfOrderMoney 自购订单总额
  1151. * selfOrderNum 自购订单总数
  1152. * sub 下线人数
  1153. * subBusinessman 下线分销商人数
  1154. * oneSub 一级下线人数
  1155. * oneSubBusinessman 一级下线分销商人数
  1156. * withdraw 已提现金额
  1157. * buyCard 购买会员卡
  1158. *
  1159. * @param array $userCenterIds
  1160. * @return ResultWrapper
  1161. */
  1162. private function statisticsData(array $userCenterIds)
  1163. {
  1164. //demo
  1165. /**$map = [
  1166. 168 => [
  1167. 'orderMoney' => 100,
  1168. 'orderNum' => 1,
  1169. 'oneOrderMoney' => 100,
  1170. 'oneOrderNum' => 1,
  1171. 'selfOrderMoney' => 100,
  1172. 'selfOrderNum' => 1,
  1173. 'sub' => 10,
  1174. 'subBusinessman' => 1,
  1175. 'oneSub' => 10,
  1176. 'oneSubBusinessman' => 1,
  1177. 'withdraw' => 100,
  1178. 'buyCard' => true
  1179. ]
  1180. ];*/
  1181. $businessmanStatisticsResult = $this->objMCommissionBusinessman->getBusinessmanStatistics($userCenterIds);
  1182. if (!$businessmanStatisticsResult->isSuccess()){
  1183. return ResultWrapper::fail($businessmanStatisticsResult->getData(),$businessmanStatisticsResult->getErrorCode());
  1184. }
  1185. //统计分销商的订单总辆
  1186. return ResultWrapper::success($businessmanStatisticsResult->getData());
  1187. }
  1188. /**
  1189. * Doc: (des="增加分销商品的销量佣金")
  1190. * User: XMing
  1191. * Date: 2020/7/28
  1192. * Time: 9:15 上午
  1193. * @param array $data
  1194. * @return ResultWrapper
  1195. */
  1196. private function incrCommissionGoods(array $data)
  1197. {
  1198. $allSkuIds = [];
  1199. foreach ($data as $value){
  1200. $allSkuIds[] = $value['skuId'];
  1201. }
  1202. //获取这批数据记录
  1203. $oldCommissionGoodsStatistics = $this->objDCommissionGoodsStatistics->select(['skuId'=>$allSkuIds]);
  1204. if ($oldCommissionGoodsStatistics === false){
  1205. return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror);
  1206. }
  1207. //给对应的商品增加销量以及商品佣金
  1208. $commissionGoodsMap = [];
  1209. foreach ($oldCommissionGoodsStatistics as $item){
  1210. $commissionGoodsMap[$item['skuId']] = $item;
  1211. }
  1212. $replace = [];
  1213. foreach ($data as $datum){
  1214. $oldSalesNum = isset($commissionGoodsMap[$datum['skuId']]['salesNum']) ? $commissionGoodsMap[$datum['skuId']]['salesNum'] : 0;
  1215. $oldCommission = isset($commissionGoodsMap[$datum['skuId']]['commission']) ? $commissionGoodsMap[$datum['skuId']]['commission'] : 0;
  1216. $replace[] = [
  1217. 'goodsId' => $datum['goodsId'],
  1218. 'skuId' => $datum['skuId'],
  1219. 'salesNum' => bcadd($oldSalesNum,$datum['buyNum']),
  1220. 'commission' => bcadd($oldCommission,$datum['retMoney']),
  1221. 'createTime' => time()
  1222. ];
  1223. }
  1224. if (empty($replace)){
  1225. return ResultWrapper::success('没有数据需要更新');
  1226. }
  1227. $replace = $this->objDCommissionGoodsStatistics->replace($replace,true);
  1228. if ($replace === false){
  1229. return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror);
  1230. }
  1231. return ResultWrapper::success('操作成功');
  1232. }
  1233. public function updateBalanceNew(int $orderId){
  1234. }
  1235. /**
  1236. * Doc: (des="订单完成将等待入账转移到余额")
  1237. * User: XMing
  1238. * Date: 2020/7/30
  1239. * Time: 5:15 下午
  1240. * @param int $orderId
  1241. * @return ResultWrapper
  1242. */
  1243. public function updateBalance(int $orderId)
  1244. {
  1245. $commissionDataResult = self::getOrderIndexData($orderId);
  1246. if (!$commissionDataResult->isSuccess()){
  1247. return ResultWrapper::fail($commissionDataResult->getData(),$commissionDataResult->getErrorCode());
  1248. }
  1249. $commissionData = $commissionDataResult->getData();
  1250. $selfCommissionData = isset($commissionData['self']) ? $commissionData['self'] : [];
  1251. $oneCommissionData = isset($commissionData['oneRet']) ? $commissionData['oneRet'] : [];
  1252. $twoCommissionData = isset($commissionData['twoRet']) ? $commissionData['twoRet'] : [];
  1253. $threeCommissionData = isset($commissionData['threeRet']) ? $commissionData['threeRet'] : [];
  1254. $allUserCenterIds = array_column($commissionData,'retUserCenterId');
  1255. //获取分销商的余额
  1256. $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allUserCenterIds], 'id,userCenterId,customerId,balance,waitMoney');
  1257. if ($businessman === false) {
  1258. return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror);
  1259. }
  1260. if(empty($businessman)){
  1261. return ResultWrapper::fail('获取分销商数据为空',ErrorCode::$paramError);
  1262. }
  1263. $businessmanMap = [];
  1264. foreach ($businessman as $value){
  1265. $businessmanMap[$value['userCenterId']] = $value;
  1266. }
  1267. $updateDataResult = self::buildUpdateData($selfCommissionData,$oneCommissionData,$twoCommissionData,$threeCommissionData,$businessmanMap);
  1268. if (!$updateDataResult->isSuccess()){
  1269. return ResultWrapper::fail($updateDataResult->getData(),$updateDataResult->getErrorCode());
  1270. }
  1271. $updateData = $updateDataResult->getData();
  1272. if (empty($updateData)){
  1273. return ResultWrapper::fail('组装分销商更新数据失败',ErrorCode::$paramError);
  1274. }
  1275. $this->objDCommissionBusinessman->beginTransaction();
  1276. foreach ($updateData as $value){
  1277. //分销商账户表
  1278. $update = $this->objDCommissionBusinessman->update(
  1279. [
  1280. 'balance' => $value['balance'],
  1281. 'waitMoney' => $value['waitMoney'],
  1282. 'updateTime' => time(),
  1283. ],
  1284. [
  1285. 'userCenterId'=> $value['userCenterId']
  1286. ]
  1287. );
  1288. if ($update === false){
  1289. $this->objDCommissionBusinessman->rollBack();
  1290. return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror);
  1291. }
  1292. //资金变动记录表
  1293. $logResult = self::changeLog($value, $value['changeMoney'],$value['balance'], StatusCode::$standard, '分佣');
  1294. if (!$logResult->isSuccess()){
  1295. $this->objDCommissionBusinessman->rollBack();
  1296. return ResultWrapper::fail($logResult->getData(),$logResult->getErrorCode());
  1297. }
  1298. }
  1299. //更新这批分销订单
  1300. $updateCommissionOrderIndex = $this->objDCommissionOrderIndex->update(
  1301. [
  1302. 'isAccount' => StatusCode::$standard,
  1303. 'updateTime'=>time()
  1304. ],
  1305. [
  1306. 'orderId' => $orderId
  1307. ]
  1308. );
  1309. if ($updateCommissionOrderIndex === false){
  1310. $this->objDCommissionBusinessman->rollBack();
  1311. }
  1312. $this->objDCommissionBusinessman->commit();
  1313. return ResultWrapper::success('更新分销商佣金成功');
  1314. }
  1315. /**
  1316. * Doc: (des="构建分销商更新数据")
  1317. * User: XMing
  1318. * Date: 2020/7/30
  1319. * Time: 6:09 下午
  1320. * @param array $selfCommissionData
  1321. * @param array $oneCommissionData
  1322. * @param array $twoCommissionData
  1323. * @param array $threeCommissionData
  1324. * @param array $businessmanMap
  1325. * @return ResultWrapper
  1326. */
  1327. private function buildUpdateData(array $selfCommissionData,array $oneCommissionData,array $twoCommissionData,array $threeCommissionData,array $businessmanMap)
  1328. {
  1329. $updateMap = [];
  1330. if (!empty($selfCommissionData)){
  1331. //自购返佣
  1332. //原等待入账
  1333. if (!isset($businessmanMap[$selfCommissionData['retUserCenterId']])){
  1334. return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError);
  1335. }
  1336. $oldWaitMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['waitMoney'];
  1337. $oldBalance = $businessmanMap[$selfCommissionData['retUserCenterId']]['balance'];
  1338. $changeMoney = $selfCommissionData['retMoney'];
  1339. $updateMap[] = [
  1340. 'userCenterId' => $selfCommissionData['retUserCenterId'],
  1341. 'oldBalance' => $oldBalance,//原账户金额
  1342. 'changeMoney' => $changeMoney,//变动金额
  1343. 'balance' => bcadd($oldBalance,$changeMoney,2),//变动后金额
  1344. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1345. 'customerId' => $businessmanMap[$selfCommissionData['retUserCenterId']]['customerId'],
  1346. 'businessmanId' => $businessmanMap[$selfCommissionData['retUserCenterId']]['id'],
  1347. 'updateTime' => time(),
  1348. ];
  1349. }
  1350. if (!empty($oneCommissionData)){
  1351. //一级返佣
  1352. if (!isset($businessmanMap[$oneCommissionData['retUserCenterId']])){
  1353. return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError);
  1354. }
  1355. $oldWaitMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['waitMoney'];
  1356. $oldBalance = $businessmanMap[$oneCommissionData['retUserCenterId']]['balance'];
  1357. $changeMoney = $oneCommissionData['retMoney'];
  1358. $updateMap[] = [
  1359. 'userCenterId' => $oneCommissionData['retUserCenterId'],
  1360. 'oldBalance' => $oldBalance,//原账户金额
  1361. 'changeMoney' => $changeMoney,//变动金额
  1362. 'balance' => bcadd($oldBalance,$changeMoney,2),
  1363. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1364. 'customerId' => $businessmanMap[$oneCommissionData['retUserCenterId']]['customerId'],
  1365. 'businessmanId' => $businessmanMap[$oneCommissionData['retUserCenterId']]['id'],
  1366. 'updateTime' => time(),
  1367. ];
  1368. }
  1369. if (!empty($twoCommissionData)){
  1370. //二级返佣
  1371. if (!isset($businessmanMap[$twoCommissionData['retUserCenterId']])){
  1372. return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError);
  1373. }
  1374. $oldWaitMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['waitMoney'];
  1375. $oldBalance = $businessmanMap[$twoCommissionData['retUserCenterId']]['balance'];
  1376. $changeMoney = $twoCommissionData['retMoney'];
  1377. $updateMap[] = [
  1378. 'userCenterId' => $twoCommissionData['retUserCenterId'],
  1379. 'oldBalance' => $oldBalance,//原账户金额
  1380. 'changeMoney' => $changeMoney,//变动金额
  1381. 'balance' => bcadd($oldBalance,$changeMoney,2),
  1382. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1383. 'customerId' => $businessmanMap[$twoCommissionData['retUserCenterId']]['customerId'],
  1384. 'businessmanId' => $businessmanMap[$twoCommissionData['retUserCenterId']]['id'],
  1385. 'updateTime' => time(),
  1386. ];
  1387. }
  1388. if (!empty($threeCommissionData)){
  1389. //三级
  1390. if (!isset($businessmanMap[$threeCommissionData['retUserCenterId']])){
  1391. return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError);
  1392. }
  1393. $oldWaitMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['waitMoney'];
  1394. $oldBalance = $businessmanMap[$threeCommissionData['retUserCenterId']]['balance'];
  1395. $changeMoney = $threeCommissionData['retMoney'];
  1396. $updateMap[] = [
  1397. 'userCenterId' => $threeCommissionData['retUserCenterId'],
  1398. 'oldBalance' => $oldBalance,//原账户金额
  1399. 'changeMoney' => $changeMoney,//变动金额
  1400. 'balance' => bcadd($oldBalance,$changeMoney,2),
  1401. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1402. 'customerId' => $businessmanMap[$threeCommissionData['retUserCenterId']]['customerId'],
  1403. 'businessmanId' => $businessmanMap[$threeCommissionData['retUserCenterId']]['id'],
  1404. 'updateTime' => time(),
  1405. ];
  1406. }
  1407. if (!empty($updateMap)){
  1408. Logger::logs(E_USER_ERROR,'分销商更新数据',__CLASS__,__LINE__,$updateMap);
  1409. }
  1410. return ResultWrapper::success($updateMap);
  1411. }
  1412. /**
  1413. * Doc: (des="根据订单id获取订单的分销信息")
  1414. * User: XMing
  1415. * Date: 2020/7/31
  1416. * Time: 5:15 下午
  1417. * @param int $orderId
  1418. * @param string $fields
  1419. * @return ResultWrapper
  1420. */
  1421. private function getOrderIndexData(int $orderId,string $fields = 'id,commissionData,isCommission')
  1422. {
  1423. $orderIndex = $this->objDOrderIndex->get(['id'=>$orderId],$fields);
  1424. if ($orderIndex === false){
  1425. return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror);
  1426. }
  1427. if (empty($orderIndex)){
  1428. return ResultWrapper::fail('获取分销订单数据为空',ErrorCode::$paramError);
  1429. }
  1430. if ($orderIndex['isCommission'] != StatusCode::$standard){
  1431. return ResultWrapper::fail('不是分销订单',ErrorCode::$paramError);
  1432. }
  1433. $commissionData = json_decode($orderIndex['commissionData'],true);
  1434. if (empty($commissionData)){
  1435. return ResultWrapper::fail('返佣数据为空',ErrorCode::$paramError);
  1436. }
  1437. return ResultWrapper::success($commissionData);
  1438. }
  1439. /**
  1440. * Doc: (des="分销订单取消,扣除返佣")
  1441. * User: XMing
  1442. * Date: 2020/7/31
  1443. * Time: 3:51 下午
  1444. * @param int $orderId
  1445. * @example
  1446. * @return ResultWrapper
  1447. *
  1448. */
  1449. public function cancelSubCommission(int $orderId)
  1450. {
  1451. $commissionDataResult = self::getOrderIndexData($orderId);
  1452. if (!$commissionDataResult->isSuccess()){
  1453. return ResultWrapper::fail($commissionDataResult->getData(),$commissionDataResult->getErrorCode());
  1454. }
  1455. $commissionData = $commissionDataResult->getData();
  1456. $selfCommissionData = isset($commissionData['self']) ? $commissionData['self'] : [];
  1457. $oneCommissionData = isset($commissionData['oneRet']) ? $commissionData['oneRet'] : [];
  1458. $twoCommissionData = isset($commissionData['twoRet']) ? $commissionData['twoRet'] : [];
  1459. $threeCommissionData = isset($commissionData['threeRet']) ? $commissionData['threeRet'] : [];
  1460. $allUserCenterIds = array_column($commissionData,'retUserCenterId');
  1461. //获取分销商的余额
  1462. $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allUserCenterIds], 'id,userCenterId,balance,totalMoney,waitMoney');
  1463. if ($businessman === false) {
  1464. return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror);
  1465. }
  1466. if(empty($businessman)){
  1467. return ResultWrapper::fail('获取分销商数据为空',ErrorCode::$paramError);
  1468. }
  1469. $businessmanMap = [];
  1470. foreach ($businessman as $value){
  1471. $businessmanMap[$value['userCenterId']] = $value;
  1472. }
  1473. $updateDataResult = self::buildCancelData($selfCommissionData,$oneCommissionData,$twoCommissionData,$threeCommissionData,$businessmanMap);
  1474. if (!$updateDataResult->isSuccess()){
  1475. return ResultWrapper::fail($updateDataResult->getData(),$updateDataResult->getErrorCode());
  1476. }
  1477. $updateData = $updateDataResult->getData();
  1478. if (empty($updateData)){
  1479. return ResultWrapper::fail('组装分销商更新数据失败',ErrorCode::$paramError);
  1480. }
  1481. $this->objDCommissionBusinessman->beginTransaction();
  1482. foreach ($updateData as $value){
  1483. $update = $this->objDCommissionBusinessman->update(
  1484. [
  1485. 'waitMoney' => $value['waitMoney'],
  1486. 'totalMoney' => $value['totalMoney'],
  1487. 'updateTime' => time(),
  1488. ],
  1489. [
  1490. 'userCenterId'=> $value['userCenterId']
  1491. ]
  1492. );
  1493. if ($update === false){
  1494. $this->objDCommissionBusinessman->rollBack();
  1495. return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror);
  1496. }
  1497. }
  1498. //更新这批分销订单取消
  1499. $updateCommissionOrderIndex = $this->objDCommissionOrderIndex->update(
  1500. [
  1501. 'isAccount' => StatusCode::$auditStatus['auditNotPass'],//3已取消
  1502. 'updateTime'=>time()
  1503. ],
  1504. [
  1505. 'orderId' => $orderId
  1506. ]
  1507. );
  1508. if ($updateCommissionOrderIndex === false){
  1509. $this->objDCommissionBusinessman->rollBack();
  1510. }
  1511. $this->objDCommissionBusinessman->commit();
  1512. return ResultWrapper::success('更新分销商佣金成功');
  1513. }
  1514. /**
  1515. * Doc: (des="取消分销订单,分销商更新数据")
  1516. * User: XMing
  1517. * Date: 2020/7/31
  1518. * Time: 5:50 下午
  1519. * @param array $selfCommissionData
  1520. * @param array $oneCommissionData
  1521. * @param array $twoCommissionData
  1522. * @param array $threeCommissionData
  1523. * @param array $businessmanMap
  1524. * @return ResultWrapper
  1525. */
  1526. private function buildCancelData(array $selfCommissionData,array $oneCommissionData,array $twoCommissionData,array $threeCommissionData,array $businessmanMap)
  1527. {
  1528. $updateMap = [];
  1529. if (!empty($selfCommissionData)){
  1530. if (!isset($businessmanMap[$selfCommissionData['retUserCenterId']])){
  1531. return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror);
  1532. }
  1533. $oldWaitMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['waitMoney'];
  1534. $oldTotalMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['totalMoney'];
  1535. //获取当前分销商的等待入账金额
  1536. $changeMoney = $selfCommissionData['retMoney'];
  1537. $updateMap[] = [
  1538. 'userCenterId' => $selfCommissionData['retUserCenterId'],
  1539. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1540. 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2),
  1541. 'updateTime' => time(),
  1542. ];
  1543. }
  1544. if (!empty($oneCommissionData)){
  1545. if (!isset($businessmanMap[$oneCommissionData['retUserCenterId']])){
  1546. return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror);
  1547. }
  1548. $oldWaitMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['waitMoney'];
  1549. $oldTotalMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['totalMoney'];
  1550. //获取当前分销商的等待入账金额
  1551. $changeMoney = $oneCommissionData['retMoney'];
  1552. $updateMap[] = [
  1553. 'userCenterId' => $oneCommissionData['retUserCenterId'],
  1554. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1555. 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2),
  1556. 'updateTime' => time(),
  1557. ];
  1558. }
  1559. if (!empty($twoCommissionData)){
  1560. if (!isset($businessmanMap[$twoCommissionData['retUserCenterId']])){
  1561. return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror);
  1562. }
  1563. $oldWaitMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['waitMoney'];
  1564. $oldTotalMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['totalMoney'];
  1565. //获取当前分销商的等待入账金额
  1566. $changeMoney = $twoCommissionData['retMoney'];
  1567. $updateMap[] = [
  1568. 'userCenterId' => $twoCommissionData['retUserCenterId'],
  1569. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1570. 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2),
  1571. 'updateTime' => time(),
  1572. ];
  1573. }
  1574. if (!empty($threeCommissionData)){
  1575. if (!isset($businessmanMap[$threeCommissionData['retUserCenterId']])){
  1576. return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror);
  1577. }
  1578. $oldWaitMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['waitMoney'];
  1579. $oldTotalMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['totalMoney'];
  1580. //获取当前分销商的等待入账金额
  1581. $changeMoney = $threeCommissionData['retMoney'];
  1582. $updateMap[] = [
  1583. 'userCenterId' => $threeCommissionData['retUserCenterId'],
  1584. 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2),
  1585. 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2),
  1586. 'updateTime' => time(),
  1587. ];
  1588. }
  1589. if (!empty($updateMap)){
  1590. Logger::logs(E_USER_ERROR,'分销订单取消,更新分销商数据',__CLASS__,__LINE__,$updateMap);
  1591. }
  1592. return ResultWrapper::success($updateMap);
  1593. }
  1594. /**
  1595. * Doc: (des="提现状态变更,操作分销商数据")
  1596. * User: XMing
  1597. * Date: 2020/7/31
  1598. * Time: 4:06 下午
  1599. * @param array $withdraw
  1600. * @param int $status
  1601. * @return ResultWrapper
  1602. * @example
  1603. * balance 余额
  1604. * waitAuditWithdraw 提现待审核金额
  1605. * auditWithdraw 提现待入账金额
  1606. * withdraw 已提现金额
  1607. */
  1608. public function buildWithdraw(array $withdraw,int $status)
  1609. {
  1610. $businessman = $this->objDCommissionBusinessman->get(['id'=>$withdraw['businessmanId']],'id,userCenterId,balance,waitAuditWithdraw,auditWithdraw,withdraw');
  1611. if ($businessman === false){
  1612. return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror);
  1613. }
  1614. if (empty($businessman)){
  1615. return ResultWrapper::fail('获取分销商账户信息失败',ErrorCode::$paramError);
  1616. }
  1617. $oldBalance = $businessman['balance'];//可提现
  1618. $oldWaitAuditWithdraw = $businessman['waitAuditWithdraw'];//提现等待审核
  1619. $oldAuditWithdraw = $businessman['auditWithdraw'];//提现待入账金额
  1620. $oldWithdraw = $businessman['withdraw'];//已提现金额
  1621. $changeMoney = $withdraw['money'];//本次变动金额
  1622. $updateMap = [];//需要更新的数据
  1623. switch ($status){
  1624. case StatusCode::$auditStatus['auditing']:
  1625. //申请提现操作
  1626. if ($oldBalance < $withdraw['money']){
  1627. return ResultWrapper::fail('可提现金额不足',ErrorCode::$paramError);
  1628. }
  1629. $updateMap = [
  1630. 'id' => $businessman['id'],
  1631. 'updateTime' => time(),
  1632. 'balance' => bcsub($oldBalance,$changeMoney,2),
  1633. 'waitAuditWithdraw' => bcadd($oldWaitAuditWithdraw,$changeMoney,2),
  1634. ];
  1635. break;
  1636. case StatusCode::$auditStatus['auditPass']:
  1637. //打款成功
  1638. if (bcsub($oldAuditWithdraw,$changeMoney,2) < 0){
  1639. return ResultWrapper::fail('待入账金额不足',ErrorCode::$paramError);
  1640. }
  1641. $updateMap = [
  1642. 'id' => $businessman['id'],
  1643. 'updateTime' => time(),
  1644. 'auditWithdraw' => bcsub($oldAuditWithdraw,$changeMoney,2),
  1645. 'withdraw' => bcadd($oldWithdraw,$changeMoney,2),
  1646. ];
  1647. break;
  1648. case StatusCode::$auditStatus['auditNotPass']:
  1649. //提现审核拒绝,回到余额
  1650. if (bcsub($oldWaitAuditWithdraw,$changeMoney,2) < 0){
  1651. return ResultWrapper::fail('待审核金额不足',ErrorCode::$paramError);
  1652. }
  1653. $updateMap = [
  1654. 'id' => $businessman['id'],
  1655. 'updateTime' => time(),
  1656. 'balance' => bcadd($oldBalance,$changeMoney,2),
  1657. 'waitAuditWithdraw' => bcsub($oldWaitAuditWithdraw,$changeMoney,2),
  1658. ];
  1659. break;
  1660. case StatusCode::$auditStatus['auditIng']:
  1661. //等待打款,审核成功
  1662. if (bcsub($oldWaitAuditWithdraw,$changeMoney,2) < 0){
  1663. return ResultWrapper::fail('待审核金额不足',ErrorCode::$paramError);
  1664. }
  1665. $updateMap = [
  1666. 'id' => $businessman['id'],
  1667. 'updateTime' => time(),
  1668. 'waitAuditWithdraw' => bcsub($oldWaitAuditWithdraw,$changeMoney,2),
  1669. 'auditWithdraw' => bcadd($oldAuditWithdraw,$changeMoney,2),
  1670. ];
  1671. break;
  1672. default:
  1673. return ResultWrapper::fail('状态值有误',ErrorCode::$paramError);
  1674. break;
  1675. }
  1676. if (!empty($updateMap)){
  1677. Logger::logs(E_USER_ERROR,'提现变动数据',__CLASS__,__LINE__,$updateMap);
  1678. }
  1679. return ResultWrapper::success($updateMap);
  1680. }
  1681. /**
  1682. * Doc: (des="佣金变动记录 balance")
  1683. * User: XMing
  1684. * Date: 2020/8/3
  1685. * Time: 2:32 下午
  1686. * @param array $data
  1687. * @param float $changeAmount 变动金额
  1688. * @param float $balance 变动后金额
  1689. * @param int $type +/-
  1690. * @param string $des 描述
  1691. * @return ResultWrapper
  1692. */
  1693. private function changeLog(array $data,float $changeAmount,float $balance,int $type,string $des="")
  1694. {
  1695. $insertRes = $this->objDCommissionFlow->insert([
  1696. "userCenterId" => $data['userCenterId'] ,//int(10) DEFAULT NULL,
  1697. "customerId" => $data['customerId'],//int(10) DEFAULT NULL COMMENT '客户id',
  1698. "businessmanId" => $data['businessmanId'] ,//int(10) DEFAULT NULL COMMENT '分销商id',
  1699. "amount" => $changeAmount,//decimal(8,2) DEFAULT NULL COMMENT '金额',
  1700. "changeAmount" => $balance ,//decimal(8,2) DEFAULT NULL COMMENT '变动后金额',
  1701. "type"=>$type ,//tinyint(1) DEFAULT NULL COMMENT '状态 4:减 5:加',
  1702. "des" => $des,
  1703. "createTime" => time(),
  1704. ]);
  1705. if ($insertRes === false){
  1706. return ResultWrapper::fail($this->objDCommissionFlow->error(),ErrorCode::$dberror);
  1707. }
  1708. return ResultWrapper::success('操作成功');
  1709. }
  1710. }