PurchaseClass.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. <?php
  2. namespace bizHd\purchase\classes;
  3. use biz\ghs\classes\GhsClass;
  4. use biz\product\classes\XjClass;
  5. use biz\shop\classes\ShopCapitalClass;
  6. use biz\shop\classes\ShopClass;
  7. use biz\shop\classes\ShopCouponClass;
  8. use biz\sj\classes\SjClass;
  9. use biz\stat\classes\StatCgClass;
  10. use biz\stat\classes\StatCgGhsClass;
  11. use biz\stat\classes\StatOutClass;
  12. use biz\stock\classes\StockClass;
  13. use biz\wx\classes\WxMessageClass;
  14. use bizGhs\admin\classes\AdminClass;
  15. use bizGhs\custom\classes\CustomClass;
  16. use bizGhs\item\classes\CostChangeClass;
  17. use bizGhs\order\classes\OrderClass;
  18. use bizGhs\order\traits\OrderTrait;
  19. use bizGhs\product\classes\ProductClass;
  20. use bizGhs\stock\classes\OnStockRecordClass;
  21. use bizGhs\stock\classes\StockRecordClass;
  22. use bizGhs\stock\services\StockRecordService;
  23. use bizHd\cg\classes\CgRefundClass;
  24. use bizHd\cg\classes\CgTreeClass;
  25. use bizHd\cg\classes\CgXjClass;
  26. use bizHd\shop\classes\MainClass;
  27. use bizHd\stat\classes\StatIncomeClass;
  28. use bizHd\wx\classes\WxOpenClass;
  29. use common\components\dict;
  30. use common\components\imgUtil;
  31. use common\components\IntraCityExpress;
  32. use common\components\mapUtil;
  33. use common\components\noticeUtil;
  34. use common\components\orderSn;
  35. use common\components\util;
  36. use bizHd\base\classes\BaseClass;
  37. use common\components\lakala\Lakala;
  38. use Yii;
  39. use yii\helpers\ArrayHelper;
  40. class PurchaseClass extends BaseClass
  41. {
  42. use OrderTrait;
  43. public static $baseFile = '\bizHd\purchase\models\Purchase';
  44. //订单状态 1待付款,待确认,2待配送,3配送中,4已完成,5取消,失败
  45. const STATUS_UN_PAY = 1;
  46. const STATUS_UN_SEND = 2;
  47. const STATUS_SENDING = 3;
  48. const STATUS_COMPLETE = 4;
  49. const STATUS_CANCEL = 5;
  50. //未知
  51. const DEBT_UNKNOWN = 0;
  52. //欠款
  53. const DEBT_YES = 1;
  54. //没有欠款
  55. const DEBT_NO = 2;
  56. //配送,这里的数值是错的,请参考dict.php的数值
  57. const GET_TYPE_SEND = 1;
  58. //自取,这里的数值是错的,请参考dict.php的数值
  59. const GET_TYPE_SELF_GET = 2;
  60. const REFUND_NO = 1;
  61. const REFUND_YES = 2;
  62. //获取打包费
  63. public static function getKmPackCost($mainId)
  64. {
  65. $cost = dict::getDict('kmPackCost');
  66. if (getenv('YII_ENV') == 'production') {
  67. //云漫梦金鹏 徐记花卉 康多鲜 旭海 打包费0元
  68. if (in_array($mainId, [10728, 20528, 10866, 38657, 41121])) {
  69. $cost = dict::getDict('kmPackCost2');
  70. }
  71. //花瀚鲜花供应链
  72. if (in_array($mainId, [50, 14499])) {
  73. $cost = dict::getDict('kmPackCost3');
  74. }
  75. } else {
  76. }
  77. return $cost;
  78. }
  79. //订单发货主方法 ssh 20231119
  80. public static function orderSend($cg, $params, $allowRepeat)
  81. {
  82. $respond = self::orderFh($cg, $params, $allowRepeat);
  83. $orderId = $cg->saleId ?? 0;
  84. $orderInfo = OrderClass::getById($orderId, true);
  85. if (empty($orderInfo)) {
  86. util::fail('没有找到销售单信息');
  87. }
  88. OrderClass::orderFh($orderInfo, $params, $allowRepeat);
  89. return $respond;
  90. }
  91. public static function cancelFh($cg, $params)
  92. {
  93. $cg->status = 2;
  94. $cg->save();
  95. $orderSn = $cg->orderSn ?? '';
  96. $itemList = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  97. if (!empty($itemList)) {
  98. $sjId = $cg->sjId ?? 0;
  99. $shopId = $cg->shopId ?? 0;
  100. $mainId = $cg->mainId ?? 0;
  101. $ghsName = $cg->ghsName ?? '';
  102. foreach ($itemList as $key => $val) {
  103. $productId = $val->productId ?? 0;
  104. $itemId = $val->itemId ?? 0;
  105. $num = $val->xhNum ?? 0;
  106. $product = ProductClass::getLockById($productId);
  107. if (empty($product)) {
  108. util::fail('没有找到花材呢');
  109. }
  110. //减少路上库存
  111. $onRecord = [];
  112. $onRecord['sjId'] = $sjId;
  113. $onRecord['shopId'] = $shopId;
  114. $onRecord['mainId'] = $mainId;
  115. $onRecord['orderSn'] = $orderSn;
  116. $onRecord['productId'] = $productId;
  117. $onRecord['itemId'] = $itemId;
  118. $onRecord['relateName'] = $ghsName;
  119. $onRecord['itemNum'] = $num;
  120. $oldOnStock = $product->onStock ?? 0;
  121. $onRecord['oldStock'] = $oldOnStock;
  122. $newOnStock = bcsub($oldOnStock, $num);
  123. $onRecord['newStock'] = $newOnStock;
  124. $onRecord['ptStyle'] = 1;
  125. OnStockRecordClass::cancelCg($onRecord);
  126. ProductClass::decreaseOnStockByItemNum($productId, $num);
  127. }
  128. }
  129. }
  130. //订单发货子方法 ssh 20231119
  131. public static function orderFh($cg, $params, $allowRepeat = false, $notice = false)
  132. {
  133. if ($notice) {
  134. $noticeText = json_encode(['id' => $cg->id]);
  135. $noticeKey = "ghsKdNoticeHd";
  136. Yii::$app->redis->executeCommand('LPUSH', [$noticeKey, $noticeText]);
  137. }
  138. if ($cg->status == 3) {
  139. if (!$allowRepeat) {
  140. util::fail('订单已发货');
  141. } else {
  142. return true;
  143. }
  144. }
  145. $fhType = $params['fhType'] ?? 0;
  146. if (!is_numeric($fhType)) {
  147. util::fail('请选择发货类型');
  148. }
  149. if ($fhType == 1) {
  150. $fhWl = $params['fhWl'] ?? '';
  151. $fhWlNo = $params['fhWlNo'] ?? '';
  152. if (empty($fhWl)) {
  153. util::fail('请填写物流名称');
  154. }
  155. if (empty($fhWlNo)) {
  156. util::fail('请填写物流编号');
  157. }
  158. $cg->fhWl = $fhWl;
  159. $cg->fhWlNo = $fhWlNo;
  160. }
  161. $cg->fhType = $fhType;
  162. $cg->status = 3;
  163. $cg->fhTime = date("Y-m-d H:i:s");
  164. $cg->save();
  165. $orderSn = $cg->orderSn ?? '';
  166. $itemList = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  167. if (!empty($itemList)) {
  168. $sjId = $cg->sjId ?? 0;
  169. $shopId = $cg->shopId ?? 0;
  170. $mainId = $cg->mainId ?? 0;
  171. $ghsName = $cg->ghsName ?? '';
  172. foreach ($itemList as $key => $val) {
  173. $productId = $val->productId ?? 0;
  174. $itemId = $val->itemId ?? 0;
  175. $num = $val->xhNum ?? 0;
  176. $product = ProductClass::getLockById($productId);
  177. if (empty($product)) {
  178. util::fail('没有找到花材呢');
  179. }
  180. //增加路上库存
  181. $onRecord = [];
  182. $onRecord['sjId'] = $sjId;
  183. $onRecord['shopId'] = $shopId;
  184. $onRecord['mainId'] = $mainId;
  185. $onRecord['orderSn'] = $orderSn;
  186. $onRecord['productId'] = $productId;
  187. $onRecord['itemId'] = $itemId;
  188. $onRecord['relateName'] = $ghsName;
  189. $onRecord['itemNum'] = $num;
  190. $oldOnStock = $product->onStock ?? 0;
  191. $onRecord['oldStock'] = $oldOnStock;
  192. $newOnStock = bcadd($oldOnStock, $num);
  193. $onRecord['newStock'] = $newOnStock;
  194. $onRecord['ptStyle'] = 1;
  195. OnStockRecordClass::addPurchaseOrderRecord($onRecord);
  196. ProductClass::addOnStockByItemNum($productId, $num);
  197. }
  198. }
  199. return $cg;
  200. }
  201. //确认收货 ssh 20231119
  202. public static function confirmTake($cg)
  203. {
  204. //订单如果没有发货,则先发货
  205. if ($cg->status == self::STATUS_UN_SEND) {
  206. $cg = self::orderSend($cg, [], true);
  207. }
  208. // 构建“冲销”函数的参数 -- 变动前的花材存库数据
  209. $purchaseItems = PurchaseItemClass::getAllByCondition(['orderSn' => $cg->orderSn], null, "productId");
  210. $productIds = ArrayHelper::getColumn($purchaseItems, 'productId'); //$productIds 是本次入库涉及的花材ID数组
  211. $oldStocks = [];
  212. foreach ($productIds as $productId) {
  213. $product = ProductClass::getById($productId, true);
  214. $oldStocks[$productId] = $product;
  215. }
  216. self::takeToPutIn($cg);
  217. $shop = ShopClass::getLockById($cg->shopId);
  218. if (empty($shop)) {
  219. util::fail('没有找到门店14');
  220. }
  221. $adminId = $shop->adminId;
  222. $mainId = $shop->mainId;
  223. PurchaseClass::rollbackProductStock($oldStocks, $shop, $adminId, $mainId, '系统');
  224. }
  225. //确认收货并入库 ssh 20231119
  226. public static function takeToPutIn($cg)
  227. {
  228. if ($cg->status != 3) {
  229. util::fail('订单不是待收货状态哦,编号:cg' . $cg->id);
  230. }
  231. $saleId = $cg->saleId ?? 0;
  232. $order = OrderClass::getById($saleId, true);
  233. if (empty($order)) {
  234. util::fail('没有找到订单');
  235. }
  236. if ($order->status != 3) {
  237. util::fail('订单不是待收货状态,订单状态:' . $order->status . ',订单ID:' . $saleId);
  238. }
  239. $order->status = 4;
  240. $order->save();
  241. //加库存 lqh 2021-05-10
  242. $orderSn = $cg->orderSn;
  243. $sjId = $cg->sjId ?? 0;
  244. $shopId = $cg->shopId ?? 0;
  245. $mainId = $cg->mainId ?? 0;
  246. $ghsName = $cg->ghsName ?? '';
  247. $purchaseItem = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, "*");
  248. foreach ($purchaseItem as $v) {
  249. //小单位库存不考虑入库 ssh 202310
  250. $itemNum = $v['itemNum'];
  251. if ($itemNum > 0) {
  252. $productId = $v['productId'];
  253. $stockInfo = ProductClass::addStockByItemNum($v['productId'], $itemNum);
  254. //记录库存流水
  255. $recordData = [];
  256. $recordData['sjId'] = $cg->sjId;
  257. $recordData['shopId'] = $cg->shopId;
  258. $recordData['mainId'] = $cg->mainId;
  259. $recordData['itemId'] = $v['itemId'] ?? 0;
  260. $recordData['itemNum'] = $itemNum;
  261. $recordData['oldStock'] = $stockInfo['oldStock'];
  262. $recordData['newStock'] = $stockInfo['newStock'];
  263. $recordData['productId'] = $v['productId'];
  264. $recordData['orderSn'] = $orderSn;
  265. $recordData['relateName'] = $cg->ghsName ?? '';
  266. StockRecordClass::addPurchaseOrderRecord($recordData);
  267. $product = ProductClass::getLockById($productId);
  268. if (empty($product)) {
  269. util::fail('没有找到花材哈');
  270. }
  271. //减少路上库存
  272. $onRecord = [];
  273. $onRecord['sjId'] = $sjId;
  274. $onRecord['shopId'] = $shopId;
  275. $onRecord['mainId'] = $mainId;
  276. $onRecord['orderSn'] = $orderSn;
  277. $onRecord['productId'] = $productId;
  278. $onRecord['itemId'] = $v['itemId'] ?? 0;
  279. $onRecord['relateName'] = $ghsName;
  280. $onRecord['itemNum'] = $itemNum;
  281. $oldOnStock = $product->onStock ?? 0;
  282. $onRecord['oldStock'] = $oldOnStock;
  283. $onRecord['newStock'] = bcsub($oldOnStock, $itemNum);
  284. $onRecord['ptStyle'] = 1;
  285. OnStockRecordClass::addInStockOrderRecord($onRecord);
  286. ProductClass::decreaseOnStockByItemNum($productId, $itemNum);
  287. $unitPrice = $v['xhUnitPrice'] ?? 0;
  288. $product->cost = $unitPrice;
  289. $product->save();
  290. $ptItemId = $product->itemId ?? 0;
  291. $mainId = $product->mainId ?? 0;
  292. $staffId = $cg->shopAdminId ?? 0;
  293. $staffName = $cg->shopAdminName ?? '';
  294. //成本变动记录
  295. $changeData = [
  296. 'ptStyle' => 2,
  297. 'sjId' => 0,
  298. 'mainId' => $mainId,
  299. 'itemId' => $productId,
  300. 'ptItemId' => $ptItemId,
  301. 'cost' => $unitPrice,
  302. 'staffId' => $staffId,
  303. 'staffName' => $staffName,
  304. 'name' => $product->name ?? '',
  305. 'cover' => $product->cover ?? '',
  306. 'targetId' => $cg->id ?? 0,
  307. 'event' => '采购',
  308. ];
  309. CostChangeClass::addData($changeData);
  310. }
  311. }
  312. $cg->status = 4;
  313. $cg->stockChange = 1;
  314. $cg->save();
  315. }
  316. // 库存回滚为入库前的状态
  317. public static function rollbackProductStock($oldStocks, $shop, $adminId, $mainId, $staffName)
  318. {
  319. $itemInfo = [];
  320. foreach ($oldStocks as $productId => $product) {
  321. $ratio = $product->ratio;
  322. $formNum = ProductClass::formatStock($product->stock, $ratio); //花材的库存转换
  323. $itemInfo[] = [
  324. 'productId' => $productId,
  325. 'itemNum' => $product->stock, // 回滚为入库前的库存
  326. 'itemId' => $product->itemId,
  327. 'bigNum' => $formNum['bigNum'],
  328. 'smallNum' => $formNum['smallNum'],
  329. 'price' => $product->price,
  330. ];
  331. }
  332. $data = [
  333. 'sjId' => $shop->sjId,
  334. 'shopId' => $shop->id,
  335. 'adminId' => $adminId,
  336. 'mainId' => $mainId,
  337. 'staffName' => $staffName,
  338. 'itemInfo' => $itemInfo,
  339. 'pdType' => 'rollbackStock',
  340. 'remark' => '',
  341. ];
  342. \bizGhs\order\classes\CheckOrderClass::opOrder($data, false, false, false);
  343. }
  344. // 指定花材新增库存
  345. public static function increaseProductStock($itemDatas, $shop, $adminId, $mainId, $staffName)
  346. {
  347. $itemInfo = [];
  348. foreach ($itemDatas as $productId => $arr) {
  349. $addNum = $arr['addNum']; //新增的数值
  350. $product = $arr['product'];
  351. $ratio = $product->ratio;
  352. $newStock = bcadd($product->stock, $addNum, 2);
  353. $formNum = ProductClass::formatStock($newStock, $ratio); //花材的库存转换
  354. $itemInfo[] = [
  355. 'productId' => $productId,
  356. 'itemNum' => $newStock, // 新库存数
  357. 'itemId' => $product->itemId,
  358. 'bigNum' => $formNum['bigNum'],
  359. 'smallNum' => $formNum['smallNum'],
  360. 'price' => $product->price,
  361. ];
  362. }
  363. $data = [
  364. 'sjId' => $shop->sjId,
  365. 'shopId' => $shop->id,
  366. 'adminId' => $adminId,
  367. 'mainId' => $mainId,
  368. 'staffName' => $staffName,
  369. 'itemInfo' => $itemInfo,
  370. 'pdType' => 'rollbackStock',
  371. 'remark' => '',
  372. ];
  373. \bizGhs\order\classes\CheckOrderClass::opOrder($data, false, false, false);
  374. }
  375. public static function notSameCity($shop, $ghsShop)
  376. {
  377. return true;
  378. $shopLat = $shop->lat ?? '';
  379. $shopLong = $shop->long ?? '';
  380. if (empty($shopLat) || empty($shopLong)) {
  381. util::fail('请完善门店地址');
  382. }
  383. $ghsShopLat = $ghsShop->lat ?? '';
  384. $ghsShopLong = $ghsShop->long ?? '';
  385. $distance = mapUtil::calculateDistance($shopLong, $shopLat, $ghsShopLong, $ghsShopLat);
  386. $formatDistance = ceil($distance / 1000);
  387. if ($formatDistance > 150) {
  388. return false;
  389. }
  390. return true;
  391. }
  392. //计算距离和运费【另外还有个地方要同步修改,关键词calc_freight_distance】 ssh 20221003
  393. public static function getDistanceFee($shop, $ghsShop, $weight, $custom)
  394. {
  395. $ability = ShopClass::hasIntraCity($ghsShop);
  396. $openIntraCity = $ability['openIntraCity'] ?? 0;
  397. if ($openIntraCity == 0) {
  398. //没有开启同城配送能力,不计算运费和距离
  399. return ['distance' => 0, 'showDistance' => 0, 'fee' => 0];
  400. }
  401. $shopLat = $shop->lat ?? '';
  402. $shopLong = $shop->long ?? '';
  403. if (empty($shopLat) || empty($shopLong)) {
  404. util::fail('请完善你的收花地址');
  405. }
  406. $address = $shop->address ?? '';
  407. if (empty($address)) {
  408. util::fail('请完善收花地址');
  409. }
  410. if ($weight <= 0) {
  411. util::fail('花材没有重量');
  412. }
  413. $wxStoreId = $ability['wxStoreId'] ?? '';
  414. $packageNum = 1;
  415. $price = 300;
  416. $cargo = [
  417. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  418. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  419. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  420. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  421. 'cargo_num' => $packageNum
  422. ];
  423. $customName = $custom->name ?? '';
  424. if (empty($customName)) {
  425. util::fail('客户名称是空的');
  426. }
  427. $customMobile = $custom->mobile ?? '';
  428. if (empty($customMobile)) {
  429. util::fail('客户手机缺失');
  430. }
  431. //根据环境变量判断是否使用沙盒环境
  432. // $useSandBox = getenv('YII_ENV') == 'production' ? 0 : 1;
  433. $orderData = [
  434. 'wx_store_id' => $wxStoreId,
  435. 'user_name' => $customName,
  436. 'user_phone' => $customMobile,
  437. 'user_lng' => $shopLong,
  438. 'user_lat' => $shopLat,
  439. 'user_address' => $address,
  440. 'cargo' => $cargo,
  441. // 'use_sandbox' => $useSandBox,//正式环境不能传这个参数,会报错
  442. ];
  443. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  444. $result = IntraCityExpress::preAddOrder($orderData);
  445. if ($result['errcode'] !== 0) {
  446. $errMsg = $result['errmsg'] ?? '';
  447. noticeUtil::push('运费查询失败原因:' . $errMsg . '参数:' . $result['errcode'], '15280215347');
  448. util::fail('运费查询失败,编号1160');
  449. }
  450. $distance = $result['distance'] ?? 0;
  451. $showDistance = sprintf("%.1f", ($distance / 1000));
  452. $fee = $result['est_fee'] ?? 0;
  453. $totalFee = sprintf("%.1f", ($fee / 100));
  454. //noticeUtil::push("批发订单,获取运费:{$totalFee} 重量:{$weight} 距离:{$showDistance} 客户名:{$customMobile} 手机号 {$customMobile} 经纬 {$shopLong} {$shopLat} 金额:{$price} 数量:{$packageNum}", '15280215347');
  455. return ['distance' => $distance, 'showDistance' => $showDistance, 'fee' => $totalFee];
  456. }
  457. //到货之后 ssh 20220321
  458. public static function arrival($cg, $data)
  459. {
  460. if ($cg->stockChange == 1) {
  461. util::fail('您已操作过了');
  462. }
  463. $sendCost = isset($data['sendCost']) && is_numeric($data['sendCost']) ? $data['sendCost'] : 0;
  464. $packCost = isset($data['packCost']) && is_numeric($data['packCost']) ? $data['packCost'] : 0;
  465. $cg->sendCost = $sendCost;
  466. $cg->packCost = $packCost;
  467. $cg->save();
  468. $sjId = $data['sjId'] ?? 0;
  469. $shopId = $data['shopId'] ?? 0;
  470. //product [{"productId":"3674","num":0,"price":1}]
  471. $product = $data['product'] ?? '';
  472. if (empty($product)) {
  473. util::fail('请填写成本价和到货数量');
  474. }
  475. $ghsName = $cg->ghsName ?? '';
  476. $orderSn = $cg->orderSn ?? '';
  477. $list = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  478. if (empty($list)) {
  479. util::fail('没有找到花材哦');
  480. }
  481. $weight = 0;
  482. $itemPrice = 0;
  483. foreach ($list as $key => $val) {
  484. $productId = $val->productId ?? 0;
  485. if (isset($product[$productId]) == false) {
  486. util::fail('没有找到对应采购花材');
  487. }
  488. $num = $product[$productId]['num'] ?? 0;
  489. $price = $product[$productId]['price'] ?? 0;
  490. if ($price <= 0) {
  491. util::fail('花材金额需要大于0');
  492. }
  493. $totalPrice = bcmul($num, $price, 2);
  494. $itemPrice = bcadd($itemPrice, $totalPrice, 2);
  495. $val->price = $price;
  496. $val->itemNum = $num;
  497. $val->preTotalPrice = $totalPrice;
  498. $val->totalPrice = $totalPrice;
  499. $val->xhNum = $num;
  500. $val->xhUnitPrice = $price;
  501. $val->xhPrice = $totalPrice;
  502. $val->save();
  503. $unitWeight = $val->unitWeight ?? 0;
  504. $currentWeight = bcmul($num, $unitWeight, 2);
  505. $weight = bcadd($weight, $currentWeight, 2);
  506. $unitType = $val->xhUnitType ?? 0;
  507. $bigNum = 0;
  508. $smallNum = 0;
  509. if ($unitType == dict::getDict('unitType', 'big')) {
  510. $bigNum = $num;
  511. } else {
  512. $smallNum = $num;
  513. }
  514. //增加库存
  515. $option = ['relateName' => $ghsName];
  516. StockClass::purchaseItem($orderSn, $sjId, $shopId, $productId, $bigNum, $smallNum, $option);
  517. }
  518. $cg->itemPrice = $itemPrice;
  519. $sendCost = $cg->sendCost ?? 0;
  520. $currentPrice = bcadd($itemPrice, $sendCost, 2);
  521. $packCost = $cg->packCost ?? 0;
  522. $currentPrice = bcadd($currentPrice, $packCost, 2);
  523. $kiloFee = $data['kiloFee'] ?? 0;
  524. $miniKilo = $data['miniKilo'] ?? 0;
  525. $calcWeight = $weight > $miniKilo ? $weight : $miniKilo;
  526. $allKiloFee = bcmul($calcWeight, $kiloFee, 2);
  527. $currentPrice = bcadd($currentPrice, $allKiloFee, 2);
  528. $cg->prePrice = $currentPrice;
  529. $cg->orderPrice = $currentPrice;
  530. $cg->actPrice = $currentPrice;
  531. $cg->realPrice = $currentPrice;
  532. $cg->stockChange = 1;
  533. $cg->save();
  534. $mainId = $cg->mainId ?? 0;
  535. $sjId = $cg->sjId ?? 0;
  536. $shopId = $cg->shopId ?? 0;
  537. $cgId = $cg->id ?? 0;
  538. $saleRefundId = $data['saleRefundId'] ?? 0;
  539. $shop = ShopClass::getLockById($shopId);
  540. if (empty($shop)) {
  541. util::fail('没有找到零售店的门店');
  542. }
  543. $main = MainClass::getLockById($mainId);
  544. if (empty($main)) {
  545. util::fail('没有main信息12');
  546. }
  547. $main->cgUnSend -= 1;
  548. $main->cgFinish += 1;
  549. $main->save();
  550. $cgRefund = null;
  551. $bookPrice = $cg->bookPrice ?? 0;
  552. if ($bookPrice == $currentPrice) {
  553. return ['refund' => $cgRefund];
  554. } elseif ($bookPrice > $currentPrice) {
  555. //退款
  556. $refundPrice = bcsub($bookPrice, $currentPrice, 2);
  557. $book = 1;
  558. $refundOrderSn = orderSn::getCgRefundSn();
  559. $refundType = CgRefundClass::REFUND_TYPE_MONEY;
  560. $refundData = [
  561. 'book' => $book,
  562. 'mainId' => $mainId,
  563. 'orderSn' => $refundOrderSn,
  564. 'cgId' => $cgId,
  565. 'status' => CgRefundClass::STATUS_COMPLETE,
  566. 'shopAdminId' => 0,
  567. 'shopAdminName' => '',
  568. 'refundType' => $refundType,
  569. 'refundPrice' => $refundPrice,
  570. 'saleRefundId' => $saleRefundId,
  571. 'sjId' => $sjId,
  572. 'shopId' => $shopId,
  573. ];
  574. $cgRefund = CgRefundClass::add($refundData, true);
  575. //门店收入增加
  576. $currentTotalIncome = bcadd($main->totalIncome, $refundPrice, 2);
  577. $main->totalIncome = $currentTotalIncome;
  578. $main->save();
  579. //供货商退款,向供货商采购总金额减少
  580. StatCgClass::replace($main, $shop, $refundPrice, 0, false);
  581. //供货商退款,按供货商分别采购的金额减少
  582. StatCgGhsClass::hdCgGhsReplace(false, $cg, $refundPrice, 0);
  583. $currentType = dict::getDict('capitalType', 'hdBookRefund', 'id');
  584. $sjId = $cg->sjId ?? 0;
  585. $shopId = $cg->shopId ?? 0;
  586. $event = "预订单{$orderSn}多退少补({$ghsName})";
  587. $capitalData = [
  588. 'capitalType' => $currentType,
  589. 'io' => 1,
  590. 'totalIncome' => $currentTotalIncome,
  591. 'payWay' => 0,
  592. 'amount' => $refundPrice,
  593. 'sjId' => $sjId,
  594. 'shopId' => $shopId,
  595. 'event' => $event,
  596. 'mainId' => $mainId,
  597. ];
  598. ShopCapitalClass::addCapital($capitalData);
  599. //收入统计
  600. StatIncomeClass::updateOrInsert($main, $shop, $refundPrice);
  601. $ghsId = $cg->ghsId ?? 0;
  602. $ghs = GhsClass::getLockById($ghsId);
  603. if (empty($ghs)) {
  604. util::fail('没有找到供货商');
  605. }
  606. $ghsShopId = $ghs->shopId ?? 0;
  607. $ghsShop = ShopClass::getById($ghsShopId, true);
  608. if (empty($ghsShop)) {
  609. util::fail('没有找到供货商的门店');
  610. }
  611. $refundFee = bcmul($refundPrice, 100);
  612. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  613. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  614. $params = [
  615. 'appid' => 'OP00002119',
  616. 'serial_no' => '018b08cfddbd',
  617. 'merchant_no' => $ghsShop->lklSjNo,
  618. 'term_no' => $ghsShop->lklScanTermNo,
  619. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  620. 'lklCertificatePath' => $lklCertificatePath,
  621. ];
  622. $laResource = new Lakala($params);
  623. $refundReason = '';
  624. $aliParams = [
  625. 'refundSn' => $refundOrderSn,
  626. 'orderSn' => $orderSn,
  627. 'refundAmount' => $refundFee,
  628. 'refundReason' => $refundReason,
  629. ];
  630. $response = $laResource->refund($aliParams);
  631. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  632. $errMsg = $response['msg'] ?? '';
  633. noticeUtil::push('退款失败了哦!请注意:' . $errMsg . ' 金额:' . $refundFee, '15280215347');
  634. util::fail('退款失败');
  635. }
  636. $refundTradeNo = isset($response['resp_data']['trade_no']) ? $response['resp_data']['trade_no'] : '';
  637. $cgRefund->thirdRefundNo = $refundTradeNo;
  638. $cgRefund->save();
  639. $cg->refundPrice = $refundPrice;
  640. $cg->tkPrice = bcadd($cg->tkPrice, $refundPrice, 2);
  641. $cg->refund = self::REFUND_YES;
  642. $cg->refundLog = 1;
  643. $cg->save();
  644. } else {
  645. //欠款
  646. $currentDebt = bcsub($currentPrice, $bookPrice, 2);
  647. $cg->debtPrice = $currentDebt;
  648. $cg->remainDebtPrice = $currentDebt;
  649. $cg->debt = PurchaseClass::DEBT_YES;
  650. $cg->save();
  651. $payWay = dict::getDict('payWay', 'debtPay');
  652. $ghsId = $cg->ghsId ?? 0;
  653. $ghs = GhsClass::getLockById($ghsId);
  654. if (empty($ghs)) {
  655. util::fail('没有找到供货商');
  656. }
  657. \bizHd\ghs\classes\GhsClass::cgDebtAmountAdd($ghs, $cg, true);
  658. //支出统计
  659. StatOutClass::updateOrInsert($main, $shop, $currentDebt);
  660. //支出流水
  661. $capitalType = dict::getDict('capitalType', 'hdBookFinalPay', 'id');
  662. $sjId = $cg->sjId ?? 0;
  663. $shopId = $cg->shopId ?? 0;
  664. $currentExpend = bcadd($main->totalExpend, $currentDebt, 2);
  665. $main->totalExpend = $currentExpend;
  666. $main->save();
  667. $event = "预订单{$orderSn}补尾款欠款";
  668. $capitalData = [
  669. 'capitalType' => $capitalType,
  670. 'io' => 0,
  671. 'totalExpend' => $currentExpend,
  672. 'payWay' => $payWay,
  673. 'amount' => $currentDebt,
  674. 'sjId' => $sjId,
  675. 'shopId' => $shopId,
  676. 'event' => $event,
  677. 'mainId' => $mainId,
  678. ];
  679. ShopCapitalClass::addCapital($capitalData);
  680. //补款给供货商,采购总金额增加
  681. StatCgClass::replace($main, $shop, $currentDebt, 0, true);
  682. //补款给供货商,按供货商分别统计采购量增加
  683. StatCgGhsClass::hdCgGhsReplace(true, $cg, $currentDebt, 0);
  684. }
  685. return ['refund' => $cgRefund];
  686. }
  687. //添加采购 ssh 2021.1.18
  688. public static function addPurchase($data, $ghs)
  689. {
  690. $shopId = $data['shopId'] ?? 0;
  691. $sjId = $data['sjId'] ?? 0;
  692. $mainId = $data['mainId'] ?? 0;
  693. $ghsId = $data['ghsId'] ?? 0;
  694. $book = $data['book'] ?? 0;
  695. $shopAdminId = $data['shopAdminId'] ?? 0;
  696. $customId = $data['customId'] ?? 0;
  697. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'ghsId' => $ghsId, 'customId' => $customId];
  698. $orderSn = orderSn::getPurchaseSn($snData);
  699. $data['orderSn'] = $orderSn;
  700. $prePrice = 0;
  701. $live = $ghs['live'] ?? 1;
  702. $sendTimeWant = !empty($data['sendTimeWant']) ? $data['sendTimeWant'] : date("Y-m-d");
  703. if ($sendTimeWant < date("Y-m-d")) {
  704. util::fail('您选了过去时间');
  705. }
  706. $data['sendTimeWant'] = $sendTimeWant;
  707. if (empty($data['product'])) {
  708. util::fail('请选择花材17');
  709. }
  710. $productList = $data['product'];
  711. $productList = self::mergeItemInfo($productList);
  712. $data['kindNum'] = count($productList); //多少种花材
  713. //传过来的是供货商的productId,需要转换为零售端的productId
  714. //数据格式 [{"productId":"113","bigNum":1,"smallNum":0,"classId":"-2","hdProductId":1}]
  715. if ($live == 1) {
  716. //花店真实向批发店采购花材,因为拿的供货商的ID,所以需要转化花店的id
  717. $productList = ProductClass::toggleProductList($productList, $shopId, $sjId, $mainId, $ghs);
  718. $ghsProductData = self::getProductMapData($productList, "ghsProductId");
  719. } else {
  720. //虚拟采购用的自己的ID所以不需要转化
  721. $ghsProductData = [];
  722. }
  723. $hdProductData = self::getProductMapData($productList, "productId");
  724. $giveLevel = $ghs['giveLevel'] ?? 0;
  725. $priceMap = CustomClass::$levelPriceKeyMap;
  726. //这个参数应该是要作废的,但下面加的参数是有用的,多处要同步修改,关键词 abandon_add_price_map ,ssh 20260116
  727. $addPriceMap = CustomClass::$levelAddPriceKeyMap;
  728. //但这边加的参数是有用的,给指定客户涨价的
  729. $addPriceMap['risePercent'] = $ghs['risePercent'] ?? 0;
  730. //累计满减
  731. $totalReachDiscount = 0;
  732. //计算价格= 各个productId的price*num(bigNum,smallNum) + sendCost(配送费)
  733. $bigNum = 0; //总共多少扎
  734. $smallNum = 0; //总共多少支
  735. $totalWeight = 0;
  736. foreach ($productList as $key => $product) {
  737. $currentBigNum = $product['bigNum'] ?? 0;
  738. $currentSmallNum = $product['smallNum'] ?? 0;
  739. $bigNum += $product['bigNum'] ?? 0;
  740. $smallNum += $product['smallNum'] ?? 0;
  741. $productList[$key]['orderSn'] = $orderSn;
  742. if ($live == 1) {
  743. $ghsProductId = $product['ghsProductId'];
  744. $hdProductId = $product['productId'];
  745. } else {
  746. $hdProductId = $product['productId'] ?? 0;
  747. $ghsProductId = 0;
  748. }
  749. $unitWeight = $hdProductData[$hdProductId]['weight'] ?? 0;
  750. $variety = $hdProductData[$hdProductId]['variety'] ?? 0;
  751. $ratio = $hdProductData[$hdProductId]['ratio'] ?? 0;
  752. $ratioType = $hdProductData[$hdProductId]['ratioType'] ?? 0;
  753. $itemId = $hdProductData[$hdProductId]['itemId'] ?? 0;
  754. $rank = $hdProductData[$hdProductId]['rank'] ?? 'B';
  755. $stock = $hdProductData[$hdProductId]['stock'] ?? 0;
  756. $kind = $hdProductData[$hdProductId]['kind'] ?? 0;
  757. $stockFormat = ProductClass::formatStock($stock, $ratio);
  758. $itemNum = ProductClass::mergeItemNum($product['bigNum'], $product['smallNum'], $ratio);
  759. $weight = $hdProductData[$hdProductId]['weight'] ?? 0;
  760. $currentWeight = bcmul($weight, $itemNum, 2);
  761. $totalWeight = bcadd($currentWeight, $totalWeight, 2);
  762. //1、供货商开单改价 2、花店向虚拟供货商采购录入价格
  763. $userPrice = isset($product['userPrice']) && $product['userPrice'] > 0 ? $product['userPrice'] : 0;
  764. $currentGhsProduct = $ghsProductData[$ghsProductId] ?? [];
  765. if (!empty($currentGhsProduct)) {
  766. //用批发店的花材名称
  767. $itemName = $currentGhsProduct['name'] ?? '';
  768. $cover = $currentGhsProduct['cover'] ?? '';
  769. //如果零售店自己下预订单,预付0.1元,有两个地方要同步修改,搜索关键词 pre0.1
  770. if ($book == 1 && $shopAdminId > 0) {
  771. $price = 0.1;
  772. } else {
  773. //用批发店花材的价格
  774. $price = ProductClass::getFinalPrice($currentGhsProduct, $giveLevel, $priceMap, $addPriceMap, $userPrice, $itemNum);
  775. }
  776. $thisPrice = $price;
  777. $reachNum = $currentGhsProduct['reachNum'] ?? 0;
  778. if ($reachNum > 0) {
  779. if ($itemNum >= $reachNum) {
  780. $reachNumDiscount = $currentGhsProduct['reachNumDiscount'] ?? 0;
  781. $currentReachDiscount = bcmul($reachNumDiscount, $itemNum, 2);
  782. $totalReachDiscount = bcadd($totalReachDiscount, $currentReachDiscount, 2);
  783. }
  784. }
  785. } else {
  786. $currentHdProduct = $hdProductData[$hdProductId] ?? [];
  787. if (empty($currentHdProduct)) {
  788. util::fail('花材有问题哦');
  789. }
  790. $itemName = $currentHdProduct['name'] ?? '';
  791. $cover = $currentHdProduct['cover'] ?? '';
  792. $price = $userPrice;
  793. $thisPrice = $userPrice;
  794. }
  795. if ($currentSmallNum > 0) {
  796. $productTotalPrice = bcmul($currentSmallNum, $price, 2);
  797. } else {
  798. $productTotalPrice = bcmul($currentBigNum, $price, 2);
  799. }
  800. $itemInfo = [
  801. 'itemName' => $itemName,
  802. 'itemCover' => $cover,
  803. 'bigNum' => $product['bigNum'] ?? 0,
  804. 'smallNum' => $product['smallNum'] ?? 0,
  805. 'bigNumStock' => $stockFormat['bigNum'],
  806. 'smallNumStock' => $stockFormat['smallNum'],
  807. 'itemUnit' => $ratio ? 2 : 1,
  808. 'ratio' => $ratio,
  809. 'rank' => $rank,
  810. 'bigUnit' => $hdProductData[$hdProductId]['bigUnit'],
  811. 'smallUnit' => $hdProductData[$hdProductId]['smallUnit'],
  812. ];
  813. if ($itemNum <= 0) {
  814. util::fail($itemName . ' 数量要大于零');
  815. }
  816. $productList[$key]['itemInfo'] = json_encode($itemInfo);
  817. $productList[$key]['variety'] = $variety;
  818. $productList[$key]['itemId'] = $itemId;
  819. $productList[$key]['preItemNum'] = $itemNum;
  820. $productList[$key]['itemNum'] = $itemNum;
  821. $productList[$key]['bigNum'] = $product['bigNum'] ?? 0;
  822. $productList[$key]['smallNum'] = $product['smallNum'] ?? 0;
  823. $productList[$key]['price'] = $thisPrice;
  824. $productList[$key]['ratio'] = $ratio;
  825. $productList[$key]['ratioType'] = $ratioType;
  826. $productList[$key]['unitWeight'] = $unitWeight;
  827. $productList[$key]['totalPrice'] = $productTotalPrice;
  828. $productList[$key]['preTotalPrice'] = $productTotalPrice;
  829. $productList[$key]['productId'] = $hdProductId;
  830. $productList[$key]['ghsProductId'] = $ghsProductId;
  831. $productList[$key]['smallPrice'] = $price;
  832. $productList[$key]['mainId'] = $mainId;
  833. $productList[$key]['ghsId'] = $ghsId;
  834. $productList[$key]['name'] = $itemName;
  835. $productList[$key]['cover'] = $cover;
  836. $productList[$key]['kind'] = $kind;
  837. $currentBigUnit = $hdProductData[$hdProductId]['bigUnit'] ?? '';
  838. $currentSmallUnit = $hdProductData[$hdProductId]['smallUnit'] ?? '';
  839. if ($currentBigNum > 0) {
  840. $xhNum = $currentBigNum;
  841. $xhUnitName = $currentBigUnit;
  842. $xhUnitType = dict::getDict('unitType', 'big');
  843. } else {
  844. $xhNum = $currentSmallNum;
  845. $xhUnitName = $currentSmallUnit;
  846. $xhUnitType = dict::getDict('unitType', 'small');
  847. }
  848. $itemPrice = $price;
  849. $price = bcmul($itemPrice, $xhNum, 2);
  850. //客户下单时会出现同时选了扎和支,很奇怪,前端没有找到原因,后端限制
  851. if ($currentBigNum > 0 && $currentSmallNum > 0) {
  852. util::fail($itemName . " {$currentBigUnit}和{$currentSmallUnit}只能选一种");
  853. }
  854. $productList[$key]['xhNum'] = $xhNum;
  855. $productList[$key]['xhUnitName'] = $xhUnitName;
  856. $productList[$key]['xhUnitType'] = $xhUnitType;
  857. $productList[$key]['xhUnitPrice'] = $itemPrice;
  858. $productList[$key]['xhPrice'] = $price;
  859. $productList[$key]['xhPreNum'] = $xhNum;
  860. $productList[$key]['xhPreUnitName'] = $xhUnitName;
  861. $productList[$key]['xhPreUnitType'] = $xhUnitType;
  862. $productList[$key]['xhPreUnitPrice'] = $itemPrice;
  863. $productList[$key]['xhPrePrice'] = $price;
  864. $prePrice = bcadd($prePrice, $productTotalPrice, 2);
  865. }
  866. $data['itemPrice'] = $prePrice;
  867. $sendCost = $data['sendCost'] ?? 0.00;
  868. $prePrice = bcadd($prePrice, $sendCost, 2);
  869. $packCost = $data['packCost'] ?? 0;
  870. $prePrice = bcadd($prePrice, $packCost, 2);
  871. $data['weight'] = $totalWeight;
  872. //预订单需要增加服务费
  873. if ($book == 1) {
  874. $kiloFee = $ghs['kiloFee'] ?? 0;
  875. $miniKilo = $ghs['miniKilo'] ?? 0;
  876. $calcWeight = max($totalWeight, $miniKilo);
  877. $allKiloFee = bcmul($calcWeight, $kiloFee, 2);
  878. $prePrice = bcadd($prePrice, $allKiloFee, 2);
  879. $data['allKiloFee'] = $allKiloFee;
  880. $data['kiloFee'] = $kiloFee;
  881. $data['miniKilo'] = $miniKilo;
  882. $data['stockChange'] = 0;
  883. }
  884. $actPrice = $prePrice;
  885. if (isset($data['modifyPrice'])) {
  886. $modifyPrice = $data['modifyPrice'];
  887. if ($modifyPrice < $prePrice) {
  888. //优惠金额
  889. $data['discountAmount'] = bcsub($prePrice, $modifyPrice, 2);
  890. $data['discountType'] = dict::getDict('discountType', 'discount');
  891. }
  892. if ($modifyPrice > $prePrice) {
  893. //人工和资材费用
  894. $data['labourCost'] = bcsub($modifyPrice, $prePrice, 2);
  895. }
  896. $actPrice = $modifyPrice;
  897. if ($book == 1) {
  898. $actPrice = 0;
  899. }
  900. } else {
  901. //客户自己下单才有整单满减,门店帮忙开单没有,,多个地方要同步修改,关键词 meet_amount_num_reduce
  902. if ($book == 0) {
  903. $ghsShopId = $ghs['shopId'] ?? 0;
  904. $ghsShop = ShopClass::getById($ghsShopId, true);
  905. if (!empty($ghsShop)) {
  906. $meetNum = $ghsShop->meetNum ?? 0;
  907. $meetAmount = $ghsShop->meetAmount ?? 0;
  908. $cutStyle = $ghsShop->cutStyle ?? 0;
  909. $cutOption = $ghsShop->cutAmount ?? 0;
  910. if ($cutStyle == 0) {
  911. $cutAmount = $cutOption;
  912. } else {
  913. $miniOption = bcsub(1, $cutOption, 2);
  914. $cutAmount = bcmul($actPrice, $miniOption, 2);
  915. }
  916. if ($cutAmount > 0 && $meetNum > 0 && $meetAmount > 0) {
  917. if ($bigNum >= $meetNum && $data['itemPrice'] >= $meetAmount) {
  918. if ($cutAmount < $actPrice) {
  919. $actPrice = bcsub($actPrice, $cutAmount, 2);
  920. $data['orderReachDiscountPrice'] = $cutAmount;
  921. } else {
  922. noticeUtil::push('订单金额不足满减金额,ghsShopId:' . $ghsShopId, '15280215347');
  923. }
  924. }
  925. }
  926. }
  927. }
  928. }
  929. //如果有设置指定客户涨价百分之几,然后又设置了涨价的幅度。【这个功能主要用于客户不收他运费,门店不赚钱,收他运费客户不乐意,所以把运费加到花材里】,多处同步修改,关键词 rise_percent_rang
  930. if (isset($data['itemPrice'])) {
  931. if (isset($data['orderReachDiscountPrice'])) {
  932. $originActPrice = bcadd($actPrice, $data['orderReachDiscountPrice'], 2);
  933. } else {
  934. $originActPrice = $actPrice;
  935. }
  936. if ($originActPrice >= $data['itemPrice']) {
  937. if (isset($ghs['risePercent']) && $ghs['risePercent'] > 0) {
  938. if (isset($ghs['riseRange']) && $ghs['riseRange'] > 0) {
  939. $risePercent = $ghs['risePercent'];
  940. $riseRange = $ghs['riseRange'];
  941. // 计算涨价金额:涨价后金额 * (涨价百分比 / (100 + 涨价百分比))
  942. $riseAmount = bcmul($data['itemPrice'], bcdiv($risePercent, bcadd(100, $risePercent, 0), 4), 2);
  943. if ($riseAmount > $riseRange) {
  944. //应该退回的金额
  945. $backAmount = bcsub($riseAmount, $riseRange, 2);
  946. $actPrice = bcsub($actPrice, $backAmount, 2);
  947. if (isset($data['orderReachDiscountPrice'])) {
  948. if ($data['orderReachDiscountPrice'] < $backAmount) {
  949. //前面整单满减的,就不减了,所以这里面加回来
  950. $actPrice = bcadd($actPrice, $data['orderReachDiscountPrice'], 2);
  951. //改成减多加钱里面的
  952. $data['orderReachDiscountPrice'] = $backAmount;
  953. }
  954. } else {
  955. $data['orderReachDiscountPrice'] = $backAmount;
  956. }
  957. }
  958. }
  959. }
  960. }
  961. }
  962. //这个字段记录每个花材满多少扎减掉的金额,并汇总金额,区别于整单满减的 $cutAmount。保存起来应该是在哪里有用,$totalReachDiscount在这边不影响actPrice,估计因为取花材的价格里::getFinalPrice()已经使用了优惠后的价格,有多处,关键词 reachDiscountPrice_explain ssh 20260116
  963. $data['reachDiscountPrice'] = $totalReachDiscount;
  964. $data['prePrice'] = $prePrice;
  965. $data['bookPrice'] = $actPrice;
  966. $data['orderPrice'] = $actPrice;
  967. $data['actPrice'] = $actPrice;
  968. $data['realPrice'] = $actPrice;
  969. $data['bigNum'] = $bigNum;
  970. $data['smallNum'] = $smallNum;
  971. $data['discount'] = 1;
  972. $data['status'] = self::STATUS_UN_PAY;
  973. //采购单有效期
  974. $currentTime = time();
  975. $validTime = dict::getDict('order_pay_has_time');
  976. $current = $currentTime + $validTime;
  977. $data['deadline'] = $data['deadline'] ?? date("Y-m-d H:i:s", $current);
  978. if ($book == 1) {
  979. $fiveTime = bcmul(86400, 5);
  980. $bookDeadline = bcadd($currentTime, $fiveTime);
  981. $data['deadline'] = date("Y-m-d H:i:s", $bookDeadline);
  982. }
  983. //采购单自动记为欠款单时间
  984. $localConfirmTime = dict::getDict('local_gys_kd_auto_set_debt_time');
  985. $currentSet = $currentTime + $localConfirmTime;
  986. $data['autoSetTime'] = $data['autoSetTime'] ?? date("Y-m-d H:i:s", $currentSet);
  987. //保存订单
  988. $respond = self::add($data, true);
  989. foreach ($productList as $productVal) {
  990. //增加采购单的花材
  991. $returnItem = PurchaseItemClass::add($productVal, true);
  992. $productId = $productVal['productId'];
  993. $unitPrice = $returnItem->price ?? 0;
  994. $currentId = $returnItem->id ?? 0;
  995. $currentPtItemId = $returnItem->itemId ?? 0;
  996. if (!empty($data['xj'][$currentPtItemId])) {
  997. $xjArr = $data['xj'][$currentPtItemId];
  998. if (is_array($xjArr)) {
  999. $ids = array_column($xjArr, 'id');
  1000. $sjInfo = XjClass::getByIds($ids, null, 'id');
  1001. $xjData = [];
  1002. foreach ($xjArr as $xjItem) {
  1003. $id = $xjItem['id'] ?? 0;
  1004. $num = $xjItem['num'] ?? 0;
  1005. $name = $sjInfo[$id]['name'] ?? '';
  1006. $cover = $sjInfo[$id]['cover'] ?? '';
  1007. $xjData[] = ['xjId' => $id, 'name' => $name, 'ptItemId' => $currentPtItemId,
  1008. 'num' => $num, 'price' => $unitPrice, 'itemId' => $currentId, 'cover' => $cover];
  1009. }
  1010. CgXjClass::batchAdd($xjData);
  1011. $returnItem->variety = 1;
  1012. $returnItem->save();
  1013. }
  1014. }
  1015. if (!empty($data['treeData'][$currentPtItemId])) {
  1016. $myTreeData = $data['treeData'][$currentPtItemId];
  1017. foreach($myTreeData as $treeItem) {
  1018. $treeNum = $treeItem['num'] ?? 0;
  1019. $treeParams = [
  1020. 'orderSn' => $orderSn,
  1021. 'num' => $treeNum,
  1022. 'productId' => $productId,
  1023. ];
  1024. CgTreeClass::add($treeParams);
  1025. $dishNum = count($myTreeData);
  1026. $returnItem->dishNum = $dishNum;
  1027. $returnItem->save();
  1028. }
  1029. }
  1030. }
  1031. $shop = ShopClass::getLockById($shopId);
  1032. if (empty($shop)) {
  1033. util::fail('没有找到门店59 ' . $shopId);
  1034. }
  1035. $mainId = $shop->mainId ?? 0;
  1036. $main = MainClass::getLockById($mainId);
  1037. if (empty($main)) {
  1038. util::fail('没有main信息13');
  1039. }
  1040. $main->totalPurchaseOrder += 1;
  1041. $main->cgUnPay += 1;
  1042. $main->save();
  1043. return $respond;
  1044. }
  1045. //添加采购 ssh 2021.1.18
  1046. public static function updatePurchase($purchase, $data)
  1047. {
  1048. util::fail('已删除');
  1049. }
  1050. //组合数据 ssh 2021.1.25
  1051. public static function groupPurchase($list, $showButton = false, $showProduct = false)
  1052. {
  1053. $ghsIds = array_unique(array_filter(array_column($list, 'ghsId')));
  1054. $ghsInfo = GhsClass::getGhsByIds($ghsIds);
  1055. $adminIds = array_unique(array_filter(array_column($list, 'adminId')));
  1056. $adminInfo = AdminClass::getAdminByIds($adminIds, null, 'id');
  1057. $time = time();
  1058. foreach ($list as $key => $val) {
  1059. //剩余支付时间
  1060. $remainPayTime = 0;
  1061. $deadline = $val['deadline'] ?? '';
  1062. if (!empty($deadline)) {
  1063. $deadTime = strtotime($deadline);
  1064. if (($deadTime - $time - 30) > 0) {
  1065. $remainPayTime = $deadTime - $time;
  1066. $remainPayTime = $remainPayTime - 30;
  1067. }
  1068. }
  1069. $list[$key]['remainPayTime'] = $remainPayTime;
  1070. $adminId = $val['adminId'] ?? 0;
  1071. $list[$key]['adminName'] = $adminInfo[$adminId]['name'] ?? '';
  1072. $ghsId = $val['ghsId'] ?? 0;
  1073. $list[$key]['supplierName'] = $ghsInfo[$ghsId]['name'] ?? '';
  1074. $list[$key]['supplierAvatar'] = $ghsInfo[$ghsId]['smallLogoUrl'] ?? '';
  1075. $list[$key]['supplierMobile'] = $ghsInfo[$ghsId]['mobile'] ?? '';
  1076. $list[$key]['supplierAddress'] = $ghsInfo[$ghsId]['address'] ?? '';
  1077. $list[$key]['debtAmount'] = $ghsInfo[$ghsId]['debtAmount'] ?? '';
  1078. //剩余欠款
  1079. $balance = $ghsInfo[$ghsId]['balance'] ?? 0;
  1080. $debtAmount = $ghsInfo[$ghsId]['debtAmount'] ?? 0;
  1081. $ghsSalt = $ghsInfo[$ghsId]['salt'] ?? '';
  1082. $remainDebtAmount = bcsub($debtAmount, $balance, 2);
  1083. $list[$key]['remainDebtAmount'] = floatval($remainDebtAmount);
  1084. $list[$key]['inMyGhsBalance'] = floatval($balance);
  1085. $list[$key]['ghsSalt'] = $ghsSalt;
  1086. $list[$key]['lat'] = $ghsInfo[$ghsId]['lat'] ?? '';
  1087. $list[$key]['long'] = $ghsInfo[$ghsId]['long'] ?? '';
  1088. $list[$key]['supplierId'] = $ghsInfo[$ghsId]['id'] ?? '';
  1089. if ($showButton) {
  1090. $list[$key]['buttonList'] = [
  1091. ['type' => 'pay', 'show' => 1, 'disable' => 1],
  1092. ['type' => 'debtPay', 'show' => 1, 'disable' => 0],
  1093. ];
  1094. }
  1095. $list[$key]['sendProgress'] = [];
  1096. if ($showProduct) {
  1097. $orderSn = $val['orderSn'];
  1098. $orderItem = PurchaseItemClass::getOrderItemDetail($orderSn);
  1099. $itemData = [];
  1100. $xjData = [];
  1101. if ($orderItem) {
  1102. foreach ($orderItem as $v) {
  1103. $info = json_decode($v['itemInfo'], true);
  1104. $tmp = $info;
  1105. unset($v['itemInfo']);
  1106. if (!isset($tmp['rank'])) {
  1107. $tmp['rank'] = 'B';
  1108. }
  1109. $tmp['name'] = $tmp['itemName'] ?? '';
  1110. $tmp = array_merge($tmp, $v);
  1111. $shortCover = $info['itemCover'] ?? '';
  1112. $tmp['cover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1113. if (isset($tmp['variety']) && $tmp['variety'] == 1) {
  1114. $currentItemId = $tmp['id'] ?? 0;
  1115. $xjList = CgXjClass::getAllByCondition(['itemId' => $currentItemId], null, '*');
  1116. if (!empty($xjList)) {
  1117. foreach ($xjList as $xjKey => $xj) {
  1118. $xjBase = $tmp;
  1119. $num = $xj['num'] ?? 0;
  1120. $name = $xj['name'] ?? '';
  1121. $cover = $xj['cover'] ?? '';
  1122. $price = $xj['price'] ?? '';
  1123. $totalPrice = bcmul($num, $price, 2);
  1124. if ($num > 0) {
  1125. $xjBase['cover'] = imgUtil::groupImg($cover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
  1126. $xjBase['name'] = $name;
  1127. $xjBase['itemNum'] = floatval($num);
  1128. $xjBase['bigNum'] = floatval($num);
  1129. $xjBase['smallNum'] = 0;
  1130. $xjBase['price'] = $price;
  1131. $xjBase['totalPrice'] = $totalPrice;
  1132. $xjBase['xhNum'] = floatval($num);
  1133. $xjAddList[] = $xjBase;
  1134. }
  1135. $xjData[] = $xjBase;
  1136. }
  1137. } else {
  1138. $itemData[] = $tmp;
  1139. }
  1140. } else {
  1141. $itemData[] = $tmp;
  1142. }
  1143. }
  1144. if (!empty($xjData)) {
  1145. $itemData = array_merge($itemData, $xjData);
  1146. }
  1147. }
  1148. $list[$key]['product'] = $itemData;
  1149. }
  1150. }
  1151. return $list;
  1152. }
  1153. //订单取消,变更状态,占用库存释放 ssh 2021.5.8
  1154. public static function cancel($id)
  1155. {
  1156. $purchase = PurchaseClass::getLockById($id);
  1157. $purchase->status = self::STATUS_CANCEL;
  1158. $purchase->cancelTime = date("Y-m-d H:i:s");
  1159. $purchase->save();
  1160. $shopId = $purchase->shopId;
  1161. $orderSn = $purchase->orderSn ?? '';
  1162. $shop = ShopClass::getLockById($shopId);
  1163. if (empty($shop)) {
  1164. util::fail('没有找到门店60');
  1165. }
  1166. $mainId = $shop->mainId ?? 0;
  1167. $main = MainClass::getLockById($mainId);
  1168. if (empty($main)) {
  1169. util::fail('没有main信息14');
  1170. }
  1171. $main->cgUnPay -= 1;
  1172. $main->cgCancel += 1;
  1173. $main->save();
  1174. $ghsId = $purchase->ghsId;
  1175. $ghs = GhsClass::getById($ghsId, true);
  1176. if (empty($ghs)) {
  1177. util::fail('没有找到供货商');
  1178. }
  1179. $ghsShopId = $ghs->shopId ?? 0;
  1180. $ghsShop = ShopClass::getById($ghsShopId, true);
  1181. if (empty($ghsShop)) {
  1182. util::fail('没有找到供货商门店');
  1183. }
  1184. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  1185. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  1186. $params = [
  1187. 'appid' => 'OP00002119',
  1188. 'serial_no' => '018b08cfddbd',
  1189. 'merchant_no' => $ghsShop->lklSjNo,
  1190. 'term_no' => $ghsShop->lklScanTermNo,
  1191. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  1192. 'lklCertificatePath' => $lklCertificatePath,
  1193. ];
  1194. $laResource = new Lakala($params);
  1195. $closeParams = ['orderSn' => $orderSn];
  1196. $response = $laResource->close($closeParams);
  1197. if (!isset($response['code']) || $response['code'] != 'BBS00000') {
  1198. $msg = $response['msg'] ?? '';
  1199. $code = $response['code'] ?? 0;
  1200. //主扫(手机上微信下单拉取微信支付)调用这个方法有效,如果收银机上扫客户收款码的,调用这个方法无效,具体说明看 https://o.lakala.com/#/home/document/detail?id=115 所以在这个取消方法,暂时不考虑关单成功与否 ssh 20250517
  1201. //noticeUtil::push('花店采购 ' . $orderSn . ' 关单没有成功哦' . $msg . ' ' . $code, '15280215347');
  1202. }
  1203. //收银台关单
  1204. $closeParams = ['orderSn' => $orderSn];
  1205. $response = $laResource->cashClose($closeParams);
  1206. if (!isset($response['code']) || $response['code'] != '000000') {
  1207. $msg = $response['msg'] ?? '';
  1208. $code = $response['code'] ?? 0;
  1209. //聚合收银台(APP发起的微信和支付支付)调用这个方法有效,说明 https://o.lakala.com/#/home/document/detail?id=722,其他情况调用无法,所以在这个取消方法,暂时不考虑关单成功与否 ssh 20250517
  1210. //noticeUtil::push('花店采购 ' . $orderSn . ' 收银台关单的提示:' . $msg . ' ' . $code, '15280215347');
  1211. }
  1212. return $purchase;
  1213. }
  1214. //采购统计2021-05-08
  1215. //采购数,采购金额统计(根据时间,今日,昨天,7天,30天)
  1216. public static function statOrderInfo($shopId, $statType)
  1217. {
  1218. $start = '';
  1219. $end = '';
  1220. switch ($statType) {
  1221. case "today":
  1222. $start = date('Y-m-d');
  1223. $end = $start;
  1224. break;
  1225. case "yesterday" :
  1226. $start = date('Y-m-d', strtotime("-1 day"));
  1227. $end = $start;
  1228. break;
  1229. case "seven":
  1230. $start = date('Y-m-d', strtotime("-6 day"));
  1231. $end = date('Y-m-d');
  1232. break;
  1233. case "thirty":
  1234. $start = date('Y-m-d', strtotime("-29 day"));
  1235. $end = date('Y-m-d');
  1236. break;
  1237. default:
  1238. }
  1239. $where = [];
  1240. $where['shopId'] = $shopId;
  1241. $where['addTime'] = ['between', [$start, $end]];
  1242. $res = self::getAllByCondition($where, null, "id,actPrice");
  1243. $totalAmount = 0;
  1244. $totalNum = count($res);
  1245. foreach ($res as $v) {
  1246. $totalAmount = bcadd($totalAmount, $v['actPrice'], 2);
  1247. }
  1248. return [
  1249. 'totalAmount' => $totalAmount,
  1250. 'totalNum' => $totalNum,
  1251. ];
  1252. }
  1253. //采购单完成 ssh 2021.5.15
  1254. public static function complete($purchase)
  1255. {
  1256. $purchase->status = self::STATUS_COMPLETE;
  1257. $purchase->save();
  1258. $shopId = $purchase->shopId;
  1259. $shop = ShopClass::getLockById($shopId);
  1260. if (empty($shop)) {
  1261. util::fail('没有找到门店61');
  1262. }
  1263. $mainId = $shop->mainId ?? 0;
  1264. $main = MainClass::getLockById($mainId);
  1265. if (empty($main)) {
  1266. util::fail('没有main信息15');
  1267. }
  1268. $main->cgSending -= 1;
  1269. $main->cgFinish += 1;
  1270. $main->save();
  1271. /********订单完成后加库存 lqh 2021-05-10*********/
  1272. $orderSn = $purchase->orderSn;
  1273. $purchaseItem = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, "*");
  1274. foreach ($purchaseItem as $v) {
  1275. $stockInfo = ProductClass::addStockByItemNum($v['productId'], $v['itemNum']);
  1276. //记录库存流水
  1277. $recordData = [];
  1278. $recordData['sjId'] = $purchase->sjId;
  1279. $recordData['shopId'] = $purchase->shopId;
  1280. $recordData['mainId'] = $purchase->mainId;
  1281. $recordData['itemId'] = $v['itemId'] ?? 0;
  1282. $recordData['itemNum'] = $v['itemNum'];
  1283. $recordData['oldStock'] = $stockInfo['oldStock'];
  1284. $recordData['newStock'] = $stockInfo['newStock'];
  1285. $recordData['productId'] = $v['productId'];
  1286. $recordData['orderSn'] = $orderSn;
  1287. StockRecordClass::addPurchaseOrderRecord($recordData);
  1288. }
  1289. }
  1290. //订单信息变更为配送中 ssh 2021.5.15
  1291. public static function sending($purchaseId)
  1292. {
  1293. $purchase = PurchaseClass::getById($purchaseId, true);
  1294. if (empty($purchase)) {
  1295. util::fail('没有采购单信息');
  1296. }
  1297. $purchase->status = PurchaseClass::STATUS_SENDING;
  1298. $purchase->save();
  1299. $shopId = $purchase->shopId;
  1300. $shop = ShopClass::getLockById($shopId);
  1301. if (empty($shop)) {
  1302. util::fail('没有找到门店62');
  1303. }
  1304. $shop->cgUnSend -= 1;
  1305. $shop->cgSending += 1;
  1306. $shop->save();
  1307. //自动完成订单时不需要通知
  1308. $noNeedWxNotice = isset(Yii::$app->params['noNeedWxNotice']) ? Yii::$app->params['noNeedWxNotice'] : 0;
  1309. if ($noNeedWxNotice == 0) {
  1310. WxMessageClass::cgOrderHasSend($shop, $purchase);
  1311. }
  1312. }
  1313. public static function valid($cg, $shopId)
  1314. {
  1315. if (isset($cg->shopId) == false || $cg->shopId != $shopId) {
  1316. util::fail('无法访问,编号1255');
  1317. }
  1318. }
  1319. }