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\stat\classes\StatCgClass;
  8. use biz\stat\classes\StatCgGhsClass;
  9. use biz\stat\classes\StatOutClass;
  10. use biz\stock\classes\StockClass;
  11. use biz\wx\classes\WxMessageClass;
  12. use bizGhs\admin\classes\AdminClass;
  13. use bizGhs\custom\classes\CustomClass;
  14. use bizGhs\item\classes\CostChangeClass;
  15. use bizGhs\order\classes\OrderClass;
  16. use bizGhs\order\traits\OrderTrait;
  17. use bizGhs\product\classes\ProductClass;
  18. use bizGhs\stock\classes\OnStockRecordClass;
  19. use bizGhs\stock\classes\StockRecordClass;
  20. use bizHd\cg\classes\CgRefundClass;
  21. use bizHd\cg\classes\CgTreeClass;
  22. use bizHd\cg\classes\CgXjClass;
  23. use bizHd\shop\classes\MainClass;
  24. use bizHd\stat\classes\StatIncomeClass;
  25. use common\components\dict;
  26. use common\components\imgUtil;
  27. use common\components\IntraCityExpress;
  28. use common\components\mapUtil;
  29. use common\components\noticeUtil;
  30. use common\components\orderSn;
  31. use common\components\util;
  32. use bizHd\base\classes\BaseClass;
  33. use common\components\lakala\Lakala;
  34. use Yii;
  35. use yii\helpers\ArrayHelper;
  36. class PurchaseClass extends BaseClass
  37. {
  38. use OrderTrait;
  39. public static $baseFile = '\bizHd\purchase\models\Purchase';
  40. //订单状态 1待付款,待确认,2待配送,3配送中,4已完成,5取消,失败
  41. const STATUS_UN_PAY = 1;
  42. const STATUS_UN_SEND = 2;
  43. const STATUS_SENDING = 3;
  44. const STATUS_COMPLETE = 4;
  45. const STATUS_CANCEL = 5;
  46. //未知
  47. const DEBT_UNKNOWN = 0;
  48. //欠款
  49. const DEBT_YES = 1;
  50. //没有欠款
  51. const DEBT_NO = 2;
  52. //配送,这里的数值是错的,请参考dict.php的数值
  53. const GET_TYPE_SEND = 1;
  54. //自取,这里的数值是错的,请参考dict.php的数值
  55. const GET_TYPE_SELF_GET = 2;
  56. const REFUND_NO = 1;
  57. const REFUND_YES = 2;
  58. //获取打包费
  59. public static function getKmPackCost($mainId)
  60. {
  61. $cost = dict::getDict('kmPackCost');
  62. if (getenv('YII_ENV') == 'production') {
  63. //云漫梦金鹏 徐记花卉 康多鲜 旭海 打包费0元
  64. if (in_array($mainId, [10728, 20528, 10866, 38657, 41121])) {
  65. $cost = dict::getDict('kmPackCost2');
  66. }
  67. //花瀚鲜花供应链
  68. if (in_array($mainId, [50, 14499])) {
  69. $cost = dict::getDict('kmPackCost3');
  70. }
  71. } else {
  72. }
  73. return $cost;
  74. }
  75. //订单发货主方法 ssh 20231119
  76. public static function orderSend($cg, $params, $allowRepeat)
  77. {
  78. $respond = self::orderFh($cg, $params, $allowRepeat);
  79. $orderId = $cg->saleId ?? 0;
  80. $orderInfo = OrderClass::getById($orderId, true);
  81. if (empty($orderInfo)) {
  82. util::fail('没有找到销售单信息');
  83. }
  84. OrderClass::orderFh($orderInfo, $params, $allowRepeat);
  85. return $respond;
  86. }
  87. public static function cancelFh($cg, $params)
  88. {
  89. $cg->status = 2;
  90. $cg->save();
  91. $orderSn = $cg->orderSn ?? '';
  92. $itemList = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  93. if (!empty($itemList)) {
  94. $sjId = $cg->sjId ?? 0;
  95. $shopId = $cg->shopId ?? 0;
  96. $mainId = $cg->mainId ?? 0;
  97. $ghsName = $cg->ghsName ?? '';
  98. foreach ($itemList as $key => $val) {
  99. $productId = $val->productId ?? 0;
  100. $itemId = $val->itemId ?? 0;
  101. $num = $val->xhNum ?? 0;
  102. $product = ProductClass::getLockById($productId);
  103. if (empty($product)) {
  104. util::fail('没有找到花材呢');
  105. }
  106. //减少路上库存
  107. $onRecord = [];
  108. $onRecord['sjId'] = $sjId;
  109. $onRecord['shopId'] = $shopId;
  110. $onRecord['mainId'] = $mainId;
  111. $onRecord['orderSn'] = $orderSn;
  112. $onRecord['productId'] = $productId;
  113. $onRecord['itemId'] = $itemId;
  114. $onRecord['relateName'] = $ghsName;
  115. $onRecord['itemNum'] = $num;
  116. $oldOnStock = $product->onStock ?? 0;
  117. $onRecord['oldStock'] = $oldOnStock;
  118. $newOnStock = bcsub($oldOnStock, $num);
  119. $onRecord['newStock'] = $newOnStock;
  120. $onRecord['ptStyle'] = 1;
  121. OnStockRecordClass::cancelCg($onRecord);
  122. ProductClass::decreaseOnStockByItemNum($productId, $num);
  123. }
  124. }
  125. }
  126. //订单发货子方法 ssh 20231119
  127. public static function orderFh($cg, $params, $allowRepeat = false, $notice = false)
  128. {
  129. if ($notice) {
  130. $noticeText = json_encode(['id' => $cg->id]);
  131. $noticeKey = "ghsKdNoticeHd";
  132. Yii::$app->redis->executeCommand('LPUSH', [$noticeKey, $noticeText]);
  133. }
  134. if ($cg->status == 3) {
  135. if (!$allowRepeat) {
  136. util::fail('订单已发货');
  137. } else {
  138. return true;
  139. }
  140. }
  141. $fhType = $params['fhType'] ?? 0;
  142. if (!is_numeric($fhType)) {
  143. util::fail('请选择发货类型');
  144. }
  145. if ($fhType == 1) {
  146. $fhWl = $params['fhWl'] ?? '';
  147. $fhWlNo = $params['fhWlNo'] ?? '';
  148. if (empty($fhWl)) {
  149. util::fail('请填写物流名称');
  150. }
  151. if (empty($fhWlNo)) {
  152. util::fail('请填写物流编号');
  153. }
  154. $cg->fhWl = $fhWl;
  155. $cg->fhWlNo = $fhWlNo;
  156. }
  157. $cg->fhType = $fhType;
  158. $cg->status = 3;
  159. $cg->fhTime = date("Y-m-d H:i:s");
  160. $cg->save();
  161. $orderSn = $cg->orderSn ?? '';
  162. $itemList = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  163. if (!empty($itemList)) {
  164. $sjId = $cg->sjId ?? 0;
  165. $shopId = $cg->shopId ?? 0;
  166. $mainId = $cg->mainId ?? 0;
  167. $ghsName = $cg->ghsName ?? '';
  168. foreach ($itemList as $key => $val) {
  169. $productId = $val->productId ?? 0;
  170. $itemId = $val->itemId ?? 0;
  171. $num = $val->xhNum ?? 0;
  172. $product = ProductClass::getLockById($productId);
  173. if (empty($product)) {
  174. util::fail('没有找到花材呢');
  175. }
  176. //增加路上库存
  177. $onRecord = [];
  178. $onRecord['sjId'] = $sjId;
  179. $onRecord['shopId'] = $shopId;
  180. $onRecord['mainId'] = $mainId;
  181. $onRecord['orderSn'] = $orderSn;
  182. $onRecord['productId'] = $productId;
  183. $onRecord['itemId'] = $itemId;
  184. $onRecord['relateName'] = $ghsName;
  185. $onRecord['itemNum'] = $num;
  186. $oldOnStock = $product->onStock ?? 0;
  187. $onRecord['oldStock'] = $oldOnStock;
  188. $newOnStock = bcadd($oldOnStock, $num);
  189. $onRecord['newStock'] = $newOnStock;
  190. $onRecord['ptStyle'] = 1;
  191. OnStockRecordClass::addPurchaseOrderRecord($onRecord);
  192. ProductClass::addOnStockByItemNum($productId, $num);
  193. }
  194. }
  195. return $cg;
  196. }
  197. //确认收货 ssh 20231119
  198. public static function confirmTake($cg)
  199. {
  200. //订单如果没有发货,则先发货
  201. if ($cg->status == self::STATUS_UN_SEND) {
  202. $cg = self::orderSend($cg, [], true);
  203. }
  204. // 构建“冲销”函数的参数 -- 变动前的花材存库数据
  205. $purchaseItems = PurchaseItemClass::getAllByCondition(['orderSn' => $cg->orderSn], null, "productId");
  206. $productIds = ArrayHelper::getColumn($purchaseItems, 'productId'); //$productIds 是本次入库涉及的花材ID数组
  207. $oldStocks = [];
  208. foreach ($productIds as $productId) {
  209. $product = ProductClass::getById($productId, true);
  210. $oldStocks[$productId] = $product;
  211. }
  212. self::takeToPutIn($cg);
  213. $shop = ShopClass::getLockById($cg->shopId);
  214. if (empty($shop)) {
  215. util::fail('没有找到门店14');
  216. }
  217. $adminId = $shop->adminId;
  218. $mainId = $shop->mainId;
  219. PurchaseClass::rollbackProductStock($oldStocks, $shop, $adminId, $mainId, '系统');
  220. }
  221. //确认收货并入库 ssh 20231119
  222. public static function takeToPutIn($cg)
  223. {
  224. if ($cg->status != 3) {
  225. util::fail('订单不是待收货状态哦,编号:cg' . $cg->id);
  226. }
  227. $saleId = $cg->saleId ?? 0;
  228. $order = OrderClass::getById($saleId, true);
  229. if (empty($order)) {
  230. util::fail('没有找到订单');
  231. }
  232. if ($order->status != 3) {
  233. util::fail('订单不是待收货状态,订单状态:' . $order->status . ',订单ID:' . $saleId);
  234. }
  235. $order->status = 4;
  236. $order->save();
  237. //加库存 lqh 2021-05-10
  238. $orderSn = $cg->orderSn;
  239. $sjId = $cg->sjId ?? 0;
  240. $shopId = $cg->shopId ?? 0;
  241. $mainId = $cg->mainId ?? 0;
  242. $ghsName = $cg->ghsName ?? '';
  243. $purchaseItem = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, "*");
  244. foreach ($purchaseItem as $v) {
  245. //小单位库存不考虑入库 ssh 202310
  246. $itemNum = $v['itemNum'];
  247. if ($itemNum > 0) {
  248. $productId = $v['productId'];
  249. $stockInfo = ProductClass::addStockByItemNum($v['productId'], $itemNum);
  250. //记录库存流水
  251. $recordData = [];
  252. $recordData['sjId'] = $cg->sjId;
  253. $recordData['shopId'] = $cg->shopId;
  254. $recordData['mainId'] = $cg->mainId;
  255. $recordData['itemId'] = $v['itemId'] ?? 0;
  256. $recordData['itemNum'] = $itemNum;
  257. $recordData['oldStock'] = $stockInfo['oldStock'];
  258. $recordData['newStock'] = $stockInfo['newStock'];
  259. $recordData['productId'] = $v['productId'];
  260. $recordData['orderSn'] = $orderSn;
  261. $recordData['relateName'] = $cg->ghsName ?? '';
  262. StockRecordClass::addPurchaseOrderRecord($recordData);
  263. $product = ProductClass::getLockById($productId);
  264. if (empty($product)) {
  265. util::fail('没有找到花材哈');
  266. }
  267. //减少路上库存
  268. $onRecord = [];
  269. $onRecord['sjId'] = $sjId;
  270. $onRecord['shopId'] = $shopId;
  271. $onRecord['mainId'] = $mainId;
  272. $onRecord['orderSn'] = $orderSn;
  273. $onRecord['productId'] = $productId;
  274. $onRecord['itemId'] = $v['itemId'] ?? 0;
  275. $onRecord['relateName'] = $ghsName;
  276. $onRecord['itemNum'] = $itemNum;
  277. $oldOnStock = $product->onStock ?? 0;
  278. $onRecord['oldStock'] = $oldOnStock;
  279. $onRecord['newStock'] = bcsub($oldOnStock, $itemNum);
  280. $onRecord['ptStyle'] = 1;
  281. OnStockRecordClass::addInStockOrderRecord($onRecord);
  282. ProductClass::decreaseOnStockByItemNum($productId, $itemNum);
  283. $unitPrice = $v['xhUnitPrice'] ?? 0;
  284. $product->cost = $unitPrice;
  285. $product->save();
  286. $ptItemId = $product->itemId ?? 0;
  287. $mainId = $product->mainId ?? 0;
  288. $staffId = $cg->shopAdminId ?? 0;
  289. $staffName = $cg->shopAdminName ?? '';
  290. //成本变动记录
  291. $changeData = [
  292. 'ptStyle' => 2,
  293. 'sjId' => 0,
  294. 'mainId' => $mainId,
  295. 'itemId' => $productId,
  296. 'ptItemId' => $ptItemId,
  297. 'cost' => $unitPrice,
  298. 'staffId' => $staffId,
  299. 'staffName' => $staffName,
  300. 'name' => $product->name ?? '',
  301. 'cover' => $product->cover ?? '',
  302. 'targetId' => $cg->id ?? 0,
  303. 'event' => '采购',
  304. ];
  305. CostChangeClass::addData($changeData);
  306. }
  307. }
  308. $cg->status = 4;
  309. $cg->stockChange = 1;
  310. $cg->save();
  311. }
  312. // 库存回滚为入库前的状态
  313. public static function rollbackProductStock($oldStocks, $shop, $adminId, $mainId, $staffName)
  314. {
  315. $itemInfo = [];
  316. foreach ($oldStocks as $productId => $product) {
  317. $ratio = $product->ratio;
  318. $formNum = ProductClass::formatStock($product->stock, $ratio); //花材的库存转换
  319. $itemInfo[] = [
  320. 'productId' => $productId,
  321. 'itemNum' => $product->stock, // 回滚为入库前的库存
  322. 'itemId' => $product->itemId,
  323. 'bigNum' => $formNum['bigNum'],
  324. 'smallNum' => $formNum['smallNum'],
  325. 'price' => $product->price,
  326. ];
  327. }
  328. $data = [
  329. 'sjId' => $shop->sjId,
  330. 'shopId' => $shop->id,
  331. 'adminId' => $adminId,
  332. 'mainId' => $mainId,
  333. 'staffName' => $staffName,
  334. 'itemInfo' => $itemInfo,
  335. 'pdType' => 'rollbackStock',
  336. 'remark' => '',
  337. ];
  338. \bizGhs\order\classes\CheckOrderClass::opOrder($data, false, false, false);
  339. }
  340. // 指定花材新增库存
  341. public static function increaseProductStock($itemDatas, $shop, $adminId, $mainId, $staffName)
  342. {
  343. $itemInfo = [];
  344. foreach ($itemDatas as $productId => $arr) {
  345. $addNum = $arr['addNum']; //新增的数值
  346. $product = $arr['product'];
  347. $ratio = $product->ratio;
  348. $newStock = bcadd($product->stock, $addNum, 2);
  349. $formNum = ProductClass::formatStock($newStock, $ratio); //花材的库存转换
  350. $itemInfo[] = [
  351. 'productId' => $productId,
  352. 'itemNum' => $newStock, // 新库存数
  353. 'itemId' => $product->itemId,
  354. 'bigNum' => $formNum['bigNum'],
  355. 'smallNum' => $formNum['smallNum'],
  356. 'price' => $product->price,
  357. ];
  358. }
  359. $data = [
  360. 'sjId' => $shop->sjId,
  361. 'shopId' => $shop->id,
  362. 'adminId' => $adminId,
  363. 'mainId' => $mainId,
  364. 'staffName' => $staffName,
  365. 'itemInfo' => $itemInfo,
  366. 'pdType' => 'rollbackStock',
  367. 'remark' => '',
  368. ];
  369. \bizGhs\order\classes\CheckOrderClass::opOrder($data, false, false, false);
  370. }
  371. public static function notSameCity($shop, $ghsShop)
  372. {
  373. return true;
  374. $shopLat = $shop->lat ?? '';
  375. $shopLong = $shop->long ?? '';
  376. if (empty($shopLat) || empty($shopLong)) {
  377. util::fail('请完善门店地址');
  378. }
  379. $ghsShopLat = $ghsShop->lat ?? '';
  380. $ghsShopLong = $ghsShop->long ?? '';
  381. $distance = mapUtil::calculateDistance($shopLong, $shopLat, $ghsShopLong, $ghsShopLat);
  382. $formatDistance = ceil($distance / 1000);
  383. if ($formatDistance > 150) {
  384. return false;
  385. }
  386. return true;
  387. }
  388. //计算距离和运费【另外还有个地方要同步修改,关键词calc_freight_distance】 ssh 20221003
  389. public static function getDistanceFee($shop, $ghsShop, $weight, $custom)
  390. {
  391. $ability = ShopClass::hasIntraCity($ghsShop);
  392. $openIntraCity = $ability['openIntraCity'] ?? 0;
  393. if ($openIntraCity == 0) {
  394. //没有开启同城配送能力,不计算运费和距离
  395. return ['distance' => 0, 'showDistance' => 0, 'fee' => 0];
  396. }
  397. $shopLat = $shop->lat ?? '';
  398. $shopLong = $shop->long ?? '';
  399. if (empty($shopLat) || empty($shopLong)) {
  400. util::fail('请完善你的收花地址');
  401. }
  402. $address = $shop->address ?? '';
  403. if (empty($address)) {
  404. util::fail('请完善收花地址');
  405. }
  406. if ($weight <= 0) {
  407. util::fail('花材没有重量');
  408. }
  409. $wxStoreId = $ability['wxStoreId'] ?? '';
  410. $packageNum = 1;
  411. $price = 300;
  412. $cargo = [
  413. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  414. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  415. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  416. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  417. 'cargo_num' => $packageNum
  418. ];
  419. $customName = $custom->name ?? '';
  420. if (empty($customName)) {
  421. util::fail('客户名称是空的');
  422. }
  423. $customMobile = $custom->mobile ?? '';
  424. if (empty($customMobile)) {
  425. util::fail('客户手机缺失');
  426. }
  427. //根据环境变量判断是否使用沙盒环境
  428. // $useSandBox = getenv('YII_ENV') == 'production' ? 0 : 1;
  429. $orderData = [
  430. 'wx_store_id' => $wxStoreId,
  431. 'user_name' => $customName,
  432. 'user_phone' => $customMobile,
  433. 'user_lng' => $shopLong,
  434. 'user_lat' => $shopLat,
  435. 'user_address' => $address,
  436. 'cargo' => $cargo,
  437. // 'use_sandbox' => $useSandBox,//正式环境不能传这个参数,会报错
  438. ];
  439. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  440. $result = IntraCityExpress::preAddOrder($orderData);
  441. if ($result['errcode'] !== 0) {
  442. $errMsg = $result['errmsg'] ?? '';
  443. noticeUtil::push('运费查询失败原因:' . $errMsg . '参数:' . $result['errcode'], '15280215347');
  444. util::fail('运费查询失败,编号1160');
  445. }
  446. $distance = $result['distance'] ?? 0;
  447. $showDistance = sprintf("%.1f", ($distance / 1000));
  448. $fee = $result['est_fee'] ?? 0;
  449. $totalFee = sprintf("%.1f", ($fee / 100));
  450. //noticeUtil::push("批发订单,获取运费:{$totalFee} 重量:{$weight} 距离:{$showDistance} 客户名:{$customMobile} 手机号 {$customMobile} 经纬 {$shopLong} {$shopLat} 金额:{$price} 数量:{$packageNum}", '15280215347');
  451. return ['distance' => $distance, 'showDistance' => $showDistance, 'fee' => $totalFee];
  452. }
  453. //到货之后 ssh 20220321
  454. public static function arrival($cg, $data)
  455. {
  456. if ($cg->stockChange == 1) {
  457. util::fail('您已操作过了');
  458. }
  459. $sendCost = isset($data['sendCost']) && is_numeric($data['sendCost']) ? $data['sendCost'] : 0;
  460. $packCost = isset($data['packCost']) && is_numeric($data['packCost']) ? $data['packCost'] : 0;
  461. $cg->sendCost = $sendCost;
  462. $cg->packCost = $packCost;
  463. $cg->save();
  464. $sjId = $data['sjId'] ?? 0;
  465. $shopId = $data['shopId'] ?? 0;
  466. //product [{"productId":"3674","num":0,"price":1}]
  467. $product = $data['product'] ?? '';
  468. if (empty($product)) {
  469. util::fail('请填写成本价和到货数量');
  470. }
  471. $ghsName = $cg->ghsName ?? '';
  472. $orderSn = $cg->orderSn ?? '';
  473. $list = PurchaseItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
  474. if (empty($list)) {
  475. util::fail('没有找到花材哦');
  476. }
  477. $weight = 0;
  478. $itemPrice = 0;
  479. foreach ($list as $key => $val) {
  480. $productId = $val->productId ?? 0;
  481. if (isset($product[$productId]) == false) {
  482. util::fail('没有找到对应采购花材');
  483. }
  484. $num = $product[$productId]['num'] ?? 0;
  485. $price = $product[$productId]['price'] ?? 0;
  486. if ($price <= 0) {
  487. util::fail('花材金额需要大于0');
  488. }
  489. $totalPrice = bcmul($num, $price, 2);
  490. $itemPrice = bcadd($itemPrice, $totalPrice, 2);
  491. $val->price = $price;
  492. $val->itemNum = $num;
  493. $val->preTotalPrice = $totalPrice;
  494. $val->totalPrice = $totalPrice;
  495. $val->xhNum = $num;
  496. $val->xhUnitPrice = $price;
  497. $val->xhPrice = $totalPrice;
  498. $val->save();
  499. $unitWeight = $val->unitWeight ?? 0;
  500. $currentWeight = bcmul($num, $unitWeight, 2);
  501. $weight = bcadd($weight, $currentWeight, 2);
  502. $unitType = $val->xhUnitType ?? 0;
  503. $bigNum = 0;
  504. $smallNum = 0;
  505. if ($unitType == dict::getDict('unitType', 'big')) {
  506. $bigNum = $num;
  507. } else {
  508. $smallNum = $num;
  509. }
  510. //增加库存
  511. $option = ['relateName' => $ghsName];
  512. StockClass::purchaseItem($orderSn, $sjId, $shopId, $productId, $bigNum, $smallNum, $option);
  513. }
  514. $cg->itemPrice = $itemPrice;
  515. $sendCost = $cg->sendCost ?? 0;
  516. $currentPrice = bcadd($itemPrice, $sendCost, 2);
  517. $packCost = $cg->packCost ?? 0;
  518. $currentPrice = bcadd($currentPrice, $packCost, 2);
  519. $kiloFee = $data['kiloFee'] ?? 0;
  520. $miniKilo = $data['miniKilo'] ?? 0;
  521. $calcWeight = $weight > $miniKilo ? $weight : $miniKilo;
  522. $allKiloFee = bcmul($calcWeight, $kiloFee, 2);
  523. $currentPrice = bcadd($currentPrice, $allKiloFee, 2);
  524. $cg->prePrice = $currentPrice;
  525. $cg->orderPrice = $currentPrice;
  526. $cg->actPrice = $currentPrice;
  527. $cg->realPrice = $currentPrice;
  528. $cg->stockChange = 1;
  529. $cg->save();
  530. $mainId = $cg->mainId ?? 0;
  531. $sjId = $cg->sjId ?? 0;
  532. $shopId = $cg->shopId ?? 0;
  533. $cgId = $cg->id ?? 0;
  534. $saleRefundId = $data['saleRefundId'] ?? 0;
  535. $shop = ShopClass::getLockById($shopId);
  536. if (empty($shop)) {
  537. util::fail('没有找到零售店的门店');
  538. }
  539. $main = MainClass::getLockById($mainId);
  540. if (empty($main)) {
  541. util::fail('没有main信息12');
  542. }
  543. $main->cgUnSend -= 1;
  544. $main->cgFinish += 1;
  545. $main->save();
  546. $cgRefund = null;
  547. $bookPrice = $cg->bookPrice ?? 0;
  548. if ($bookPrice == $currentPrice) {
  549. return ['refund' => $cgRefund];
  550. } elseif ($bookPrice > $currentPrice) {
  551. //退款
  552. $refundPrice = bcsub($bookPrice, $currentPrice, 2);
  553. $book = 1;
  554. $refundOrderSn = orderSn::getCgRefundSn();
  555. $refundType = CgRefundClass::REFUND_TYPE_MONEY;
  556. $refundData = [
  557. 'book' => $book,
  558. 'mainId' => $mainId,
  559. 'orderSn' => $refundOrderSn,
  560. 'cgId' => $cgId,
  561. 'status' => CgRefundClass::STATUS_COMPLETE,
  562. 'shopAdminId' => 0,
  563. 'shopAdminName' => '',
  564. 'refundType' => $refundType,
  565. 'refundPrice' => $refundPrice,
  566. 'saleRefundId' => $saleRefundId,
  567. 'sjId' => $sjId,
  568. 'shopId' => $shopId,
  569. ];
  570. $cgRefund = CgRefundClass::add($refundData, true);
  571. //门店收入增加
  572. $currentTotalIncome = bcadd($main->totalIncome, $refundPrice, 2);
  573. $main->totalIncome = $currentTotalIncome;
  574. $main->save();
  575. //供货商退款,向供货商采购总金额减少
  576. StatCgClass::replace($main, $shop, $refundPrice, 0, false);
  577. //供货商退款,按供货商分别采购的金额减少
  578. StatCgGhsClass::hdCgGhsReplace(false, $cg, $refundPrice, 0);
  579. $currentType = dict::getDict('capitalType', 'hdBookRefund', 'id');
  580. $sjId = $cg->sjId ?? 0;
  581. $shopId = $cg->shopId ?? 0;
  582. $event = "预订单{$orderSn}多退少补({$ghsName})";
  583. $capitalData = [
  584. 'capitalType' => $currentType,
  585. 'io' => 1,
  586. 'totalIncome' => $currentTotalIncome,
  587. 'payWay' => 0,
  588. 'amount' => $refundPrice,
  589. 'sjId' => $sjId,
  590. 'shopId' => $shopId,
  591. 'event' => $event,
  592. 'mainId' => $mainId,
  593. ];
  594. ShopCapitalClass::addCapital($capitalData);
  595. //收入统计
  596. StatIncomeClass::updateOrInsert($main, $shop, $refundPrice);
  597. $ghsId = $cg->ghsId ?? 0;
  598. $ghs = GhsClass::getLockById($ghsId);
  599. if (empty($ghs)) {
  600. util::fail('没有找到供货商');
  601. }
  602. $ghsShopId = $ghs->shopId ?? 0;
  603. $ghsShop = ShopClass::getById($ghsShopId, true);
  604. if (empty($ghsShop)) {
  605. util::fail('没有找到供货商的门店');
  606. }
  607. $refundFee = bcmul($refundPrice, 100);
  608. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  609. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  610. $params = [
  611. 'appid' => 'OP00002119',
  612. 'serial_no' => '018b08cfddbd',
  613. 'merchant_no' => $ghsShop->lklSjNo,
  614. 'term_no' => $ghsShop->lklScanTermNo,
  615. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  616. 'lklCertificatePath' => $lklCertificatePath,
  617. ];
  618. $laResource = new Lakala($params);
  619. $refundReason = '';
  620. $aliParams = [
  621. 'refundSn' => $refundOrderSn,
  622. 'orderSn' => $orderSn,
  623. 'refundAmount' => $refundFee,
  624. 'refundReason' => $refundReason,
  625. ];
  626. $response = $laResource->refund($aliParams);
  627. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  628. $errMsg = $response['msg'] ?? '';
  629. noticeUtil::push('退款失败了哦!请注意:' . $errMsg . ' 金额:' . $refundFee, '15280215347');
  630. util::fail('退款失败');
  631. }
  632. $refundTradeNo = isset($response['resp_data']['trade_no']) ? $response['resp_data']['trade_no'] : '';
  633. $cgRefund->thirdRefundNo = $refundTradeNo;
  634. $cgRefund->save();
  635. $cg->refundPrice = $refundPrice;
  636. $cg->tkPrice = bcadd($cg->tkPrice, $refundPrice, 2);
  637. $cg->refund = self::REFUND_YES;
  638. $cg->refundLog = 1;
  639. $cg->save();
  640. } else {
  641. //欠款
  642. $currentDebt = bcsub($currentPrice, $bookPrice, 2);
  643. $cg->debtPrice = $currentDebt;
  644. $cg->remainDebtPrice = $currentDebt;
  645. $cg->debt = PurchaseClass::DEBT_YES;
  646. $cg->save();
  647. $payWay = dict::getDict('payWay', 'debtPay');
  648. $ghsId = $cg->ghsId ?? 0;
  649. $ghs = GhsClass::getLockById($ghsId);
  650. if (empty($ghs)) {
  651. util::fail('没有找到供货商');
  652. }
  653. \bizHd\ghs\classes\GhsClass::cgDebtAmountAdd($ghs, $cg, true);
  654. //支出统计
  655. StatOutClass::updateOrInsert($main, $shop, $currentDebt);
  656. //支出流水
  657. $capitalType = dict::getDict('capitalType', 'hdBookFinalPay', 'id');
  658. $sjId = $cg->sjId ?? 0;
  659. $shopId = $cg->shopId ?? 0;
  660. $currentExpend = bcadd($main->totalExpend, $currentDebt, 2);
  661. $main->totalExpend = $currentExpend;
  662. $main->save();
  663. $event = "预订单{$orderSn}补尾款欠款";
  664. $capitalData = [
  665. 'capitalType' => $capitalType,
  666. 'io' => 0,
  667. 'totalExpend' => $currentExpend,
  668. 'payWay' => $payWay,
  669. 'amount' => $currentDebt,
  670. 'sjId' => $sjId,
  671. 'shopId' => $shopId,
  672. 'event' => $event,
  673. 'mainId' => $mainId,
  674. ];
  675. ShopCapitalClass::addCapital($capitalData);
  676. //补款给供货商,采购总金额增加
  677. StatCgClass::replace($main, $shop, $currentDebt, 0, true);
  678. //补款给供货商,按供货商分别统计采购量增加
  679. StatCgGhsClass::hdCgGhsReplace(true, $cg, $currentDebt, 0);
  680. }
  681. return ['refund' => $cgRefund];
  682. }
  683. //添加采购 ssh 2021.1.18
  684. public static function addPurchase($data, $ghs)
  685. {
  686. $shopId = $data['shopId'] ?? 0;
  687. $sjId = $data['sjId'] ?? 0;
  688. $mainId = $data['mainId'] ?? 0;
  689. $ghsId = $data['ghsId'] ?? 0;
  690. $book = $data['book'] ?? 0;
  691. $shopAdminId = $data['shopAdminId'] ?? 0;
  692. $customId = $data['customId'] ?? 0;
  693. $snData = ['shopId' => $shopId, 'mainId' => $mainId, 'ghsId' => $ghsId, 'customId' => $customId];
  694. $orderSn = orderSn::getPurchaseSn($snData);
  695. $data['orderSn'] = $orderSn;
  696. $prePrice = 0;
  697. $live = $ghs['live'] ?? 1;
  698. $sendTimeWant = !empty($data['sendTimeWant']) ? $data['sendTimeWant'] : date("Y-m-d");
  699. if ($sendTimeWant < date("Y-m-d")) {
  700. util::fail('您选了过去时间');
  701. }
  702. $data['sendTimeWant'] = $sendTimeWant;
  703. if (empty($data['product'])) {
  704. util::fail('请选择花材17');
  705. }
  706. $productList = $data['product'];
  707. $productList = self::mergeItemInfo($productList);
  708. $data['kindNum'] = count($productList); //多少种花材
  709. //传过来的是供货商的productId,需要转换为零售端的productId
  710. //数据格式 [{"productId":"113","bigNum":1,"smallNum":0,"classId":"-2","hdProductId":1}]
  711. if ($live == 1) {
  712. //花店真实向批发店采购花材,因为拿的供货商的ID,所以需要转化花店的id
  713. $productList = ProductClass::toggleProductList($productList, $shopId, $sjId, $mainId, $ghs);
  714. $ghsProductData = self::getProductMapData($productList, "ghsProductId");
  715. } else {
  716. //虚拟采购用的自己的ID所以不需要转化
  717. $ghsProductData = [];
  718. }
  719. $hdProductData = self::getProductMapData($productList, "productId");
  720. $giveLevel = $ghs['giveLevel'] ?? 0;
  721. $priceMap = CustomClass::$levelPriceKeyMap;
  722. //这个参数应该是要作废的,但下面加的参数是有用的,多处要同步修改,关键词 abandon_add_price_map ,ssh 20260116
  723. $addPriceMap = CustomClass::$levelAddPriceKeyMap;
  724. //但这边加的参数是有用的,给指定客户涨价的
  725. $addPriceMap['risePercent'] = $ghs['risePercent'] ?? 0;
  726. //累计满减
  727. $totalReachDiscount = 0;
  728. //计算价格= 各个productId的price*num(bigNum,smallNum) + sendCost(配送费)
  729. $bigNum = 0; //总共多少扎
  730. $smallNum = 0; //总共多少支
  731. $totalWeight = 0;
  732. foreach ($productList as $key => $product) {
  733. $currentBigNum = $product['bigNum'] ?? 0;
  734. $currentSmallNum = $product['smallNum'] ?? 0;
  735. $bigNum += $product['bigNum'] ?? 0;
  736. $smallNum += $product['smallNum'] ?? 0;
  737. $productList[$key]['orderSn'] = $orderSn;
  738. if ($live == 1) {
  739. $ghsProductId = $product['ghsProductId'];
  740. $hdProductId = $product['productId'];
  741. } else {
  742. $hdProductId = $product['productId'] ?? 0;
  743. $ghsProductId = 0;
  744. }
  745. $unitWeight = $hdProductData[$hdProductId]['weight'] ?? 0;
  746. $variety = $hdProductData[$hdProductId]['variety'] ?? 0;
  747. $ratio = $hdProductData[$hdProductId]['ratio'] ?? 0;
  748. $ratioType = $hdProductData[$hdProductId]['ratioType'] ?? 0;
  749. $itemId = $hdProductData[$hdProductId]['itemId'] ?? 0;
  750. $rank = $hdProductData[$hdProductId]['rank'] ?? 'B';
  751. $stock = $hdProductData[$hdProductId]['stock'] ?? 0;
  752. $kind = $hdProductData[$hdProductId]['kind'] ?? 0;
  753. $stockFormat = ProductClass::formatStock($stock, $ratio);
  754. $limitKey = ProductClass::LIMIT_BUY_KEY . $ghsProductId; // 注意:要使用批发的花材id
  755. $hasNum = Yii::$app->redis->executeCommand('HGET', [$limitKey, $customId]);
  756. $hasBuyNum = $hasNum ?: 0;
  757. $itemNum = ProductClass::mergeItemNum($product['bigNum'], $product['smallNum'], $ratio);
  758. $hasBuyNum = bcadd($itemNum, $hasBuyNum, 2); // 已购买总数量
  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, $hasBuyNum);
  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. }