OrderService.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. <?php
  2. namespace bizGhs\order\services;
  3. use biz\ghs\classes\GhsClass;
  4. use biz\shop\classes\ShopAdminClass;
  5. use biz\shop\classes\ShopCapitalClass;
  6. use biz\shop\classes\ShopClass;
  7. use biz\shop\classes\ShopExtClass;
  8. use biz\stat\classes\StatKdClass;
  9. use biz\stat\classes\StatKhCgClass;
  10. use biz\stat\classes\StatSaleClass;
  11. use biz\wx\classes\WxMessageClass;
  12. use bizGhs\base\services\BaseService;
  13. use bizGhs\book\classes\BookItemClass;
  14. use bizGhs\custom\classes\CustomClass;
  15. use bizGhs\custom\classes\CustomDebtChangeClass;
  16. use bizGhs\custom\services\GhsRechargeSettleService;
  17. use bizGhs\clear\classes\OrderCgClearClass;
  18. use bizGhs\order\classes\OrderClass;
  19. use bizGhs\order\classes\OrderExpressClass;
  20. use bizGhs\order\classes\OrderForwardClass;
  21. use bizGhs\order\classes\OrderItemClass;
  22. use bizGhs\order\classes\OrderSendClass;
  23. use bizGhs\order\classes\RefundOrderClass;
  24. use bizGhs\order\classes\RefundOrderItemClass;
  25. use bizGhs\product\classes\ProductClass;
  26. use bizGhs\shop\classes\MainClass;
  27. use bizGhs\shop\classes\ShopMoneyChangeClass;
  28. use bizGhs\stat\classes\StatYjClass;
  29. use biz\stat\classes\StatOrderCountClass;
  30. use bizGhs\stock\classes\StockRecordClass;
  31. use bizHd\cg\classes\CgRefundClass;
  32. use bizHd\cg\services\CgRefundService;
  33. use bizHd\purchase\classes\PurchaseItemClass;
  34. use bizHd\purchase\services\PurchaseService;
  35. use bizHd\stat\classes\StatIncomeClass;
  36. use bizHd\stat\classes\StatOrderClass;
  37. use common\components\dict;
  38. use common\components\orderSn;
  39. use common\components\util;
  40. use bizHd\purchase\classes\PurchaseClass;
  41. use common\components\stringUtil;
  42. use Yii;
  43. class OrderService extends BaseService
  44. {
  45. public static $baseFile = '\bizGhs\order\classes\OrderClass';
  46. public static function arrival($order, $data)
  47. {
  48. $params = ['fhType' => 0, 'fhWl' => '', 'fhWlNo' => '',];
  49. OrderClass::orderSend($order, $params);
  50. //product [{"productId":"3674","num":0,"price":1}]
  51. $product = $data['product'] ?? '';
  52. if (empty($product)) {
  53. util::fail('请填写成本价和到货数量');
  54. }
  55. $product = json_decode($product, true);
  56. if (empty($product)) {
  57. util::fail('没有填写成本价和到货数量');
  58. }
  59. $data['product'] = $product;
  60. //供货商到货
  61. $respond = OrderClass::arrival($order, $data);
  62. $cgId = $order->purchaseId ?? 0;
  63. $cg = PurchaseClass::getById($cgId, true);
  64. if (empty($cg)) {
  65. util::fail('没有找到采购单');
  66. }
  67. //供货商花材转换为零售店花材
  68. $ids = array_column($product, 'productId');
  69. $ghsProductInfo = ProductClass::getByIds($ids);
  70. if (empty($ghsProductInfo)) {
  71. util::fail('没有花材??');
  72. }
  73. $ghsPtIdRelation = [];
  74. foreach ($ghsProductInfo as $ghsProduct) {
  75. $id = $ghsProduct['id'] ?? 0;
  76. $ptItemId = $ghsProduct['itemId'] ?? 0;
  77. $ghsPtIdRelation[$ptItemId] = $id;
  78. }
  79. $ptIds = array_keys($ghsPtIdRelation);
  80. $cgMainId = $cg->mainId ?? 0;
  81. $cgSjId = $cg->sjdId ?? 0;
  82. $cgShopId = $cg->shopId ?? 0;
  83. $cgItem = ProductClass::getAllByCondition(['mainId' => $cgMainId, 'itemId' => ['in', $ptIds]], null, '*');
  84. $ghsHdIdRelate = [];
  85. foreach ($cgItem as $it) {
  86. $ptItemId = $it['itemId'] ?? 0;
  87. $ghsItemId = $ghsPtIdRelation[$ptItemId] ?? 0;
  88. $cgItemId = $it['id'] ?? 0;
  89. $ghsHdIdRelate[$ghsItemId] = $cgItemId;
  90. }
  91. $cgProduct = [];
  92. foreach ($product as $pro) {
  93. $price = $pro['price'] ?? 0;
  94. $num = $pro['num'] ?? 0;
  95. $productId = $pro['productId'] ?? 0;
  96. $currentId = $ghsHdIdRelate[$productId] ?? 0;
  97. $cgProduct[$currentId] = ['num' => $num, 'price' => $price, 'productId' => $currentId];
  98. }
  99. //零售到货
  100. $saleRefund = $respond['refund'] ?? null;
  101. $saleRefundId = 0;
  102. if (!empty($saleRefund)) {
  103. $saleRefundId = $saleRefund->id ?? 0;
  104. }
  105. $kiloFee = $respond['kiloFee'] ?? 0;
  106. $miniKilo = $respond['miniKilo'] ?? 0;
  107. $saleRefundId = $saleRefundId;
  108. $sendCost = isset($data['sendCost']) && is_numeric($data['sendCost']) ? $data['sendCost'] : 0;
  109. $packCost = isset($data['packCost']) && is_numeric($data['packCost']) ? $data['packCost'] : 0;
  110. $cgData = [
  111. 'product' => $cgProduct,
  112. 'kiloFee' => $kiloFee,
  113. 'miniKilo' => $miniKilo,
  114. 'saleRefundId' => $saleRefundId,
  115. 'sjId' => $cgSjId,
  116. 'shopId' => $cgShopId,
  117. 'mainId' => $cgMainId,
  118. 'sendCost' => $sendCost,
  119. 'packCost' => $packCost,
  120. ];
  121. $result = PurchaseClass::arrival($cg, $cgData);
  122. $cgRefund = $result['refund'] ?? null;
  123. if (!empty($cgRefund)) {
  124. $cgRefundId = $cgRefund->id ?? 0;
  125. if (!empty($saleRefund)) {
  126. $saleRefund->cgRefundId = $cgRefundId;
  127. $saleRefund->save();
  128. }
  129. }
  130. //不是预订单,并且供货商不是源花汇、小明鲜花、淄博花超、云漫梦金鹏、海翔,则订单直接完成掉。是预订单,则确认发货时直接完成掉。有多个地方要修改,请搜索关键词zjFinish
  131. if (!empty($cg) && !empty($order)) {
  132. $ghsShopId = $order->shopId ?? 0;
  133. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  134. if ($ext->orderFlow == 0) {
  135. $newCg = PurchaseClass::getById($cgId, true);
  136. PurchaseClass::confirmTake($newCg);
  137. }
  138. }
  139. }
  140. //添加订单
  141. public static function createNewOrder($data, $custom, $hasPay = 1)
  142. {
  143. //有unitType数据,说明是收银台传过来的数据,转换成和手机端结构一致
  144. $hasUnitType = array_column($data['product'], 'unitType');
  145. if (!empty($hasUnitType)) {
  146. $newProductData = [];
  147. foreach ($data['product'] as $productItem) {
  148. $unitType = $productItem['unitType'] ?? 0;
  149. $num = $productItem['num'] ?? 0;
  150. $productId = $productItem['productId'] ?? 0;
  151. $classId = $productItem['classId'] ?? 0;
  152. $itemId = $productItem['itemId'] ?? 0;
  153. $price = $productItem['price'] ?? 0;
  154. if ($unitType == 0) {
  155. $bigNum = $num;
  156. $smallNum = '';
  157. } else {
  158. $bigNum = '';
  159. $smallNum = $num;
  160. }
  161. $newProductData[] = [
  162. 'productId' => (int)$productId,
  163. 'bigNum' => (int)$bigNum,
  164. 'smallNum' => (int)$smallNum,
  165. 'classId' => (int)$classId,
  166. 'itemId' => (int)$itemId,
  167. 'price' => floatval($price),
  168. ];
  169. }
  170. $data['product'] = $newProductData;
  171. }
  172. //供货商销售单
  173. $returnOrder = OrderClass::addOrder($data, $custom);
  174. $saleId = $returnOrder->id ?? 0;
  175. $customSjId = $custom['sjId'] ?? 0;
  176. $customShopId = $custom['shopId'] ?? 0;
  177. $localOrder = $data['localOrder'] ?? 0;
  178. $transType = $data['transType'] ?? 0;
  179. $ghsShopAdminId = $data['shopAdminId'] ?? 0;
  180. $ghsShopAdminName = $data['shopAdminName'] ?? '';
  181. $customId = $data['customId'] ?? 0;
  182. $ghsId = $data['ghsId'] ?? 0;
  183. $ghs = GhsClass::getById($ghsId);
  184. if (empty($ghs)) {
  185. util::fail('没有找到供货商');
  186. }
  187. $ghsName = $ghs['name'] ?? '';
  188. $ghsAvatar = $ghs['avatar'] ?? '';
  189. $ghsMobile = $ghs['mobile'] ?? '';
  190. $ghsFullAddress = $ghs['fullAddress'] ?? '';
  191. $payWay = $data['payWay'] ?? dict::getDict('payWay', 'wxPay');
  192. //销售单欠款字段与采购单欠款字段转换
  193. $debt = $data['debt'] ?? 0;
  194. $purchaseDebt = $debt == 1 ? PurchaseClass::DEBT_YES : PurchaseClass::DEBT_NO;
  195. if ($hasPay == dict::getDict('hasPay', 'balance')) {
  196. $payWay = dict::getDict('payWay', 'balancePay');
  197. $purchaseDebt = PurchaseClass::DEBT_NO;
  198. } elseif ($debt == 1) {
  199. $payWay = dict::getDict('payWay', 'debtPay');
  200. }
  201. //销售单的自取还是配送字段 与 采购单的转换
  202. $sendType = $data['sendType'] ?? OrderClass::SEND_TYPE_CAR_GET;
  203. $getType = $sendType == OrderClass::SEND_TYPE_THIRD_SEND ? PurchaseClass::GET_TYPE_SEND : PurchaseClass::GET_TYPE_SELF_GET;
  204. //零售采购单时没有传price字段,供货商可以改价会传price字段,这里转成userPrice以便采购单识别使用改的价还是花材原价!
  205. $currentProduct = $data['product'];
  206. foreach ($currentProduct as $currentKey => $currentItem) {
  207. if (isset($currentItem['price'])) {
  208. $currentProduct[$currentKey]['userPrice'] = $currentItem['price'];
  209. unset($currentProduct[$currentKey]['price']);
  210. }
  211. }
  212. $sendTimeWant = !empty($data['sendTimeWant']) ? $data['sendTimeWant'] : date("Y-m-d");
  213. $remark = $data['remark'] ?? '';
  214. $xj = $data['xj'] ?? '';
  215. $treeData = $data['treeData'] ?? [];
  216. $book = $data['book'] ?? 0;
  217. //后端开单,涉及花材满减,关键词 back_order_reach_discount_price
  218. $reachDiscountPrice = $data['reachDiscountPrice'] ?? 0;
  219. $wlName = $data['wlName'] ?? '';
  220. $cgMainId = $ghs['ownMainId'] ?? 0;
  221. $purchaseData = [
  222. 'book' => $book,
  223. 'product' => $currentProduct,
  224. 'sendTimeWant' => $sendTimeWant,
  225. 'sendCost' => $data['sendCost'] ?? '0',
  226. 'packCost' => $data['packCost'] ?? '0',
  227. 'ghsShopAdminId' => $ghsShopAdminId,
  228. 'ghsShopAdminName' => $ghsShopAdminName,
  229. 'sjId' => $customSjId,
  230. 'shopId' => $customShopId,
  231. 'saleId' => $saleId,
  232. 'ghsId' => $ghsId,
  233. 'ghsName' => $ghsName,
  234. 'ghsMobile' => $ghsMobile,
  235. 'ghsFullAddress' => $ghsFullAddress,
  236. 'ghsAvatar' => $ghsAvatar,
  237. 'customId' => $customId,
  238. 'payWay' => $payWay,
  239. 'status' => PurchaseClass::STATUS_UN_PAY,
  240. 'cgStyle' => dict::getDict('cgStyle', 'ghs'),
  241. 'debt' => $purchaseDebt,
  242. 'getType' => $getType,
  243. 'sendType' => $sendType,
  244. 'remark' => $remark,
  245. 'xj' => $xj,
  246. 'treeData' => $treeData,
  247. 'discount' => 1,
  248. 'mainId' => $cgMainId,
  249. 'wlName' => $wlName,
  250. 'localOrder' => $localOrder,
  251. 'transType' => $transType,
  252. 'reachDiscountPrice' => $reachDiscountPrice,
  253. ];
  254. if (!empty($data['deadline'])) {
  255. $purchaseData['deadline'] = $data['deadline'];
  256. }
  257. if (isset($data['modifyPrice']) && is_numeric($data['modifyPrice'])) {
  258. $purchaseData['modifyPrice'] = $data['modifyPrice'];
  259. }
  260. $purchase = PurchaseClass::addPurchase($purchaseData, $ghs);
  261. //开历史订单
  262. $historyDate = $data['historyDate'] ?? '';
  263. if (!empty($historyDate)) {
  264. $currentPayTime = $historyDate . ' 12:00:00';
  265. $returnOrder->payTime = $currentPayTime;
  266. $purchase->payTime = $currentPayTime;
  267. $purchase->save();
  268. CustomDebtChangeClass::updateByCondition(['capitalType' => 10, 'relateId' => $returnOrder->id], ['payTime' => $currentPayTime]);
  269. }
  270. $purchaseId = $purchase->id ?? 0;
  271. $returnOrder->purchaseId = $purchaseId;
  272. $returnOrder->save();
  273. //欠款、已付款、余额支付的走付款后流程
  274. if (in_array($hasPay, [dict::getDict('hasPay', 'payed'), dict::getDict('hasPay', 'debt'), dict::getDict('hasPay', 'balance')])) {
  275. // 挂账/余额:先处理销售单(含余额抵挂账),再同步采购单待结
  276. if (in_array($hasPay, [dict::getDict('hasPay', 'debt'), dict::getDict('hasPay', 'balance')])) {
  277. self::payAfter($returnOrder, $payWay);
  278. $purchase = PurchaseClass::getLockById($purchaseId);
  279. if (!empty($purchase)) {
  280. $purchase->remainDebtPrice = $returnOrder->remainDebtPrice ?? '0.00';
  281. $purchase->debtPrice = $returnOrder->debtPrice ?? '0.00';
  282. $purchase->debt = ($returnOrder->debt ?? 0) == OrderClass::DEBT_YES
  283. ? PurchaseClass::DEBT_YES : PurchaseClass::DEBT_NO;
  284. $purchase->save(false, ['remainDebtPrice', 'debtPrice', 'debt']);
  285. }
  286. PurchaseService::payAfter($purchase, $payWay);
  287. } else {
  288. PurchaseService::payAfter($purchase, $payWay);
  289. self::payAfter($returnOrder, $payWay);
  290. }
  291. //不是预订单,并且供货商不是源花汇、小明鲜花、淄博花超、云漫梦金鹏、海翔,则订单直接完成掉。是预订单,则确认发货时直接完成掉。有多个地方要修改,请搜索关键词zjFinish
  292. if (isset($returnOrder->book) && $returnOrder->book == 0) {
  293. $ghsShopId = $ghs['shopId'] ?? 0;
  294. $ext = ShopExtClass::getByCondition(['shopId' => $ghsShopId], true, null, 'id,shopId,orderFlow');
  295. if ($ext->orderFlow == 0) {
  296. $returnId = $returnOrder->id;
  297. $order = OrderClass::getById($returnId, true);
  298. if (!empty($order)) {
  299. OrderClass::confirmReach($order);
  300. }
  301. }
  302. }
  303. }
  304. return $returnOrder;
  305. }
  306. //修改订单
  307. public static function updateOrder($order, $data)
  308. {
  309. $purchaseId = $order->purchaseId ?? 0;
  310. $purchase = PurchaseClass::getLockById($purchaseId);
  311. //修改供货商销售单
  312. $returnOrder = OrderClass::updateOrder($order, $data);
  313. //供货商销售单的 0未欠款 1欠款 转成零售采购单的 1欠款 2未欠款
  314. $debt = $data['debt'] ?? 0;
  315. $purchaseDebt = $debt == 1 ? PurchaseClass::DEBT_YES : PurchaseClass::DEBT_NO;
  316. $payWay = $data['payWay'] ?? dict::getDict('payWay', 'wxPay');
  317. if ($debt == 1) {
  318. $payWay = dict::getDict('payWay', 'debtPay');
  319. }
  320. //自取还是配送订单,销售单与采购单之间转换
  321. $sendType = $data['sendType'] ?? OrderClass::SEND_TYPE_MYSELF;
  322. $getType = $sendType == OrderClass::SEND_TYPE_NO ? PurchaseClass::GET_TYPE_SELF_GET : PurchaseClass::GET_TYPE_SEND;
  323. //供货商价格是可以修改的,修改的价格一起传给采购单保存
  324. $currentProduct = $data['product'];
  325. foreach ($currentProduct as $currentKey => $currentItem) {
  326. if (isset($currentProduct[$currentKey]['price'])) {
  327. $currentProduct[$currentKey]['userPrice'] = $currentProduct[$currentKey]['price'];
  328. unset($currentProduct[$currentKey]['price']);
  329. }
  330. }
  331. $remark = $data['remark'] ?? '';
  332. $purchaseData = [
  333. 'product' => $currentProduct,
  334. 'sendTime' => date("H:i:s"),
  335. 'sendCost' => $data['sendCost'] ?: '0.00',
  336. 'payWay' => $payWay,
  337. 'status' => PurchaseClass::STATUS_UN_PAY,
  338. 'cgStyle' => dict::getDict('cgStyle', 'ghs'),
  339. 'debt' => $purchaseDebt,
  340. 'getType' => $getType,
  341. 'status' => PurchaseClass::STATUS_UN_PAY,
  342. 'remark' => $remark,
  343. ];
  344. if (isset($data['deadline']) && !empty($data['deadline'])) {
  345. $purchaseData['deadline'] = $data['deadline'];
  346. }
  347. if (isset($data['modifyPrice']) && is_numeric($data['modifyPrice'])) {
  348. //优惠之后的金额
  349. if (is_numeric($data['modifyPrice']) == false || $data['modifyPrice'] <= 0) {
  350. util::fail('金额填错了哦');
  351. }
  352. $purchaseData['modifyPrice'] = $data['modifyPrice'];
  353. }
  354. //修改采购单
  355. $purchase = PurchaseClass::updatePurchase($purchase, $purchaseData);
  356. //除了自取订单直接变成已确认,其它都进入待确认流程。订单的确认以欠款或已收款方式确认。 ssh 20210809
  357. if (isset($data['sendType']) && $data['sendType'] == OrderClass::SEND_TYPE_NO) {
  358. PurchaseService::payAfter($purchase, $payWay);
  359. self::payAfter($returnOrder, $payWay);
  360. } else {
  361. //没有进入确认流程的订单也有打印需求
  362. if ($data['needPrint'] == dict::getDict('needPrint', 'need')) {
  363. OrderClass::onlinePrint($returnOrder);
  364. $returnOrder->printNum += 1;
  365. $returnOrder->save();
  366. }
  367. }
  368. return $returnOrder;
  369. }
  370. //自取免配送流程处理 ssh 2021.1.24
  371. public static function withoutSend($order)
  372. {
  373. if (isset($order->status) == false) {
  374. util::fail('没有订单状态');
  375. }
  376. if ($order->status == OrderClass::ORDER_STATUS_COMPLETE) {
  377. util::fail('订单已完成');
  378. }
  379. //自取订单,订单直接完成。【现在有三个地方有订单完成操作】
  380. $shopId = $order->shopId ?? 0;
  381. $shop = ShopClass::getLockById($shopId);
  382. if (empty($shop)) {
  383. util::fail('没有找到门店3');
  384. }
  385. $shop->unSendOrder -= 1;
  386. $shop->sendingOrder += 1;
  387. $shop->save();
  388. //自取免配送
  389. $order->sendType = OrderClass::SEND_TYPE_NO;
  390. $order->save();
  391. //这个是采购模板的withoutSend,应另外封装方法
  392. $purchaseId = $order->purchaseId ?? 0;
  393. $purchase = PurchaseClass::getById($purchaseId, true);
  394. $pShopId = $purchase->shopId;
  395. $pShop = ShopClass::getLockById($pShopId);
  396. $pShop->cgUnSend -= 1;
  397. $pShop->cgSending += 1;
  398. $pShop->save();
  399. //订单完成
  400. self::finish($order, $shop);
  401. OrderSendClass::withoutSend($order);
  402. return OrderClass::TOTAL_FLOW;
  403. }
  404. //确认送达 ssh 2021.3.4
  405. public static function reach($order)
  406. {
  407. if ($order->status != OrderClass::ORDER_STATUS_SENDING) {
  408. util::fail('订单没有在配送状态');
  409. }
  410. //第三方配送的变更第三方订单状态
  411. if (isset($order->sendType) && $order->sendType == OrderClass::SEND_TYPE_THIRD) {
  412. $express = OrderExpressClass::getByCondition(['orderSn' => $order->orderSn], true);
  413. if (!empty($express)) {
  414. $express->status = OrderExpressClass::STATUS_COMPLETE;
  415. $express->save();
  416. }
  417. }
  418. $shopId = $order->shopId ?? 0;
  419. $shop = ShopClass::getLockById($shopId);
  420. if (empty($shop)) {
  421. util::fail('没有找到门店4');
  422. }
  423. //订单完成
  424. self::finish($order, $shop);
  425. OrderSendClass::reach($order);
  426. //是否微信通知
  427. $noNeedWxNotice = isset(Yii::$app->params['noNeedWxNotice']) ? Yii::$app->params['noNeedWxNotice'] : 0;
  428. if ($noNeedWxNotice == 0) {
  429. //微信通知
  430. WxMessageClass::reachInform($shop, $order);
  431. }
  432. }
  433. //订单完成
  434. public static function finish($order, $shop)
  435. {
  436. //销售单完成
  437. $order = OrderClass::complete($order, $shop);
  438. //采购单完成
  439. $purchaseId = $order->purchaseId ?? 0;
  440. $purchase = PurchaseClass::getById($purchaseId, true);
  441. PurchaseClass::complete($purchase);
  442. }
  443. //获取订单信息 ssh 2019.11.28
  444. public static function getOrderList($where)
  445. {
  446. $data = self::getList('*', $where, 'addTime DESC');
  447. if (isset($data['list']) == false || empty($data['list'])) {
  448. return $data;
  449. }
  450. $orderSns = array_column($data['list'], 'orderSn');
  451. //获取订单的商品信息
  452. $goodsList = OrderGoodsService::getGoodsListByOrderSns($orderSns);
  453. //获取订花人的用户信息
  454. $orderUserIds = array_column($data['list'], 'userId');
  455. $orderUserIds = array_unique($orderUserIds);
  456. $userInfoList = UserService::getUserByIds($orderUserIds);
  457. $sjIdList = array_column($data['list'], 'sjId');
  458. $sjIdList = array_filter(array_unique($sjIdList));
  459. $merchantList = MerchantService::getByIds($sjIdList, null, 'id');
  460. $periodData = [0 => '上午', 1 => '下午', 2 => '晚上'];
  461. foreach ($data['list'] as $key => $val) {
  462. $id = $val['id'];
  463. $userId = $val['userId'];
  464. $data['list'][$key]['goodsInfoList'] = isset($goodsList[$id]) ? $goodsList[$id] : [];
  465. $data['list'][$key]['bookAvatar'] = isset($userInfoList[$userId]['smallAvatarUrl']) ? $userInfoList[$userId]['smallAvatarUrl'] : '';
  466. $sjId = $val['sjId'];
  467. $data['list'][$key]['name'] = isset($merchantList[$sjId]['name']) ? $merchantList[$sjId]['name'] : '';
  468. $data['list'][$key]['reachTime'] = OrderClass::getReachTime($val);
  469. $requireReachTime = '';
  470. if ($val['reachDate'] != '0000-00-00') {
  471. $reachPeriodId = $val['reachPeriod'];
  472. $reachPeriod = isset($periodData[$reachPeriodId]) ? $periodData[$reachPeriodId] : '上午';
  473. $requireReachTime = date("m-d", strtotime($val['reachDate'])) . ' ' . $reachPeriod;
  474. }
  475. $data['list'][$key]['requireReachTime'] = $requireReachTime;
  476. }
  477. return $data;
  478. }
  479. //取客户最近若干条订单 ssh 2019.11.30
  480. public static function getUserOrder($userId, $limit = 10, $order = null, $with = null)
  481. {
  482. $where = ['userId' => $userId, 'payStatus' => 1];
  483. return self::getLimitList('*', $where, $limit, $order, $with);
  484. }
  485. //支付前验证订单 ssh 2019.12.6
  486. public static function checkBeforePay($order, $userId)
  487. {
  488. $now = time();
  489. if (empty($order)) {
  490. util::fail('订单无效');
  491. }
  492. if (isset($order['userId']) && $order['userId'] != $userId) {
  493. util::fail('非法访问');
  494. }
  495. if ($order['status'] != 0) {
  496. util::fail('订单不是待付款状态');
  497. }
  498. if (isset($order['deadline']) && $now > $order['deadline']) {
  499. util::fail('订单已过期');
  500. }
  501. if (ceil($order['actPrice']) <= 0) {
  502. util::fail('订单金额有问题');
  503. }
  504. if ($order['payStatus'] == 1) {
  505. util::fail('您已经付过了');
  506. }
  507. }
  508. //商家验证是否有效 ssh 2019.12.15
  509. public static function valid($order, $shopId)
  510. {
  511. $now = date("Y-m-d H:i:s");
  512. if (empty($order)) {
  513. util::fail('订单无效');
  514. }
  515. if ($order['shopId'] != $shopId) {
  516. util::fail('不是您的订单');
  517. }
  518. if (isset($order['status']) && $order['status'] == OrderClass::ORDER_STATUS_UN_PAY) {
  519. if (isset($order['deadline']) && $now > $order['deadline']) {
  520. util::fail('订单已过期');
  521. }
  522. }
  523. }
  524. //点评 ssh 2019.12.16
  525. public static function comment($data)
  526. {
  527. return OrderClass::comment($data);
  528. }
  529. //订单归类
  530. public static function classify($id, $categoryId, $usageId)
  531. {
  532. $connection = Yii::$app->db;
  533. $transaction = $connection->beginTransaction();
  534. try {
  535. $order = OrderClass::getById($id, true);
  536. if ($order->payStatus != 1) {
  537. util::fail('订单还未付款');
  538. }
  539. if ($order->classify == 1) {
  540. util::fail('已经归类过了');
  541. }
  542. $order->categoryId = $categoryId;
  543. $order->usageId = $usageId;
  544. $order->classify = 1;
  545. $order->save();
  546. //设置流水的分类和用途并分配资金
  547. $setData = [
  548. 'sjId' => $order->sjId,
  549. 'capitalId' => $order->capitalId,
  550. 'time' => $order->payTime,
  551. 'usageId' => $order->usageId,
  552. 'categoryId' => $order->categoryId,
  553. 'amount' => $order->actPrice,
  554. 'payWay' => $order->payWay,
  555. ];
  556. SjCapitalService::orderClassify($setData);
  557. $transaction->commit();
  558. } catch (Exception $e) {
  559. $transaction->rollBack();
  560. util::fail('没有归类成功');
  561. }
  562. }
  563. //更新配送单 ssh 2019.12.17
  564. public static function updateSheet($order, $data)
  565. {
  566. $id = $order['id'];
  567. if ($order['status'] != OrderClass::ORDER_STATUS_UN_SEND) {
  568. util::fail('订单当前不是待配送状态');
  569. }
  570. $data['deliver'] = 1;
  571. OrderClass::updateById($id, $data);
  572. }
  573. //订单详情 ssh 2020.1.2
  574. public static function getOrderById($id)
  575. {
  576. return OrderClass::getOrderById($id);
  577. }
  578. //查看订单详情 ssh 2020.1.4
  579. public static function getOrderBySn($orderSn)
  580. {
  581. return OrderClass::getOrderBySn($orderSn);
  582. }
  583. //计算优惠 ssh 2020.3.9
  584. public static function getDiscountPrice($params)
  585. {
  586. $couponId = isset($params['couponId']) ? $params['couponId'] : 0;
  587. $userId = isset($params['userId']) ? $params['userId'] : 0;
  588. $price = isset($params['price']) ? $params['price'] : 0;
  589. $sourceType = isset($params['sourceType']) ? $params['sourceType'] : 0;
  590. $discountAmount = 0;
  591. $discountType = 0;
  592. $discountPrice = $price;
  593. //使用优惠券
  594. if (!empty($couponId)) {
  595. $discountAmount = CouponService::checkBeforeUse($couponId, $price, $userId);
  596. $discountPrice = stringUtil::calcSub($price, $discountAmount);
  597. $discountType = 1;
  598. } else {
  599. //使用会员
  600. // $asset = UserAssetClass::getByUserId($userId);
  601. // if (isset($asset['member']) && $asset['member'] > 0) {
  602. // $currentDiscount = $asset['discount'];
  603. // $currentPrice = $price * $currentDiscount;
  604. // $newPrice = substr(sprintf("%.3f", $currentPrice), 0, -1);
  605. // $discountType = 2;
  606. // $discountAmount = stringUtil::calcSub($price, $newPrice);
  607. // $discountPrice = $newPrice;
  608. // }
  609. }
  610. //如果没有优惠券和会员优惠,并且是朋友圈收款,则进行随机优惠 ssh 2019.9.12
  611. if ($discountPrice == $price && $sourceType == 3) {
  612. $discountAmount = OrderClass::getRandDiscount($price);
  613. //开发和测试环境直接随机优惠
  614. $env = getenv('YII_ENV');
  615. if ($env == 'local' || $env == 'test') {
  616. $discountAmount = 0.01;
  617. }
  618. $discountPrice = stringUtil::calcSub($price, $discountAmount);
  619. $discountType = 3;
  620. }
  621. $discountType = $discountAmount <= 0 ? 0 : $discountType;
  622. $discountPrice = $discountPrice <= 0 ? 0.01 : $discountPrice;
  623. return ['price' => $discountPrice, 'discountType' => $discountType, 'discountAmount' => $discountAmount];
  624. }
  625. //获取订单详情 ssh 2021.1.21
  626. public static function getOrderInfo($id, $showButton = false, $showItem = false, $showExpress = false, $isList = false)
  627. {
  628. $order = OrderClass::getById($id, true);
  629. if (empty($order)) {
  630. util::fail('没有找到订单');
  631. }
  632. $info = $order->attributes;
  633. $respond = OrderClass::groupOrder([$info], $showButton, $showItem, $showExpress, $isList);
  634. $result = current($respond);
  635. $orderId = intval($result['id'] ?? 0);
  636. $result['orderClearList'] = $orderId > 0 ? OrderCgClearClass::listPaidClearRecordsForOrder($orderId) : [];
  637. return $result;
  638. }
  639. //订单失效后的操作 ssh 2021.5.14
  640. public static function expire($order)
  641. {
  642. $purchaseId = $order->purchaseId ?? 0;
  643. $current = PurchaseClass::getById($purchaseId, true);
  644. if (empty($current)) {
  645. util::fail('没有找到采购单');
  646. }
  647. PurchaseService::expire($current);
  648. return true;
  649. }
  650. //支付成功后的流程 ssh 2021.5.14
  651. //$isPurchase 是否零售端采购支付,如果是会引起销售方余额变动
  652. public static function payAfter($order, $payWay, $isPurchase = false)
  653. {
  654. if (isset($order->status) == false) {
  655. util::fail('没有订单状态');
  656. }
  657. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  658. util::fail('重复操作');
  659. }
  660. if (isset($order->debt) == false) {
  661. util::fail('订单有问题,没有欠款项');
  662. }
  663. $orderId = $order->id;
  664. $orderSn = $order->orderSn ?? '';
  665. $customId = $order->customId;
  666. $ghs = null;
  667. if (in_array($payWay, [dict::getDict('payWay', 'balancePay'), dict::getDict('payWay', 'debtPay')], true)) {
  668. $pair = GhsRechargeSettleService::lockAccountPair(['id' => $customId]);
  669. $custom = $pair['custom'];
  670. $ghs = $pair['ghs'];
  671. } else {
  672. $custom = CustomClass::getLockById($customId);
  673. }
  674. if (empty($custom)) {
  675. util::fail('没有找到客户信息');
  676. }
  677. //门店资产变化
  678. $amount = $order->actPrice ?? 0.00;
  679. $realPrice = $order->realPrice ?? 0.00;
  680. $currentShopId = $order->shopId ?? 0;
  681. $book = $order->book ?? 0;
  682. $shop = ShopClass::getLockById($currentShopId);
  683. if (empty($shop)) {
  684. util::fail('没有找到门店5');
  685. }
  686. if ($payWay == dict::getDict('payWay', 'debtPay') && $book != 1) {
  687. if (isset($shop->overAllowDebt) && $shop->overAllowDebt == 0) {
  688. $debtLimit = $custom->debtLimit ?? 0;
  689. $outstanding = \bizGhs\custom\classes\AccountMoneyClass::getOutstandingDebt($custom);
  690. $newDebt = bcadd((string)$realPrice, (string)$outstanding, 2);
  691. if (bccomp($newDebt, (string)$debtLimit, 2) > 0) {
  692. util::fail('待结款已超' . $debtLimit . ',请先结账');
  693. }
  694. }
  695. }
  696. $mainId = $shop->mainId ?? 0;
  697. $main = MainClass::getLockById($mainId);
  698. if (empty($main)) {
  699. util::fail('没有main信息3');
  700. }
  701. $main->unPayOrder -= 1;
  702. //预订单的待发货订单增加
  703. if ($book == 1) {
  704. $main->unSendOrder += 1;
  705. //预订单统计数量增加
  706. $itemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  707. if (!empty($itemList)) {
  708. $bookData = [];
  709. foreach ($itemList as $currentItem) {
  710. $itemRemark = $currentItem->remark ?? 0;
  711. $hasRemark = !empty($itemRemark) ? 1 : 0;
  712. $bookData[] = [
  713. 'productId' => $currentItem->productId,
  714. 'num' => $currentItem->xhNum ?? 0,
  715. 'lastNum' => $currentItem->xhNum ?? 0,
  716. 'remark' => $itemRemark,
  717. 'hasRemark' => $hasRemark,
  718. ];
  719. }
  720. $staffId = $order->shopAdminId ?? 0;
  721. $staffName = $order->shopAdminName ?? '';
  722. $params = [
  723. 'staffId' => $staffId, 'staffName' => $staffName, 'action' => 'add'
  724. ];
  725. BookItemClass::addBatchItem($bookData, $order, $params);
  726. }
  727. } else {
  728. $main->finishOrder += 1;
  729. }
  730. $main->totalOrderNum += 1;
  731. $currentTotalIncome = bcadd($main->totalIncome, $amount, 2);
  732. $main->totalIncome = $currentTotalIncome;
  733. $totalSale = bcadd($main->totalSale, $amount, 2);
  734. $main->totalSale = $totalSale;
  735. if ($payWay == dict::getDict('payWay', 'debtPay')) {
  736. $currentGathering = bcadd($main->mayGathering, $realPrice, 2);
  737. $main->mayGathering = $currentGathering;
  738. if ($custom->debtNum == 0) {
  739. $main->mayGatheringNum += 1;
  740. }
  741. }
  742. $main->save();
  743. $capitalType = dict::getDict('capitalType', 'xhGhsOrder', 'id');
  744. $shopAdminId = $order->shopAdminId ?? 0;
  745. $shopAdminName = $order->shopAdminName ?? '';
  746. $event = '下单';
  747. if ($isPurchase) {
  748. $event = '客户采购';
  749. if (isset($custom->name) && !empty($custom->name)) {
  750. $event = $custom->name . '采购';
  751. }
  752. }
  753. $sjId = $order->sjId ?? 0;
  754. $shopId = $order->shopId ?? 0;
  755. $capital = [
  756. 'capitalType' => $capitalType,
  757. 'relateId' => $orderId,
  758. 'io' => 1,
  759. 'amount' => $amount,
  760. 'totalIncome' => $currentTotalIncome,
  761. 'payWay' => $payWay,
  762. 'event' => $event,
  763. 'mainId' => $mainId,
  764. 'sjId' => $sjId,
  765. 'shopId' => $shopId,
  766. 'shopAdminId' => $shopAdminId,
  767. 'shopAdminName' => $shopAdminName,
  768. 'mainId' => $mainId,
  769. ];
  770. ShopCapitalClass::addCapital($capital);
  771. //客户采购,会增加余额,会增加收入
  772. if ($isPurchase == true) {
  773. //余额支付和在线支付(微信支付、支付宝支付)会增加余额
  774. if ($order->onlinePay == dict::getDict('onlinePay', 'yes') || $payWay == dict::getDict('payWay', 'balancePay')) {
  775. ShopClass::customKdAddBalance($main, $shop, $realPrice, $order, $capitalType);
  776. }
  777. }
  778. //现金付款,现金余额需要增加
  779. if ($payWay == dict::getDict('payWay', 'cash')) {
  780. $moneyBalance = bcadd($main->money, $realPrice, 2);
  781. $main->money = $moneyBalance;
  782. $main->save();
  783. $moneyEvent = $custom->name . "现金下单" . floatval($realPrice) . "元(单号 {$orderSn})";
  784. $moneyRemark = '';
  785. $change = [
  786. 'relateId' => $orderId,
  787. 'amount' => $realPrice,
  788. 'balance' => $moneyBalance,
  789. 'io' => 1,
  790. 'mainId' => $mainId,
  791. 'capitalType' => $capitalType,
  792. 'ptStyle' => dict::getDict('ptStyle', 'ghs'),
  793. 'event' => $moneyEvent,
  794. 'remark' => $moneyRemark,
  795. ];
  796. ShopMoneyChangeClass::addData($change);
  797. }
  798. //更新订单基础状态和支付状态
  799. $order->payWay = $payWay;
  800. if ($book == 1) {
  801. $order->status = OrderClass::ORDER_STATUS_UN_SEND;
  802. } else {
  803. $order->status = OrderClass::ORDER_STATUS_UN_SEND;
  804. }
  805. if ($payWay == dict::getDict('payWay', 'debtPay')) {
  806. if (isset($order->actPrice) && $order->actPrice == 0) {
  807. $order->debt = OrderClass::DEBT_NO;
  808. } else {
  809. $order->debt = OrderClass::DEBT_YES;
  810. }
  811. $order->remainDebtPrice = $order->orderPrice ?? 0;
  812. $order->debtPrice = $order->orderPrice ?? 0;
  813. }
  814. $order->payStatus = 1;
  815. if (!isset($order->payTime) || $order->payTime == '0000-00-00 00:00:00') {
  816. $order->payTime = date("Y-m-d H:i:s");
  817. }
  818. $order->save();
  819. //新订单进入队列,用于花材的销量统计
  820. OrderClass::newOrderAddQueue($order);
  821. //员工业绩、总业绩增加
  822. $shopAdminId = $order->shopAdminId ?? 0;
  823. if (!empty($shopAdminId)) {
  824. $shopAdmin = ShopAdminClass::getById($shopAdminId, true);
  825. $shopAdmin->kdAmount = bcadd($shopAdmin->kdAmount, $amount, 2);
  826. $shopAdmin->save();
  827. $yjAmount = $order->orderPrice ?? 0;
  828. StatYjClass::addYj($main, $shop, $shopAdminId, $yjAmount);
  829. }
  830. //余额支付
  831. if ($payWay == dict::getDict('payWay', 'balancePay') && $isPurchase == false) {
  832. CustomClass::payToChangeBalance($order, $custom, $ghs);
  833. }
  834. //欠款
  835. if ($payWay == dict::getDict('payWay', 'debtPay')) {
  836. CustomClass::cgDebtAmountAdd($custom, $order, false, $ghs);
  837. }
  838. $custom->buyNum += 1;
  839. $custom->buyAmount = bcadd($custom->buyAmount, $amount, 2);
  840. $custom->visitTime = date("Y-m-d H:i:s");
  841. $custom->save();
  842. //收入统计
  843. StatIncomeClass::updateOrInsert($main, $shop, $amount);
  844. //各渠道收入金额统计
  845. StatKdClass::replace($shop, $amount, $payWay);
  846. //今日订单+1
  847. StatOrderClass::updateOrInsert($main, $shop);
  848. //销售统计
  849. StatSaleClass::replace($main, $shop, $amount);
  850. //客户采购统计
  851. StatKhCgClass::replace($order, $amount);
  852. //当天同个人同地址的订单汇总
  853. $prefixDate = substr($order->payTime, 0, 10);
  854. OrderClass::updateSameTimeIds($order, $prefixDate);
  855. OrderClass::updateMergeOrder($order, 0);
  856. }
  857. //发起退款
  858. public static function refund($id, $post)
  859. {
  860. $order = OrderClass::getLockById($id);
  861. if (empty($order)) {
  862. util::fail('没有找到订单');
  863. }
  864. // 无支付时间不能售后
  865. \bizGhs\order\services\NextDayRefundService::assertCanRefund($order);
  866. $sameDay = intval($post['sameDay'] ?? \bizGhs\order\classes\RefundOrderClass::SAME_DAY_YES);
  867. // 非当天 / 已结账 / 挂账结清 → 强制隔天售后(sameDay=0),不再拦截为「不能售后」
  868. if (\bizGhs\order\services\NextDayRefundService::mustUseNextDay($order)) {
  869. $sameDay = \bizGhs\order\classes\RefundOrderClass::SAME_DAY_NO;
  870. $post['sameDay'] = $sameDay;
  871. }
  872. // 兜底:仍写成当天且已结账时拦截(正常不会走到,mustUseNextDay 已覆盖)
  873. if ($sameDay === \bizGhs\order\classes\RefundOrderClass::SAME_DAY_YES
  874. && isset($order->clearId) && !empty($order->clearId)) {
  875. util::fail('已经结账,请按冲销处理');
  876. }
  877. if ($order->debt != 1 && $order->addTime < '2023-10-17 00:00:00') {
  878. util::fail('10月17日前订单无法申请退款');
  879. }
  880. //供货商销售单退款
  881. $saleRefund = RefundOrderService::addRefund($post, $order);
  882. $saleRefundId = $saleRefund->id;
  883. $purchaseId = $order->purchaseId;
  884. $cg = PurchaseClass::getLockById($purchaseId);
  885. if (empty($cg)) {
  886. util::fail('没有找到采购订单');
  887. }
  888. $mainId = $cg->mainId ?? 0;
  889. //花材列表结构
  890. // [{productId:0,num:1,unitType:0,unitPrice:12,unitName:'扎'}] productId 花材id num 退货数 unitType 大小单位0大1小 unitPrice 售价 unitName单位名称
  891. //供货商的花材信息转换成零售店的花材信息
  892. $ghsProduct = $post['product'] ?? '';
  893. $ghsProductIndex = array_column($ghsProduct, null, 'productId');
  894. $ids = array_column($ghsProduct, 'productId');
  895. $ghsProductInfo = ProductClass::getByIds($ids, null, 'itemId');
  896. $ptItemIds = array_keys($ghsProductInfo);
  897. $ptItemIds = array_unique(array_filter($ptItemIds));
  898. $hdProductInfo = ProductClass::getAllByCondition(['mainId' => $mainId, 'itemId' => ['in', $ptItemIds]], null, '*', 'itemId');
  899. $newProduct = [];
  900. foreach ($hdProductInfo as $ptItemId => $hdInfo) {
  901. $ghsItemId = $ghsProductInfo[$ptItemId]['id'] ?? 0;
  902. $current = $ghsProductIndex[$ghsItemId] ?? [];
  903. $hdItemId = $hdInfo['id'] ?? 0;
  904. $cost = $hdInfo['cost'] ?? 0;
  905. $name = $hdInfo['name'] ?? '';
  906. $cover = $hdInfo['cover'] ?? '';
  907. $ratio = $hdInfo['ratio'] ?? 20;
  908. if (empty($current)) {
  909. util::fail('没有找到花材');
  910. }
  911. $current['productId'] = $hdItemId;
  912. $current['ptItemId'] = $ptItemId;
  913. $current['cost'] = $cost;
  914. $current['name'] = $name;
  915. $current['cover'] = $cover;
  916. $current['ratio'] = $ratio;
  917. $newProduct[] = $current;
  918. }
  919. $refundType = $post['refundType'] ?? 0;
  920. $price = $post['price'] ?? 0;
  921. $remark = $post['remark'] ?? '';
  922. $cause = $post['cause'] ?? 0;
  923. $refundSendCost = isset($post['refundSendCost']) && is_numeric($post['refundSendCost']) ? $post['refundSendCost'] : 0;
  924. $refundPackCost = isset($post['refundPackCost']) && is_numeric($post['refundPackCost']) ? $post['refundPackCost'] : 0;
  925. $cgData = [
  926. 'product' => $newProduct,
  927. 'refundType' => $refundType,
  928. 'price' => $price,
  929. 'remark' => $remark,
  930. 'cause' => $cause,
  931. 'refundSendCost' => $refundSendCost,
  932. 'refundPackCost' => $refundPackCost,
  933. // 与销售侧售后成对写入隔天标记
  934. 'sameDay' => $saleRefund->sameDay ?? \bizGhs\order\classes\RefundOrderClass::SAME_DAY_YES,
  935. 'fundType' => $saleRefund->fundType ?? 0,
  936. ];
  937. $cgRefund = CgRefundService::addRefund($cgData, $cg);
  938. $cgRefundId = $cgRefund->id;
  939. $saleRefund->cgRefundId = $cgRefundId;
  940. $saleRefund->save();
  941. $cgRefund->saleRefundId = $saleRefundId;
  942. $cgRefund->sameDay = intval($saleRefund->sameDay ?? 1);
  943. $cgRefund->fundType = intval($saleRefund->fundType ?? 0);
  944. $cgRefund->save();
  945. return $saleRefund;
  946. }
  947. /**
  948. * 创建冲销单(金额为负的独立订单)
  949. * 设计说明:不复用极其庞杂的常规开单主链路(createNewOrder->OrderClass::addOrder),
  950. * 避免误伤现网所有商户的正常开单流程;只在数据落地时保持与正常订单相同的表结构,方便统一查询/统计。
  951. * @param $post array 前端提交参数:customId,product(JSON数组),remark,needPrint,payWay,forwardStock,returnBalance,
  952. * originalRefund(可选,原路退回网关,仅线上支付+关联原单时生效),relateOrderId(可选),refundOrderId(可选)
  953. * @param $custom array 客户信息(CustomClass::getCustom 返回)
  954. * @return array ['order'=>冲销单模型, 'customBalance'=>返充后的余额(未返充时为null), 'thirdRefundNo'=>原路退回的网关流水号(未走原路退回时为空)]
  955. */
  956. public static function createForwardOrder($post, $custom)
  957. {
  958. $customId = $custom['id'] ?? 0;
  959. $mainId = $post['mainId'] ?? 0;
  960. $shopId = $post['shopId'] ?? 0;
  961. $sjId = $post['sjId'] ?? 0;
  962. $shopAdminId = $post['shopAdminId'] ?? 0;
  963. $shopAdminName = $post['shopAdminName'] ?? '';
  964. $ghsId = $custom['ghsId'] ?? 0;
  965. //售后申请审核转冲销单场景:refundOrderId 是待审核的售后申请(xhRefund)id,
  966. //由 refundDetail.vue"通过"弹框直接提交而来,商品明细以售后申请里已提交的为准(不信任前端重新传的product),
  967. //避免和客户/花店实际申请的售后商品不一致;这里锁行是因为最后要把它标记为"已通过"。ssh 冲销单功能
  968. $refundOrderId = $post['refundOrderId'] ?? 0;
  969. $refundOrder = null;
  970. if (!empty($refundOrderId)) {
  971. $refundOrder = RefundOrderClass::getLockById($refundOrderId);
  972. if (empty($refundOrder)) {
  973. util::fail('没有找到售后申请');
  974. }
  975. if ($refundOrder->mainId != $mainId) {
  976. util::fail('售后申请信息不匹配');
  977. }
  978. if ($refundOrder->status != 0) {
  979. util::fail('该售后申请已被处理,请刷新页面');
  980. }
  981. if ($refundOrder->customId != $customId) {
  982. util::fail('售后申请客户信息不匹配');
  983. }
  984. $relateOrderSnFromRefund = $refundOrder->relateOrderSn ?? '';
  985. $relateOrderFromRefund = OrderClass::getByCondition(['orderSn' => $relateOrderSnFromRefund], true);
  986. if (empty($relateOrderFromRefund)) {
  987. util::fail('没有找到售后申请关联的原订单');
  988. }
  989. $post['relateOrderId'] = $relateOrderFromRefund->id;
  990. $refundItems = RefundOrderItemClass::getAllByCondition(['orderSn' => $refundOrder->orderSn], null, '*');
  991. $productList = [];
  992. foreach ($refundItems as $refundItem) {
  993. $productList[] = [
  994. 'productId' => $refundItem['productId'] ?? 0,
  995. 'bigNum' => ($refundItem['xhUnitType'] ?? 0) == 0 ? ($refundItem['xhNum'] ?? 0) : 0,
  996. 'smallNum' => ($refundItem['xhUnitType'] ?? 0) == 1 ? ($refundItem['xhNum'] ?? 0) : 0,
  997. 'price' => $refundItem['xhUnitPrice'] ?? 0,
  998. ];
  999. }
  1000. } else {
  1001. $productList = $post['product'] ?? [];
  1002. }
  1003. if (empty($productList)) {
  1004. util::fail('请选择花材');
  1005. }
  1006. $level = $custom['level'] ?? 1;
  1007. $live = isset($custom['live']) ? $custom['live'] : 1;
  1008. $respond = ProductClass::formatProductInfo($productList, $level, $live, ['custom' => $custom]);
  1009. $items = $respond['product'] ?? [];
  1010. if (empty($items)) {
  1011. util::fail('花材信息有误');
  1012. }
  1013. //本次冲销总金额(正数)
  1014. $totalAmount = 0;
  1015. foreach ($items as $it) {
  1016. $totalAmount = bcadd($totalAmount, $it['price'], 2);
  1017. }
  1018. if (bccomp($totalAmount, '0', 2) <= 0) {
  1019. util::fail('冲销金额必须大于0');
  1020. }
  1021. $forwardStock = isset($post['forwardStock']) && in_array((int)$post['forwardStock'], [0, 1], true) ? (int)$post['forwardStock'] : 1;
  1022. $returnBalance = isset($post['returnBalance']) && (int)$post['returnBalance'] == 1 ? 1 : 0;
  1023. //原路退回(仅线上支付关联原单场景可用):是否调支付网关把这笔钱退回给付款人,与"返充到余额"二选一。ssh 冲销单功能
  1024. $originalRefund = isset($post['originalRefund']) && (int)$post['originalRefund'] == 1 ? 1 : 0;
  1025. $payWay = isset($post['payWay']) ? (int)$post['payWay'] : dict::getDict('payWay', 'wxPay');
  1026. //关联原单场景:累计冲销上限校验,并且强制按原单支付方式,不信任前端传的 payWay
  1027. $relateOrderId = $post['relateOrderId'] ?? 0;
  1028. $relateOrder = null;
  1029. $relateCg = null;
  1030. if (!empty($relateOrderId)) {
  1031. $relateOrder = OrderClass::getLockById($relateOrderId);
  1032. if (empty($relateOrder)) {
  1033. util::fail('没有找到原订单');
  1034. }
  1035. if ($relateOrder->mainId != $mainId || $relateOrder->customId != $customId) {
  1036. util::fail('原订单信息不匹配');
  1037. }
  1038. //服务端复核"转冲销单"资格:非当天下单 或者 欠款已结清,二者满足其一才允许,不能只靠前端拦截,
  1039. //避免绕过前端直接调接口对"今天下的、欠款还没结清"的订单发起冲销单。ssh 冲销单功能
  1040. $relatePayTime = $relateOrder->payTime ?? '';
  1041. $notToday = empty($relatePayTime) || date('Y-m-d', strtotime($relatePayTime)) != date('Y-m-d');
  1042. $debtCleared = bccomp($relateOrder->debtPrice ?? 0, '0', 2) > 0 && bccomp($relateOrder->remainDebtPrice ?? 0, '0', 2) == 0;
  1043. if (!$notToday && !$debtCleared) {
  1044. util::fail('该订单不满足转冲销单条件(需为非当天订单,或欠款已结清),请走常规售后流程');
  1045. }
  1046. $actPrice = $relateOrder->actPrice ?? 0;
  1047. $hasForwardPrice = $relateOrder->forwardPrice ?? 0;
  1048. if (bccomp($hasForwardPrice, $actPrice, 2) >= 0) {
  1049. util::fail('该订单已冲销完,无法再次冲销');
  1050. }
  1051. $remain = bcsub($actPrice, $hasForwardPrice, 2);
  1052. if (bccomp($totalAmount, $remain, 2) == 1) {
  1053. util::fail("冲销金额超过原订单可冲销余额(剩余可冲销 ¥{$remain})");
  1054. }
  1055. //退款方式锁定为原单实际支付方式
  1056. $payWay = $relateOrder->payWay ?? $payWay;
  1057. //花店侧原采购单:下面"原路退回"网关退款、以及后面同步hasForward/forwardPrice都要用到,这里统一加锁取一次
  1058. $relateCgId = $relateOrder->purchaseId ?? 0;
  1059. if (!empty($relateCgId)) {
  1060. $relateCg = PurchaseClass::getLockById($relateCgId);
  1061. }
  1062. }
  1063. //资金处理方式按原单支付渠道强制/校验,不完全信任前端传值:仅在"售后转冲销单"(带relateOrderId)场景生效,
  1064. //因为只有这种场景 payWay 才是真实原订单的支付渠道;没有关联原单的自由开冲销单,payWay 只是用户自己选的
  1065. //一个记账渠道说明,并不对应任何真实交易,不需要也不能做这里的强制/原路退回逻辑。
  1066. //挂账、余额支付:欠款本质是负余额,返充余额=冲减欠款,二者在账本层面是同一个动作,强制走"返充余额",不允许原路退回网关
  1067. //微信/支付宝:允许"原路退回"(真实网关退款)与"返充余额"二选一
  1068. if (!empty($relateOrderId)) {
  1069. $wxPay = dict::getDict('payWay', 'wxPay');
  1070. $aliPay = dict::getDict('payWay', 'alipay');
  1071. $debtPay = dict::getDict('payWay', 'debtPay');
  1072. $balancePay = dict::getDict('payWay', 'balancePay');
  1073. if (in_array($payWay, [$debtPay, $balancePay], true)) {
  1074. $returnBalance = 1;
  1075. $originalRefund = 0;
  1076. } elseif (in_array($payWay, [$wxPay, $aliPay], true)) {
  1077. if ($originalRefund == 1) {
  1078. if (empty($relateCg)) {
  1079. util::fail('没有关联原订单的真实交易信息,无法原路退回');
  1080. }
  1081. //原路退回和返充余额二选一,不能同时生效
  1082. $returnBalance = 0;
  1083. }
  1084. } else {
  1085. $originalRefund = 0;
  1086. }
  1087. } else {
  1088. //自由开冲销单:不存在"原路退回网关"这个概念,永远不生效,防止前端异常传参
  1089. $originalRefund = 0;
  1090. }
  1091. //落库统一取负:金额字段为负,数量字段保持正数(代表冲销的数量)
  1092. $negItems = [];
  1093. $totalCost = 0;
  1094. foreach ($items as $it) {
  1095. $it['price'] = bcmul($it['price'], -1, 2);
  1096. $it['userPrice'] = bcmul($it['userPrice'], -1, 2);
  1097. $it['unitPrice'] = bcmul($it['unitPrice'], -1, 2);
  1098. $it['smallUnitPrice'] = bcmul($it['smallUnitPrice'], -1, 2);
  1099. $it['xhPrice'] = bcmul($it['xhPrice'], -1, 2);
  1100. $it['xhUnitPrice'] = bcmul($it['xhUnitPrice'], -1, 2);
  1101. $it['xhPrePrice'] = bcmul($it['xhPrePrice'], -1, 2);
  1102. $it['xhPreUnitPrice'] = bcmul($it['xhPreUnitPrice'], -1, 2);
  1103. $it['cost'] = bcmul($it['cost'], -1, 2);
  1104. $it['forward'] = 1;
  1105. $totalCost = bcadd($totalCost, $it['cost'], 2);
  1106. $negItems[] = $it;
  1107. }
  1108. $actPrice = bcmul($totalAmount, -1, 2);
  1109. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'ghsId' => $ghsId, 'customId' => $customId];
  1110. $orderSn = orderSn::getGhsOrderSn($snData);
  1111. $now = date('Y-m-d H:i:s');
  1112. $deadline = date('Y-m-d H:i:s', time() + dict::getDict('order_pay_has_time'));
  1113. $orderData = [
  1114. 'mainId' => $mainId,
  1115. 'sendNum' => '',
  1116. 'orderSn' => $orderSn,
  1117. 'customId' => $customId,
  1118. 'customName' => $custom['name'] ?? '',
  1119. 'customNamePy' => $custom['py'] ?? '',
  1120. 'customAvatar' => $custom['shortSmallAvatar'] ?? '',
  1121. 'customMobile' => $custom['mobile'] ?? '',
  1122. 'ghsId' => $ghsId,
  1123. 'sjId' => $sjId,
  1124. 'shopId' => $shopId,
  1125. 'shopAdminId' => $shopAdminId,
  1126. 'shopAdminName' => $shopAdminName,
  1127. 'getStaffId' => $shopAdminId,
  1128. 'getStaffName' => $shopAdminName,
  1129. 'itemNum' => $respond['totalItemNum'] ?? 0,
  1130. 'bigNum' => $respond['bigNum'] ?? 0,
  1131. 'smallNum' => $respond['smallNum'] ?? 0,
  1132. 'itemPrice' => $actPrice,
  1133. 'prePrice' => $actPrice,
  1134. 'orderPrice' => $actPrice,
  1135. 'bookPrice' => $actPrice,
  1136. 'realPrice' => $actPrice,
  1137. 'actPrice' => $actPrice,
  1138. 'totalCost' => $totalCost,
  1139. 'remainCost' => $totalCost,
  1140. 'payWay' => $payWay,
  1141. 'fromType' => 1,
  1142. 'debt' => OrderClass::DEBT_NO,
  1143. 'status' => OrderClass::ORDER_STATUS_COMPLETE,
  1144. 'payStatus' => OrderClass::PAY_STATUS_HAS_PAY,
  1145. 'sendType' => OrderClass::SEND_TYPE_SHOP_GET,
  1146. 'sendStatus' => -4,
  1147. 'sendTimeWant' => date('Y-m-d'),
  1148. 'payTime' => $now,
  1149. 'deadline' => $deadline,
  1150. 'autoSetTime' => $deadline,
  1151. 'needPrint' => $post['needPrint'] ?? 2,
  1152. 'remark' => $post['remark'] ?? '',
  1153. 'forward' => 1,
  1154. 'forwardStock' => $forwardStock,
  1155. 'salt' => stringUtil::charsShuffleLowerCase(10),
  1156. ];
  1157. $order = OrderClass::add($orderData, true);
  1158. foreach ($negItems as $it) {
  1159. $it['orderSn'] = $orderSn;
  1160. $it['mainId'] = $mainId;
  1161. OrderItemClass::add($it, true);
  1162. }
  1163. //库存处理:forwardStock==0 货退回来则加库存,==1 不退回则不动库存
  1164. if ($forwardStock == 0) {
  1165. $customName = $custom['name'] ?? '';
  1166. foreach ($negItems as $it) {
  1167. $productId = $it['productId'] ?? 0;
  1168. $itemNum = $it['num'] ?? 0;
  1169. if (empty($productId) || bccomp($itemNum, '0', 2) <= 0) {
  1170. continue;
  1171. }
  1172. $stockInfo = ProductClass::addStockByItemNum($productId, $itemNum);
  1173. $recordData = [
  1174. 'sjId' => $sjId,
  1175. 'shopId' => $shopId,
  1176. 'mainId' => $mainId,
  1177. 'orderSn' => $orderSn,
  1178. 'itemId' => $it['itemId'] ?? 0,
  1179. 'productId' => $productId,
  1180. 'itemNum' => $itemNum,
  1181. 'oldStock' => $stockInfo['oldStock'] ?? 0,
  1182. 'newStock' => $stockInfo['newStock'] ?? 0,
  1183. 'relateName' => $customName,
  1184. 'ptStyle' => dict::getDict('ptStyle', 'ghs'),
  1185. 'io' => 1,
  1186. ];
  1187. StockRecordClass::ghsRefundAddRecord($recordData);
  1188. }
  1189. }
  1190. //配对生成花店侧采购冲销记录 xhCg/xhCgItem,直接构造模型保存,不复用 PurchaseClass::addPurchase 的完整业务规则
  1191. //此处需要加锁,因为下面还要用它同步扣减 xhGhs.expendAmount(累计消费镜像字段)
  1192. $ghs = GhsClass::getLockById($ghsId);
  1193. $cgSn = orderSn::getPurchaseSn($snData);
  1194. $cgData = [
  1195. 'mainId' => $ghs['ownMainId'] ?? 0,
  1196. 'saleId' => $order->id ?? 0,
  1197. 'orderSn' => $cgSn,
  1198. 'customId' => $customId,
  1199. 'ghsId' => $ghsId,
  1200. 'ghsName' => $ghs['name'] ?? '',
  1201. 'ghsAvatar' => $ghs['avatar'] ?? '',
  1202. 'ghsMobile' => $ghs['mobile'] ?? '',
  1203. 'ghsFullAddress' => $ghs['fullAddress'] ?? '',
  1204. 'sjId' => $custom['sjId'] ?? 0,
  1205. 'shopId' => $custom['shopId'] ?? 0,
  1206. 'ghsShopId' => $shopId,
  1207. 'ghsShopAdminId' => $shopAdminId,
  1208. 'ghsShopAdminName' => $shopAdminName,
  1209. 'itemPrice' => $actPrice,
  1210. 'prePrice' => $actPrice,
  1211. 'orderPrice' => $actPrice,
  1212. 'bookPrice' => $actPrice,
  1213. 'realPrice' => $actPrice,
  1214. 'actPrice' => $actPrice,
  1215. 'kindNum' => count($negItems),
  1216. 'bigNum' => $respond['bigNum'] ?? 0,
  1217. 'smallNum' => $respond['smallNum'] ?? 0,
  1218. 'payWay' => $payWay,
  1219. 'status' => PurchaseClass::STATUS_COMPLETE,
  1220. 'cgStyle' => dict::getDict('cgStyle', 'ghs'),
  1221. 'debt' => PurchaseClass::DEBT_NO,
  1222. 'getType' => PurchaseClass::GET_TYPE_SELF_GET,
  1223. 'payStatus' => 1,
  1224. 'sendTimeWant' => date('Y-m-d'),
  1225. 'payTime' => $now,
  1226. 'remark' => $post['remark'] ?? '',
  1227. 'forward' => 1,
  1228. 'forwardStock' => $forwardStock,
  1229. 'salt' => stringUtil::charsShuffleLowerCase(10),
  1230. ];
  1231. $cg = PurchaseClass::add($cgData, true);
  1232. $order->purchaseId = $cg->id ?? 0;
  1233. $order->save(false, ['purchaseId']);
  1234. foreach ($negItems as $it) {
  1235. $cgItemData = [
  1236. 'name' => $it['name'] ?? '',
  1237. 'cover' => $it['cover'] ?? '',
  1238. 'orderSn' => $cgSn,
  1239. 'productId' => $it['productId'] ?? 0,
  1240. 'itemId' => $it['itemId'] ?? 0,
  1241. 'mainId' => $cgData['mainId'],
  1242. 'ghsId' => $ghsId,
  1243. 'itemNum' => $it['num'] ?? 0,
  1244. 'preItemNum' => $it['num'] ?? 0,
  1245. 'itemInfo' => json_encode(['itemName' => $it['name'] ?? '', 'bigNum' => $it['bigNum'] ?? 0, 'smallNum' => $it['smallNum'] ?? 0]),
  1246. 'ghsProductId' => $it['productId'] ?? 0,
  1247. 'ratio' => $it['ratio'] ?? 0,
  1248. 'ratioType' => $it['ratioType'] ?? 0,
  1249. 'price' => $it['userPrice'] ?? 0,
  1250. 'totalPrice' => $it['price'] ?? 0,
  1251. 'preTotalPrice' => $it['price'] ?? 0,
  1252. 'variety' => $it['variety'] ?? 0,
  1253. 'unitWeight' => $it['unitWeight'] ?? 0,
  1254. 'belongCost' => $it['belongCost'] ?? 0,
  1255. 'remark' => $it['remark'] ?? '',
  1256. 'kind' => $it['kind'] ?? 0,
  1257. 'forward' => 1,
  1258. ];
  1259. PurchaseItemClass::add($cgItemData, true);
  1260. }
  1261. //累计消费金额同步:冲销单本质是负金额订单,$actPrice 已经是负数。
  1262. //xhGhsCustom.buyAmount 与 xhGhs.expendAmount 是同一份"累计消费"的两边镜像
  1263. //(参考 CustomController::actionRefreshBuyamount 按订单 actPrice 汇总重算两边字段的口径),
  1264. //这里直接按 actPrice 同步扣减,两边保持一致;但冲销单不算一次新的"下单",buyNum/买入次数不增加。
  1265. $lockCustom = CustomClass::getLockById($customId);
  1266. if (empty($lockCustom)) {
  1267. util::fail('没有找到客户');
  1268. }
  1269. $lockCustom->buyAmount = bcadd($lockCustom->buyAmount ?? '0.00', $actPrice, 2);
  1270. $lockCustom->save(false, ['buyAmount']);
  1271. $ghs->expendAmount = bcadd($ghs->expendAmount ?? '0.00', $actPrice, 2);
  1272. $ghs->save(false, ['expendAmount']);
  1273. //资金处理:originalRefund==1 调支付网关原路退回给付款人;returnBalance==1 加回客户余额;
  1274. //两者都为0时不改动任何资金字段,只把 payWay 记在订单上作为返款渠道记录。ssh 冲销单功能
  1275. $customBalance = null;
  1276. $thirdRefundNo = '';
  1277. if ($originalRefund == 1) {
  1278. //原路退回:用原单对应的采购单(xhCg)真实支付信息调网关退款,用冲销单自己的orderSn做退款流水号,天然保证唯一/幂等
  1279. $thirdRefundNo = PurchaseClass::forwardOriginalOnlineRefund($relateCg, $orderSn, $totalAmount, '冲销单' . $orderSn . '原路退回');
  1280. $order->remark = trim(($order->remark ?? '') . " [原路退回成功,网关退款单号:{$thirdRefundNo}]");
  1281. $order->save(false, ['remark']);
  1282. } elseif ($returnBalance == 1) {
  1283. $customBalance = CustomClass::forwardReturnBalance($lockCustom, $order, $totalAmount);
  1284. }
  1285. //关联原单:写关系表 + 同步原单 hasForward/forwardPrice 与订单项 forwardNum
  1286. if (!empty($relateOrderId) && !empty($relateOrder)) {
  1287. OrderForwardClass::addRelate($relateOrder, $order, $totalAmount);
  1288. $relateOrder->hasForward = 1;
  1289. $relateOrder->forwardPrice = bcadd($relateOrder->forwardPrice ?? 0, $totalAmount, 2);
  1290. $relateOrder->save(false, ['hasForward', 'forwardPrice']);
  1291. $relateItems = OrderItemClass::getAllByCondition(['orderSn' => $relateOrder->orderSn], null, '*', 'productId', true);
  1292. foreach ($negItems as $it) {
  1293. $productId = $it['productId'] ?? 0;
  1294. $relateItem = $relateItems[$productId] ?? null;
  1295. if (!empty($relateItem)) {
  1296. $relateItem->forward = 1;
  1297. $relateItem->forwardNum = bcadd($relateItem->forwardNum ?? 0, $it['num'] ?? 0, 2);
  1298. $relateItem->save(false, ['forward', 'forwardNum']);
  1299. }
  1300. }
  1301. //同步花店侧原采购单(xhCg)的 hasForward/forwardPrice 与采购单项(xhCgItem)的 forwardNum,
  1302. //供 hdApp 的 purDetails.vue/refundList.vue 展示冲销记录,与 GHS 侧原单缓存字段保持一致
  1303. //($relateCg 已在前面校验资金处理方式时统一加锁取过,这里直接复用,避免重复查询/重复加锁)
  1304. if (!empty($relateCg)) {
  1305. $relateCg->hasForward = 1;
  1306. $relateCg->forwardPrice = bcadd($relateCg->forwardPrice ?? 0, $totalAmount, 2);
  1307. $relateCg->save(false, ['hasForward', 'forwardPrice']);
  1308. $relateCgItems = PurchaseItemClass::getAllByCondition(['orderSn' => $relateCg->orderSn], null, '*', 'productId', true);
  1309. foreach ($negItems as $it) {
  1310. $productId = $it['productId'] ?? 0;
  1311. $relateCgItem = $relateCgItems[$productId] ?? null;
  1312. if (!empty($relateCgItem)) {
  1313. $relateCgItem->forward = 1;
  1314. $relateCgItem->forwardNum = bcadd($relateCgItem->forwardNum ?? 0, $it['num'] ?? 0, 2);
  1315. $relateCgItem->save(false, ['forward', 'forwardNum']);
  1316. }
  1317. }
  1318. }
  1319. }
  1320. //售后申请审核转冲销单:这条售后申请本身并没有走老的 passRefund 流程(没有原路退款/没有改原订单actPrice等),
  1321. //真正的退款/退货/返余额是由上面新生成的这张冲销单完成的,所以不能标"已通过"(会让人误以为是走了老流程原路退款)。
  1322. //这里标"已取消",并把冲销单号写进 hdRemark 备注,同时用 forwardOrderId 结构化记录对应的冲销单id,
  1323. //方便后续排查/统计这条售后申请最终去了哪(forwardOrderId=0表示常规售后,未转冲销单)。ssh 冲销单功能
  1324. if (!empty($refundOrder)) {
  1325. $refundOrder->status = RefundOrderClass::STATUS_CANCEL;
  1326. $refundOrder->forwardOrderId = $order->id;
  1327. $refundOrder->hdRemark = '已转为冲销单处理,退款/退货/返余额流程详见冲销单:' . $orderSn;
  1328. $refundOrder->shopAdminId = $shopAdminId;
  1329. $refundOrder->shopAdminName = $shopAdminName;
  1330. $refundOrder->save(false, ['status', 'forwardOrderId', 'hdRemark', 'shopAdminId', 'shopAdminName']);
  1331. //明细项同步标记为"已取消",与父级售后申请的status保持一致(不再是"已处理",因为并没有走老的passRefund流程去处理它)
  1332. $refundItemModels = RefundOrderItemClass::getAllByCondition(['orderSn' => $refundOrder->orderSn], null, '*', null, true);
  1333. foreach ($refundItemModels as $refundItemModel) {
  1334. $refundItemModel->status = RefundOrderClass::STATUS_CANCEL;
  1335. $refundItemModel->save(false, ['status']);
  1336. }
  1337. //同步花店端(hdApp)对应的售后记录(xhCgRefund):一条售后在GHS/HD两端各有一条记录(通过cgRefundId关联),
  1338. //两端都要能看出"这条售后已转冲销单",HD侧记录的是花店视角的冲销采购单id(xhCg.id)
  1339. $cgRefundId = $refundOrder->cgRefundId ?? 0;
  1340. if (!empty($cgRefundId)) {
  1341. $cgRefund = CgRefundClass::getLockById($cgRefundId);
  1342. if (!empty($cgRefund)) {
  1343. $cgRefund->forwardCgId = $cg->id ?? 0;
  1344. $cgRefund->hdRemark = '已转为冲销单处理,退款/退货/返余额流程详见冲销单:' . $cgSn;
  1345. $cgRefund->save(false, ['forwardCgId', 'hdRemark']);
  1346. }
  1347. }
  1348. }
  1349. return ['order' => $order, 'customBalance' => $customBalance, 'thirdRefundNo' => $thirdRefundNo];
  1350. }
  1351. }