OrderClass.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. <?php
  2. namespace bizHd\order\classes;
  3. use biz\goods\classes\GoodsClass;
  4. use biz\goods\models\Goods;
  5. use biz\shop\classes\ShopAdminClass;
  6. use biz\shop\classes\ShopCapitalClass;
  7. use biz\shop\classes\ShopClass;
  8. use biz\shop\classes\ShopExtClass;
  9. use biz\shop\models\Shop;
  10. use biz\stat\classes\StatKdClass;
  11. use biz\stat\classes\StatOrderCountClass;
  12. use biz\stat\classes\StatSaleClass;
  13. use biz\stock\classes\GoodsStockRecordClass;
  14. use biz\wx\classes\WxMessageClass;
  15. use bizGhs\order\classes\CheckOrderClass;
  16. use bizGhs\product\classes\ProductClass;
  17. use bizGhs\stat\classes\StatYjClass;
  18. use bizGhs\stock\classes\StockRecordClass;
  19. use bizGhs\ws\services\WsService;
  20. use bizHd\custom\classes\CustomClass;
  21. use bizHd\merchant\classes\SjClass;
  22. use bizHd\order\classes\OrderItemClass;
  23. use bizHd\refund\classes\HdRefundClass;
  24. use bizHd\shop\classes\MainClass;
  25. use bizHd\shop\classes\ShopMoneyChangeClass;
  26. use bizHd\stat\classes\StatIncomeClass;
  27. use bizHd\stat\classes\StatOrderClass;
  28. use bizHd\user\classes\UserClass;
  29. use bizHd\work\classes\WorkClass;
  30. use bizHd\wx\classes\WxOpenClass;
  31. use common\components\dict;
  32. use common\components\imgUtil;
  33. use common\components\miniUtil;
  34. use common\components\noticeUtil;
  35. use common\components\orderSn;
  36. use common\components\printUtil;
  37. use common\components\util;
  38. use Yii;
  39. use bizHd\base\classes\BaseClass;
  40. use common\components\lakala\Lakala;
  41. class OrderClass extends BaseClass
  42. {
  43. public static $baseFile = '\bizHd\order\models\Order';
  44. //已取消
  45. const ORDER_STATUS_CANCEL = 5;
  46. //完成
  47. const ORDER_STATUS_COMPLETE = 4;
  48. //配送中
  49. const ORDER_STATUS_SENDING = 3;
  50. //待配送
  51. const ORDER_STATUS_UN_SEND = 2;
  52. //待付款
  53. const ORDER_STATUS_UN_PAY = 1;
  54. //订单总流程数
  55. const ORDER_TOTAL_FLOW = 4;
  56. //未确认配送方式
  57. const SEND_TYPE_UNKNOWN = 0;
  58. //自取
  59. const SEND_TYPE_NO = 1;
  60. //自己送
  61. const SEND_TYPE_MYSELF = 2;
  62. //快递送
  63. const SEND_TYPE_THIRD = 3;
  64. //正常订单
  65. const REFUND_NO = 0;
  66. //已退款订单
  67. const REFUND_YES = 1;
  68. //送达时间段
  69. public static $reachPeriod = [0 => '上午', 1 => '下午', 2 => '晚上'];
  70. //优惠金额
  71. public static $randDiscount = [
  72. 50 => [1, 3],
  73. 100 => [5, 9],
  74. 300 => [10, 15],
  75. 500 => [16, 18],
  76. 1000 => [18, 30],
  77. 20000 => [90, 100],
  78. ];
  79. /**
  80. * 售后付款单是否已经充值过了 ssh 20250801
  81. * @param $order
  82. * @param $set false 判断是否充值 true 标记为充值
  83. */
  84. public static function shOrderRecharge($order, $set = false)
  85. {
  86. $orderId = $order->id;
  87. $cacheKey = "sh_order_recharge_" . $orderId;
  88. if ($set) {
  89. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 864000, 'has']);
  90. } else {
  91. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  92. if (!empty($has)) {
  93. util::fail('已经充值过了,请勿重复操作');
  94. }
  95. }
  96. }
  97. //因为开负数订单时引导库存变化 ssh 20250731
  98. public static function shPayChange($order, $shop, $staff, $originOrder = null)
  99. {
  100. $forward = $order['forward'] ?? 0;
  101. if ($forward == 0) {
  102. return false;
  103. }
  104. $forwardStock = $order['forwardStock'] ?? 0;
  105. $orderSn = $order['orderSn'] ?? '';
  106. $orderItemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
  107. $orderGoodsList = OrderGoodsClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
  108. if (empty($orderItemList) && empty($orderGoodsList)) {
  109. return false;
  110. }
  111. $shopId = $shop->id ?? 0;
  112. $sjId = $shop->sjId ?? 0;
  113. $adminId = $staff->adminId;
  114. $staffName = $staff->name ?? '';
  115. $mainId = $shop->mainId;
  116. if (!empty($orderItemList)) {
  117. $itemInfo = [];
  118. $ids = array_column($orderItemList, 'itemId');
  119. $infoList = ProductClass::getAllByCondition(['id' => ['in', $ids]], null, '*', 'id');
  120. foreach ($orderItemList as $orderItem) {
  121. $unitType = $orderItem['unitType'] ?? 0;
  122. $num = $orderItem['num'] ?? 0;
  123. $productId = $orderItem['itemId'] ?? 0;
  124. $info = $infoList[$productId] ?? [];
  125. $stock = $info['stock'] ?? 0;
  126. $ratio = $info['ratio'] ?? 20;
  127. $map = ProductClass::formatStock($stock, $ratio);
  128. $bigNum = $map['bigNum'] ?? 0;
  129. $smallNum = $map['smallNum'] ?? 0;
  130. $num = $forwardStock == 0 ? $num * 2 : $num;
  131. if ($unitType == 0) {
  132. $bigNum = $bigNum + $num;
  133. } else {
  134. $smallNum = $smallNum + $num;
  135. }
  136. $itemInfo[] = ['productId' => $productId, 'bigNum' => $bigNum, 'smallNum' => $smallNum];
  137. }
  138. $remark = $forwardStock == 0 ? '开负数订单,退货并退款' : '开负数订单,只退款';
  139. $itemData = [
  140. 'remark' => $remark,
  141. 'itemInfo' => $itemInfo,
  142. 'sjId' => $sjId,
  143. 'shopId' => $shopId,
  144. 'adminId' => $adminId,
  145. 'staffName' => $staffName,
  146. ];
  147. CheckOrderClass::opOrder($itemData);
  148. }
  149. if (!empty($orderGoodsList)) {
  150. foreach ($orderGoodsList as $orderGoods) {
  151. $goodsId = $orderGoods['goodsId'] ?? 0;
  152. $num = $orderGoods['num'] ?? 0;
  153. $num = $forwardStock == 0 ? $num * 2 : $num;
  154. $ret = \bizHd\goods\classes\GoodsClass::addStock($goodsId, $mainId, $num);
  155. $oldStock = $ret['oldStock'] ?? 0;
  156. $newStock = $ret['newStock'] ?? 0;
  157. $recordData = [];
  158. $recordData['sjId'] = $sjId;
  159. $recordData['shopId'] = $shopId;
  160. $recordData['mainId'] = $mainId;
  161. $recordData['orderSn'] = '';
  162. $recordData['goodsId'] = $goodsId;
  163. $recordData['goodsNum'] = $num;
  164. $recordData['oldStock'] = $oldStock;
  165. $recordData['newStock'] = $newStock;
  166. $recordData['relateName'] = $staffName;
  167. GoodsStockRecordClass::pdGoods($recordData);
  168. }
  169. }
  170. if (is_object($order) && !empty($originOrder)) {
  171. //建立关系
  172. $originOrder->hasForward = 1;
  173. $originOrder->save();
  174. $map = ['orderId' => $originOrder->id, 'shOrderId' => $order->id];
  175. OrderForwardClass::add($map, true);
  176. }
  177. return true;
  178. }
  179. /**
  180. * @param $order
  181. * @param $mainId
  182. * @return array
  183. * $shAddPay 0走正常流程售后,1走售后付款单
  184. * $shAddPayReason 走售后付款单的原因:0、售后金额大于剩余欠款(剩余欠款可能没有了,可能还有);1、可售后时间到了
  185. */
  186. public static function ifShPay($order, $main, $refundAmount = 0)
  187. {
  188. $shAddPay = 0;
  189. $shAddPayReason = 0;
  190. $payStatus = $order['payStatus'] ?? 0;
  191. if ($payStatus == 1) {
  192. if ($order['payWay'] == 3) {
  193. if ($order['remainDebtPrice'] <= 0) {
  194. //不管是否要售后,没有剩余欠款了,只能走开负数订单模式
  195. $shAddPay = 1;
  196. } else {
  197. if ($refundAmount > 0 && $refundAmount > $order['remainDebtPrice']) {
  198. //如果需要售后,并且售后金额大于剩余欠款,走开负数订单模式
  199. $shAddPay = 1;
  200. }
  201. }
  202. }
  203. $cRet = OrderClass::couldRefund($order, $main);
  204. $could = $cRet['could'];
  205. if (!$could) {
  206. //可售后时间到了
  207. $shAddPay = 1;
  208. $shAddPayReason = 1;
  209. }
  210. }
  211. return ['shAddPay' => $shAddPay, 'shAddPayReason' => $shAddPayReason];
  212. }
  213. //订单是否过了可以售后的时间 ssh 20250730
  214. // $could false 过了售后时间,不能售后,true可以
  215. public static function couldRefund($order, $main)
  216. {
  217. $refundLimit = $main->refundLimit ?? 0;
  218. $payTime = $order['payTime'];
  219. $currentPayTime = strtotime($payTime);
  220. $addDateTime = $refundLimit * 86400;
  221. $couldRefundTime = $currentPayTime + $addDateTime;
  222. $now = time();
  223. $could = $couldRefundTime > $now;
  224. return ['could' => $could];
  225. }
  226. public static function valid($order, $mainId)
  227. {
  228. if (isset($order->mainId) == false || $order->mainId != $mainId) {
  229. Yii::info(json_encode($order));
  230. Yii::info('mainId: ' . $mainId);
  231. util::fail('无法访问的订单');
  232. }
  233. return true;
  234. }
  235. //添加订单 ssh 2019.12.5
  236. public static function addOrder($data)
  237. {
  238. $data['orderSn'] = $data['orderSn'] ?? orderSn::getOrderSn();
  239. $data['payStatus'] = $data['payStatus'] ?? 0;
  240. $shopId = $data['shopId'] ?? 0;
  241. //累计订单增加
  242. $shop = ShopClass::getLockById($shopId);
  243. if (empty($shop)) {
  244. util::fail('没有找到门店信息54');
  245. }
  246. $mainId = $shop->mainId ?? 0;
  247. $main = MainClass::getLockById($mainId);
  248. if (empty($main)) {
  249. util::fail('没有找到main信息');
  250. }
  251. $main->unPayOrder += 1;
  252. $main->totalOrder += 1;
  253. $main->save();
  254. $address = $data['address'] ?? '';
  255. $floor = $data['floor'] ?? '';
  256. if (isset($data['fullAddress']) == false || empty($data['fullAddress'])) {
  257. $data['fullAddress'] = $address . $floor;
  258. }
  259. //非自取订单考虑配送时间
  260. $data['reachDate'] = isset($data['reachDate']) && !empty($data['reachDate']) ? $data['reachDate'] : date("Y-m-d");
  261. $sendType = $data['sendType'] ?? 0;
  262. if ($sendType != 1) {
  263. if (isset($data['reachPeriod']) == false || empty($data['reachPeriod'])) {
  264. util::fail('请选择配送时间');
  265. }
  266. $data['reachTime'] = strtotime($data['reachDate'] . ' ' . $data['reachPeriod']);
  267. }
  268. //将花店每月的总订单数作为编号
  269. $riseNum = StatOrderCountClass::addOrder($shop, $main);
  270. $data['sendNum'] = date("d") . $riseNum;
  271. $data['totalFlow'] = OrderClass::ORDER_TOTAL_FLOW;
  272. return self::add($data, true);
  273. }
  274. public static function getByOrderSn($orderSn)
  275. {
  276. return self::getByCondition(['orderSn' => $orderSn]);
  277. }
  278. //评价 ssh 2019.12.16
  279. public static function comment($data)
  280. {
  281. $id = $data['id'];
  282. unset($data['id']);
  283. return self::updateById($id, $data);
  284. }
  285. public static function getFullInfo($id)
  286. {
  287. $order = self::getById($id);
  288. if (empty($order)) {
  289. return [];
  290. }
  291. $sn = $order['orderSn'] ?? '';
  292. $order['goodsInfoList'] = OrderGoodsClass::getListBySn($sn);
  293. $order['itemInfoList'] = OrderItemClass::getListBySn($sn);
  294. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*');
  295. if (!empty($workList)) {
  296. foreach ($workList as $key => $work) {
  297. $shortCover = $work['cover'] ?? '';
  298. $workList[$key]['shortCover'] = $shortCover;
  299. $workList[$key]['smallCover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  300. }
  301. }
  302. $order['workList'] = $workList;
  303. $debtPrice = $order['debtPrice'] ?? 0;
  304. $remainDebtPrice = $order['remainDebtPrice'] ?? 0;
  305. $orderId = $order['id'] ?? 0;
  306. $osList = [];
  307. if ($debtPrice > $remainDebtPrice) {
  308. $osList = OrderSettleClass::getAllByCondition(['orderId' => $orderId, 'status' => 1], null, '*', null, true);
  309. }
  310. //结账记录关系
  311. $order['orderSettleList'] = $osList;
  312. $order['today'] = date("Y-m-d");
  313. $order['tomorrow'] = date("Y-m-d", strtotime("+1 day"));
  314. return $order;
  315. }
  316. //订单
  317. public static function getOrderById($id)
  318. {
  319. $order = self::getById($id);
  320. if (empty($order)) {
  321. return [];
  322. }
  323. $sn = $order['orderSn'] ?? '';
  324. $order['goodsInfoList'] = OrderGoodsClass::getListBySn($sn);
  325. return $order;
  326. }
  327. //根据订单查询 ssh 2020.1.4
  328. public static function getOrderBySn($orderSn)
  329. {
  330. $order = self::getByCondition(['orderSn' => $orderSn]);
  331. if (empty($order)) {
  332. return [];
  333. }
  334. $id = $order['id'];
  335. $order['goodsInfoList'] = OrderGoodsClass::getGoodsListById($id);
  336. return $order;
  337. }
  338. //返回随机优惠金额 ssh 2019.9.12
  339. public static function getRandDiscount($amount)
  340. {
  341. if ($amount <= 0) {
  342. return 0;
  343. }
  344. $randDiscount = self::$randDiscount;
  345. krsort($randDiscount);
  346. $rand = 0;
  347. foreach ($randDiscount as $currentAmount => $val) {
  348. if ($amount >= $currentAmount) {
  349. $rand = rand($val[0], $val[1]);
  350. break;
  351. }
  352. }
  353. return $rand / 10;
  354. }
  355. //第三方支付后回调处理流程 ssh 2021.4.30
  356. public static function thirdPay($payWay, $orderSn, $totalFee, $attach, $transactionId)
  357. {
  358. $order = self::getByCondition(['orderSn' => $orderSn], true);
  359. if (empty($order)) {
  360. noticeUtil::push('散客下单,付款成功,支付回调,单号:' . $orderSn . ' 金额:' . $totalFee . ' 回调id:' . $transactionId . ' 附件:' . $attach . ',没有找到订单', '15280215347');
  361. $msg = "没有找到零售订单 orderSn:{$orderSn}";
  362. Yii::info($msg);
  363. util::fail($msg);
  364. }
  365. if ($order->mainPay != $totalFee) {
  366. noticeUtil::push("散客下单,付款成功,支付回调错误,零售订单金额与回调通知金额不一致 orderSn:{$orderSn} {$order->mainPay} {$totalFee} 附件:{$attach}", '15280215347');
  367. $msg = "零售订单金额与回调通知金额不一致 orderSn:{$orderSn} {$order->mainPay} {$totalFee}";
  368. Yii::info($msg);
  369. util::fail($msg);
  370. }
  371. $id = $order->id;
  372. $order = self::getLockById($id);
  373. $date = date("Y-m-d H:i:s");
  374. $order->payTime = $date;
  375. $order->thirdNo = $transactionId;
  376. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  377. $order->save();
  378. self::payAfter($order, $payWay);
  379. }
  380. //订单完成 ssh 2021.4.20
  381. public static function payAfter($order, $payWay)
  382. {
  383. if (empty($order)) {
  384. util::fail('没有找到订单');
  385. }
  386. if (!isset($order->status)) {
  387. util::fail('没有找到订单的状态');
  388. }
  389. $orderSn = $order->orderSn ?? '';
  390. if ($order->status == self::ORDER_STATUS_CANCEL) {
  391. $shopId = $order->shopId;
  392. $shop = ShopClass::getById($shopId, true);
  393. if (empty($shop)) {
  394. noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功但订单已取消,没有找到门店,关键词 cancel_get_money', '15280215347');
  395. util::stop("SUCCESS");
  396. }
  397. Yii::$app->params['errorReport'] = 1;
  398. try {
  399. //恢复取消的订单
  400. self::recoverOrderToPay($order);
  401. noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功,取消的订单,已恢复 SUCCESS', '15280215347');
  402. } catch (\Exception $exception) {
  403. $ret = HdRefundClass::onlyRefundAmount($shop, $order);
  404. if ($ret['status'] == 0) {
  405. $errMsg = $exception->getMessage();
  406. noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功但订单取消。订单没有恢复成功,原因' . $errMsg . ',也没有退款成功。请手动处理。关键词 cancel_get_money', '15280215347');
  407. }
  408. util::stop("SUCCESS");
  409. }
  410. }
  411. if ($order->payStatus == 1) {
  412. noticeUtil::push('注意,零售订单:' . $orderSn . ',已经付过款了,无需重复请求和操作', '15280215347');
  413. util::fail('订单已经付过款了');
  414. }
  415. $orderId = $order->id ?? 0;
  416. $customId = $order->customId ?? 0;
  417. if ($order->fromType == 3) {
  418. //客服下的单要配送流程
  419. $order->status = self::ORDER_STATUS_UN_SEND;
  420. } else {
  421. $order->status = self::ORDER_STATUS_COMPLETE;
  422. }
  423. $order->payWay = $payWay;
  424. $order->payStatus = 1;
  425. $order->payTime = date("Y-m-d H:i:s");
  426. $order->stockChange = 1;
  427. $order->save();
  428. \bizMall\order\classes\OrderGoodsClass::stockChange($order);
  429. $realPrice = $order->realPrice ?? 0;
  430. $shopId = $order->shopId;
  431. $shop = ShopClass::getLockById($shopId);
  432. if (empty($shop)) {
  433. util::fail('没有找到门店,编号5115');
  434. }
  435. $mainId = $shop->mainId ?? 0;
  436. $main = MainClass::getLockById($mainId);
  437. if (empty($main)) {
  438. util::fail('没有main信息,编号3096');
  439. }
  440. $main->unSendOrder += 1;
  441. $main->unPayOrder -= 1;
  442. $currentTotalIncome = bcadd($main->totalIncome, $realPrice, 2);
  443. $main->totalIncome = $currentTotalIncome;
  444. $main->save();
  445. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  446. $shopAdminId = $order->shopAdminId ?? 0;
  447. $shopAdminName = $order->shopAdminName ?? '';
  448. $sjId = $order->sjId;
  449. $fromType = $order->fromType ?? 1;
  450. $event = !empty($shopAdminId) ? '员工开单' : '客户下单';
  451. $capital = [
  452. 'capitalType' => $capitalType,
  453. 'relateId' => $orderId,
  454. 'io' => 1,
  455. 'totalIncome' => $currentTotalIncome,
  456. 'payWay' => $payWay,
  457. 'event' => $event,
  458. 'sjId' => $sjId,
  459. 'shopId' => $shopId,
  460. 'shopAdminId' => $shopAdminId,
  461. 'shopAdminName' => $shopAdminName,
  462. 'amount' => $realPrice,
  463. 'fromType' => $fromType,
  464. 'mainId' => $mainId,
  465. ];
  466. ShopCapitalClass::addCapital($capital);
  467. //每天和每月收入增加
  468. StatIncomeClass::updateOrInsert($main, $shop, $realPrice);
  469. //今日订单+1
  470. StatOrderClass::updateOrInsert($main, $shop);
  471. //销售收入增加
  472. StatSaleClass::replace($main, $shop, $realPrice);
  473. //各渠道收入金额统计
  474. StatKdClass::replace($shop, $realPrice, $payWay);
  475. //当天同个人同地址的订单汇总
  476. $sameDate = date("Y_m_d");
  477. $sameAddress = $order->showAddress ?? '';
  478. $addressMd5 = md5($sameAddress);
  479. $sameKey = $customId . '_' . $addressMd5 . '_' . $sameDate . '_retail';
  480. $sameString = Yii::$app->redis->executeCommand('GET', [$sameKey]);
  481. if (!empty($sameString)) {
  482. $newString = $sameString . ',' . $orderId;
  483. $newIdsArray = explode(',', $newString);
  484. if (count($newIdsArray) <= 90) {
  485. Yii::$app->redis->executeCommand('SETEX', [$sameKey, 186400, $newString]);
  486. foreach ($newIdsArray as $currentOrderId) {
  487. OrderClass::updateById($currentOrderId, ['sameTimeIds' => $newString]);
  488. }
  489. //noticeUtil::push($sameKey . '' . $sameAddress . " 花掌柜当天汇总ids:" . $newString, '15280215347');
  490. }
  491. } else {
  492. Yii::$app->redis->executeCommand('SETEX', [$sameKey, 186400, $orderId]);
  493. $order->sameTimeIds = $orderId;
  494. $order->save();
  495. //noticeUtil::push($sameKey . '' . $sameAddress . " 花掌柜当天汇总ids:" . $orderId, '15280215347');
  496. }
  497. //客户在线支付下单增加商家可提现余额
  498. if (isset($order->onlinePay) && $order->onlinePay == dict::getDict('onlinePay', 'yes')) {
  499. $amount = $order->mainPay;
  500. ShopClass::customKdAddBalance($main, $shop, $amount, $order, $capitalType);
  501. }
  502. //客户使用余额付款
  503. if ($payWay == dict::getDict('payWay', 'balancePay')) {
  504. CustomClass::payToChangeBalance($order);
  505. }
  506. //有尾款或全部欠款时
  507. if ($payWay == dict::getDict('payWay', 'debtPay')) {
  508. if (isset($order->remainDebtPrice) && $order->remainDebtPrice > 0) {
  509. $newCustom = CustomClass::getLockById($customId);
  510. CustomClass::cgDebtAmountAdd($newCustom, $order);
  511. }
  512. }
  513. //全部现金付款余额增加
  514. if ($payWay == dict::getDict('payWay', 'cash')) {
  515. $moneyBalance = bcadd($main->money, $order->mainPay, 2);
  516. $main->money = $moneyBalance;
  517. $main->save();
  518. $moneyEvent = "客户现金下单" . floatval($order->mainPay) . "元(单号 {$order->orderSn})";
  519. $moneyRemark = '';
  520. $change = [
  521. 'relateId' => $orderId,
  522. 'amount' => $order->mainPay,
  523. 'balance' => $moneyBalance,
  524. 'io' => 1,
  525. 'mainId' => $mainId,
  526. 'capitalType' => $capitalType,
  527. 'ptStyle' => dict::getDict('ptStyle', 'hd'),
  528. 'event' => $moneyEvent,
  529. 'remark' => $moneyRemark,
  530. ];
  531. ShopMoneyChangeClass::addData($change);
  532. } else {
  533. //部分现金付款
  534. $orderCash = $order->cash ?? 0;
  535. $orderCash = floatval($orderCash);
  536. if ($orderCash > 0) {
  537. $moneyBalance = bcadd($main->money, $orderCash, 2);
  538. $main->money = $moneyBalance;
  539. $main->save();
  540. $moneyEvent = "客户部分现金付款{$orderCash}元(单号 {$order->orderSn})";
  541. $moneyRemark = '';
  542. $change = [
  543. 'relateId' => $orderId,
  544. 'amount' => $orderCash,
  545. 'balance' => $moneyBalance,
  546. 'io' => 1,
  547. 'mainId' => $mainId,
  548. 'capitalType' => $capitalType,
  549. 'ptStyle' => dict::getDict('ptStyle', 'hd'),
  550. 'event' => $moneyEvent,
  551. 'remark' => $moneyRemark,
  552. ];
  553. ShopMoneyChangeClass::addData($change);
  554. }
  555. }
  556. }
  557. //转化出送到时间 ssh 2020.3.15
  558. public static function getReachTime($order)
  559. {
  560. $reachTime = '';
  561. if (isset($order['reachDate']) && !empty($order['reachDate'])) {
  562. $prev = date("n-j", strtotime($order['reachDate']));
  563. $periodData = self::$reachPeriod;
  564. $periodKey = $order['reachPeriod'];
  565. $period = isset($periodData[$periodKey]) ? $periodData[$periodKey] : '上午';
  566. $reachTime = $prev . ' ' . $period;
  567. }
  568. return $reachTime;
  569. }
  570. //支付成功获取unionId ssh 2020.5.12
  571. public static function payToUpdateUnionId($merchant, $merchantExtend, $orderSn, $user)
  572. {
  573. $mcId = $merchantExtend['wxPayMerchantId'];
  574. $miniOpenId = isset($user['miniOpenId']) ? $user['miniOpenId'] : '';
  575. $unionId = isset($user['unionId']) ? $user['unionId'] : '';
  576. $userId = $user['id'];
  577. if (empty($unionId)) {
  578. $unionId = miniUtil::getPaidUnionId($merchant, $miniOpenId, $mcId, (string)$orderSn, 0);
  579. if (!empty($unionId)) {
  580. $findUser = UserClass::getByUnionId($unionId);
  581. if (empty($findUser)) {
  582. UserClass::updateByCondition(['id' => $userId], ['unionId' => $unionId]);
  583. } else {
  584. UserClass::mergeUser($findUser, $user);
  585. }
  586. }
  587. }
  588. }
  589. //订单取消 ssh 20220516
  590. public static function setExpire($order, $force = false)
  591. {
  592. $now = time();
  593. if ($order->deadline > $now && $force == false) {
  594. return false;
  595. }
  596. if ($order->status != 1) {
  597. return false;
  598. }
  599. $order->status = 5;
  600. $order->cancelTime = date("Y-m-d H:i:s");
  601. $order->save();
  602. //暂时只考虑花材库存的回滚。商品只有下单成功了才会占用库存。
  603. $orderSn = $order->orderSn ?? '';
  604. $itemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  605. if (!empty($itemList)) {
  606. foreach ($itemList as $item) {
  607. $ptItemId = $item->ptItemId ?? 0;
  608. $sjId = $item->sjId ?? 0;
  609. $shopId = $item->shopId ?? 0;
  610. $mainId = $item->mainId ?? 0;
  611. $ratio = $item->ratio ?? 20;
  612. $unitType = $item->unitType ?? 0;
  613. if ($unitType == 0) {
  614. $bigNum = $item->num;
  615. $smallNum = 0;
  616. } else {
  617. $bigNum = 0;
  618. $smallNum = $item->num;
  619. }
  620. $itemId = $item->itemId ?? 0;
  621. $stockInfo = ProductClass::addStock($itemId, $bigNum, $smallNum);
  622. $recordData = [];
  623. $recordData['sjId'] = $sjId;
  624. $recordData['shopId'] = $shopId;
  625. $recordData['mainId'] = $mainId;
  626. $recordData['itemId'] = $ptItemId;
  627. $recordData['itemNum'] = ProductClass::mergeItemNum($bigNum, $smallNum, $ratio);
  628. $recordData['oldStock'] = $stockInfo['oldStock'];
  629. $recordData['newStock'] = $stockInfo['newStock'];
  630. $recordData['productId'] = $itemId;
  631. $recordData['orderSn'] = $orderSn;
  632. $recordData['relateName'] = '系统';
  633. StockRecordClass::addSellStockOrderCancelRecord($recordData);
  634. }
  635. }
  636. $shopId = $order->shopId ?? 0;
  637. $shop = ShopClass::getById($shopId, true);
  638. if (!empty($shop)) {
  639. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  640. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  641. $params = [
  642. 'appid' => 'OP00002119',
  643. 'serial_no' => '018b08cfddbd',
  644. 'merchant_no' => $shop->lklSjNo,
  645. 'term_no' => $shop->lklScanTermNo,
  646. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  647. 'lklCertificatePath' => $lklCertificatePath,
  648. ];
  649. $laResource = new Lakala($params);
  650. $closeParams = [
  651. 'orderSn' => $orderSn,
  652. ];
  653. $response = $laResource->close($closeParams);
  654. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  655. //noticeUtil::push('零售订单:' . $orderSn . ',关单没有成功。', '15280215347');
  656. } else {
  657. //noticeUtil::push('零售订单:' . $orderSn . ',关单成功。', '15280215347');
  658. }
  659. }
  660. }
  661. // 恢复订单 -- 即:把订单的状态从取消状态变成待付款状态
  662. public static function recoverOrderToPay($order)
  663. {
  664. $now = time();
  665. $order->status = 1;
  666. $order->deadline = $now + 86400;
  667. $order->save();
  668. // 重新占用库存(与取消订单时的库存回滚相反)
  669. $itemList = OrderItemClass::getAllByCondition(['orderSn' => $order->orderSn], null, '*', null, true);
  670. if (!empty($itemList)) {
  671. foreach ($itemList as $item) {
  672. $ptItemId = $item->ptItemId ?? 0;
  673. $sjId = $item->sjId ?? 0;
  674. $shopId = $item->shopId ?? 0;
  675. $mainId = $item->mainId ?? 0;
  676. $ratio = $item->ratio ?? 20;
  677. $unitType = $item->unitType ?? 0;
  678. if ($unitType == 0) {
  679. $bigNum = $item->num;
  680. $smallNum = 0;
  681. } else {
  682. $bigNum = 0;
  683. $smallNum = $item->num;
  684. }
  685. $itemId = $item->itemId ?? 0;
  686. // 重新扣减库存(占用库存)
  687. $stockInfo = ProductClass::decreaseStock($itemId, $bigNum, $smallNum, true);
  688. $recordData = [];
  689. $recordData['sjId'] = $sjId;
  690. $recordData['shopId'] = $shopId;
  691. $recordData['mainId'] = $mainId;
  692. $recordData['itemId'] = $ptItemId;
  693. $recordData['itemNum'] = ProductClass::mergeItemNum($bigNum, $smallNum, $ratio);
  694. $recordData['oldStock'] = $stockInfo['oldStock'];
  695. $recordData['newStock'] = $stockInfo['newStock'];
  696. $recordData['productId'] = $itemId;
  697. $recordData['orderSn'] = $order->orderSn;
  698. $recordData['relateName'] = $order->customName ?? '';
  699. StockRecordClass::hdKdAddRecord($recordData);
  700. }
  701. }
  702. return true;
  703. }
  704. // 扣库存
  705. protected static function decGoodsStock($orderGoods)
  706. {
  707. foreach ($orderGoods as $goods) {
  708. GoodsClass::counters([
  709. 'stock' => -$goods['num']
  710. ], [
  711. 'and',
  712. ['id' => $goods['goodsId']],
  713. ['<>', 'stock', Goods::FULL_STOCK]
  714. ]);
  715. }
  716. }
  717. //云打印 ssh 20210709
  718. public static function onlinePrint($order, $must = false, $port = 'front')
  719. {
  720. if (empty($order)) {
  721. return false;
  722. }
  723. if ($must == false) {
  724. if ($order->needPrint != dict::getDict('needPrint', 'need')) {
  725. return false;
  726. }
  727. if ($order->payStatus != 1) {
  728. return false;
  729. }
  730. }
  731. $shopId = $order->shopId ?? 0;
  732. $ext = ShopExtClass::getByCondition(['shopId' => $shopId]);
  733. $printSn = $ext['printSn'] ?? '';
  734. if ($port == 'make') {
  735. $printSn = $ext['makePrintSn'] ?? '';
  736. if ($order->fromType == 4) {
  737. $printSn = $ext['mtPrintSn'] ?? '';
  738. }
  739. $workList = WorkClass::getAllByCondition(['orderId' => $order->id], null, '*', null, true);
  740. $hasSh = 0;
  741. if (!empty($workList)) {
  742. foreach ($workList as $work) {
  743. $sh = $work->sh ?? 0;
  744. if ($sh == 1) {
  745. $hasSh = 1;
  746. }
  747. }
  748. }
  749. if ($hasSh == 1) {
  750. $printSn = $ext['printSn'] ?? '';
  751. }
  752. }
  753. if (empty($printSn)) {
  754. return false;
  755. }
  756. $order->printNum += 1;
  757. $order->save();
  758. $customId = $order->customId ?? 0;
  759. $custom = CustomClass::getById($customId);
  760. $debtAmount = $custom['debtAmount'] ?? 0;
  761. $respond = self::getPrintData($order, $debtAmount);
  762. $fromType = $order->fromType ?? dict::getDict('fromType', 'shop');
  763. $fromTypeMap = dict::getDict('fromTypeMap');
  764. $fromTypeName = $fromTypeMap[$fromType] ?? '门店';
  765. //客服下的单则显示客服号和客户名称
  766. if ($fromType == dict::getDict('fromType', 'friend')) {
  767. $staffName = $order->shopAdminName ?? '';
  768. $bookName = $order->bookName ?? '';
  769. $fromTypeName = $staffName . ' ' . $bookName;
  770. }
  771. $content = '';
  772. //$content .= "<CB>【零售】</CB><BR>";
  773. if ($fromType == dict::getDict('fromType', 'mt')) {
  774. $content .= '<B>美团 ' . $order->thirdSn . '</B><BR>';
  775. if (isset($order->goodsNum) && $order->goodsNum > 1) {
  776. $content .= '<B>美团 ' . $order->thirdSn . ' (' . $order->goodsNum . '份)</B><BR>';
  777. }
  778. $content .= '--------------------------------<BR>';
  779. $content .= date("Y-m-d", strtotime($order->addTime)) . '<BR>';
  780. } else {
  781. $content .= '<CB>' . $fromTypeName . ' ' . $respond['sendNum'] . '</CB><BR>';
  782. $content .= '--------------------------------<BR>';
  783. }
  784. $readPeriod = $order->reachPeriod ?? 0;
  785. if ($order->sendType == 1) {
  786. if (isset($order->reachDate) && !empty($order->reachDate) && $order->reachDate != '0000-00-00') {
  787. $currentReachDate = date("m-d", strtotime($order->reachDate));
  788. $content .= '<B>' . $currentReachDate . ' ' . $readPeriod . '前</B><BR>';
  789. $content .= '<B>到店自取</B><BR><BR>';
  790. } else {
  791. $content .= '<B>到店自取</B><BR><BR>';
  792. }
  793. } else {
  794. if ($order->sendType == 0) {
  795. $content .= '<B>送货上门</B><BR><BR>';
  796. } else if ($order->sendType == 2) {
  797. $content .= '<B>跑腿到付</B><BR><BR>';
  798. } else if ($order->sendType == 3) {
  799. $content .= '<B>物流到付</B><BR><BR>';
  800. } else if ($order->sendType == 4) {
  801. $content .= '<B>快递到付</B><BR><BR>';
  802. } else {
  803. $content .= '';
  804. }
  805. if (isset($order->reachDate) && !empty($order->reachDate) && $order->reachDate != '0000-00-00') {
  806. $currentReachDate = date("m-d", strtotime($order->reachDate));
  807. $content .= '<B>' . $currentReachDate . ' ' . $readPeriod . '前</B><BR><BR>';
  808. }
  809. }
  810. if (isset($order->receiveUserName) && !empty($order->receiveUserName)) {
  811. $content .= '收花人:<BR>';
  812. $content .= '<B>' . $order->receiveUserName . '</B><BR>';
  813. }
  814. if (isset($order->receiveMobile) && !empty($order->receiveMobile)) {
  815. $content .= '<B>' . $order->receiveMobile . '</B><BR><BR>';
  816. }
  817. if (isset($order->fullAddress) && !empty($order->fullAddress)) {
  818. $content .= '<B>' . $order->fullAddress . '(' . $order->showAddress . ')' . '</B><BR><BR>';
  819. }
  820. if (isset($order->cardInfo) && !empty($order->cardInfo)) {
  821. $content .= '<B>贺卡内容:' . $order->cardInfo . '</B><BR><BR>';
  822. }
  823. if ($order->anonymity == 1) {
  824. $content .= '<B>匿名派送!!</B><BR><BR>';
  825. } else {
  826. if (isset($order->bookMobile) && !empty($order->bookMobile)) {
  827. $bookName = $order->bookName ?? '';
  828. $bookMobile = $order->bookMobile ?? '';
  829. $content .= '订花人:<BR>';
  830. if (!empty($bookName)) {
  831. $content .= '<B>' . $bookName . '</B><BR>';
  832. }
  833. if (!empty($bookMobile)) {
  834. $content .= '<B>' . $bookMobile . '</B><BR>';
  835. }
  836. }
  837. }
  838. if (isset($respond['remark']) && !empty($respond['remark'])) {
  839. $content .= '<BR>';
  840. $content .= '备注:<BR>';
  841. $content .= '<B>' . $respond['remark'] . '</B><BR>';
  842. }
  843. $content .= '<BR>';
  844. $content .= '商品 数量/单价 金额 <BR>';
  845. $content .= '--------------------------------<BR>';
  846. if (isset($respond['product']) && !empty($respond['product'])) {
  847. foreach ($respond['product'] as $current) {
  848. $content = self::printGroup($current, $content);
  849. }
  850. $content .= '--------------------------------<BR>';
  851. }
  852. if (isset($respond['refund']) && !empty($respond['refund'])) {
  853. $content .= '<B>已退款:</B><BR>';
  854. foreach ($respond['refund'] as $current) {
  855. //58mm的机器,一行打印16个汉字,32个字母
  856. $name = $current['name'] ?? '';
  857. $content .= $name . '<BR>';
  858. $name = str_repeat(' ', 10);
  859. $productNum = $current['num'] ?? '';
  860. $blankNum = bcsub(12, strlen($productNum));
  861. if ($blankNum > 0) {
  862. $productNum = $productNum . str_repeat(' ', $blankNum);
  863. }
  864. $productPrice = $current['price'] ?? '';
  865. $blankNum = bcsub(7, strlen($productPrice));
  866. if ($blankNum > 0) {
  867. $productPrice = $productPrice . str_repeat(' ', $blankNum);
  868. }
  869. $content .= $name . " " . $productNum . ' ' . $productPrice . '<BR>';
  870. }
  871. $content .= '--------------------------------<BR>';
  872. }
  873. if (isset($order->goodsPrice) && $order->goodsPrice > 0) {
  874. $content .= '商品合计:' . floatval($order->goodsPrice) . '<BR>';
  875. }
  876. if (isset($respond['sendCost']) && $respond['sendCost'] > 0 && $order->sendType == 2) {
  877. $content .= '运费:' . floatval($respond['sendCost']) . '<BR>';
  878. }
  879. if (isset($order->serviceFee) && $order->serviceFee > 0) {
  880. $content .= '手续费:' . floatval($order->serviceFee) . '<BR>';
  881. }
  882. if (isset($order->labourCost) && $order->labourCost > 0) {
  883. $content .= '包装费:' . floatval($order->labourCost) . '<BR>';
  884. }
  885. if (isset($order->prePrice) && $order->prePrice > 0) {
  886. $content .= '总计:' . floatval($order->prePrice) . '<BR>';
  887. }
  888. if (isset($respond['discountAmount']) && !empty($respond['discountAmount']) && $respond['discountAmount'] > 0) {
  889. $content .= '优惠扣除:-' . floatval($respond['discountAmount']) . '<BR>';
  890. }
  891. $content .= '订单金额:' . floatval($respond['orderPrice']) . '<BR>';
  892. if (isset($respond['refundPrice']) && $respond['refundPrice'] > 0) {
  893. $content .= '退款金额:' . floatval($respond['refundPrice']) . '<BR>';
  894. }
  895. if (isset($respond['debt']) && $respond['debt'] == 1) {
  896. $content .= '实付金额:0<BR>';
  897. } else {
  898. $content .= '实付金额:' . floatval($respond['realPrice']) . '<BR>';
  899. }
  900. if (isset($order->remainDebtPrice) && $order->remainDebtPrice > 0) {
  901. $content .= '<B>待付尾款:' . floatval($order->remainDebtPrice) . '</B><BR>';
  902. }
  903. $shop = ShopClass::getById($shopId, true);
  904. $sjId = $shop->sjId ?? 0;
  905. $sj = SjClass::getById($sjId, true);
  906. $sjName = $sj->name ?? '';
  907. $shopName = $shop->shopName ?? '';
  908. $currentName = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  909. $content .= '--------------------------------<BR>';
  910. $content .= '订单日期:' . $order->addTime . '<BR>';
  911. $content .= '订单编号:' . $respond['orderSn'] . '<BR>';
  912. $content .= '门店名称:' . $currentName . '<BR>';
  913. $content .= "<BR>";
  914. $p = new printUtil($printSn);
  915. $orderSn = $order->orderSn ?? '';
  916. $workList = WorkClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  917. if (!empty($workList)) {
  918. $content .= "<BR>";
  919. $content .= '--------------------------------<BR>';
  920. foreach ($workList as $work) {
  921. $goodsSn = $work->goodsSn ?? '';
  922. $sn = $work->sn ?? '';
  923. $content .= '<B>制作号:' . $sn . '<B>';
  924. // 1-523 有-特殊符号,使用飞鹅自带的函数处理
  925. $content .= $p->bar_code($goodsSn);
  926. $content .= "<BR>";
  927. }
  928. }
  929. $p->printMsg($content);
  930. }
  931. //打印数据 ssh 20210702
  932. public static function getPrintData($order, $debtAmount)
  933. {
  934. $orderSn = $order->orderSn ?? '';
  935. $printProduct = [];
  936. $orderItemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
  937. if (!empty($orderItemList)) {
  938. foreach ($orderItemList as $itemKey => $itemVal) {
  939. $unitName = $itemVal['unitName'] ?? '';
  940. $unitPrice = $itemVal['unitPrice'] ? floatval($itemVal['unitPrice']) : 0;
  941. $printProduct[] = [
  942. 'name' => $itemVal['name'] ?? '',
  943. 'num' => $itemVal['num'] . $unitName . '*' . $unitPrice,
  944. 'price' => floatval($itemVal['price']),
  945. ];
  946. }
  947. }
  948. $orderGoodsList = OrderGoodsClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
  949. if (!empty($orderGoodsList)) {
  950. foreach ($orderGoodsList as $itemKey => $itemVal) {
  951. $unitName = $itemVal['unitName'] ?? '份';
  952. $unitPrice = $itemVal['unitPrice'] ? floatval($itemVal['unitPrice']) : 0;
  953. $printProduct[] = [
  954. 'name' => $itemVal['name'] ?? '',
  955. 'num' => $itemVal['num'] . $unitName . '*' . $unitPrice,
  956. 'price' => floatval($itemVal['price']),
  957. ];
  958. }
  959. }
  960. $sendNum = $order['sendNum'] ?? '';
  961. //退款记录
  962. $refundList = [];
  963. $printData = [
  964. 'address' => '',
  965. 'sendCost' => $order->sendCost ?? '0.00',
  966. 'prePrice' => $order->prePrice ?? '0.00',
  967. 'orderPrice' => $order->orderPrice ?? '0',
  968. 'discountAmount' => $order->discountAmount ?? '0.00',
  969. 'realPrice' => $order->realPrice ?? '0.00',
  970. 'refundPrice' => $order->refundPrice ?? '0.00',
  971. 'debt' => $order->debt ?? 0,
  972. 'orderSn' => $order->orderSn ?? '',
  973. 'date' => $order->addTime ?? '',
  974. 'remark' => $order->remark ?? '',
  975. 'custom' => [
  976. 'customName' => $order->customName ?? '',
  977. 'customMobile' => $order->customMobile ?? '',
  978. 'fullAddress' => $order->fullAddress ?? '',
  979. ],
  980. 'product' => $printProduct,
  981. 'refund' => $refundList,
  982. 'sendNum' => $sendNum,
  983. 'debtAmount' => $debtAmount,
  984. ];
  985. return $printData;
  986. }
  987. public static function printGroup($current, $content)
  988. {
  989. //58mm的机器,一行打印16个汉字,32个字母
  990. $name = $current['name'] ?? '';
  991. $content .= $name . '<BR>';
  992. $name = str_repeat(' ', 10);
  993. $productNum = $current['num'] ?? '';
  994. $blankNum = bcsub(12, strlen($productNum));
  995. if ($blankNum > 0) {
  996. $productNum = $productNum . str_repeat(' ', $blankNum);
  997. }
  998. $productPrice = $current['price'] ?? '';
  999. $blankNum = bcsub(7, strlen($productPrice));
  1000. if ($blankNum > 0) {
  1001. $productPrice = $productPrice . str_repeat(' ', $blankNum);
  1002. }
  1003. $content .= $name . " " . $productNum . ' ' . $productPrice . '<BR>';
  1004. return $content;
  1005. }
  1006. }