CloudStockAgentOrder.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. <?php
  2. namespace addons\CloudStock\common\models;
  3. use addons\CloudStock\common\events\order\FillOrderPickEvent;
  4. use addons\CloudStock\common\services\CloudStockAgentCartService;
  5. use addons\CloudStock\common\services\CloudStockAgentGoodsService;
  6. use addons\CloudStock\common\services\CloudStockAgentOrderService;
  7. use addons\CloudStock\common\services\CloudStockLevelService;
  8. use common\enums\AppEnum;
  9. use common\enums\PayTypeEnum;
  10. use common\enums\PreviewTypeEnum;
  11. use common\enums\ShippingTypeEnum;
  12. use common\enums\StatusEnum;
  13. use common\helpers\FormatHelper;
  14. use common\logic\order\OrderFormLogic;
  15. use common\logic\order\OrderInitDataLogic;
  16. use common\logic\order\OrderMarketingLogic;
  17. use common\models\base\BaseActiveRecord;
  18. use common\models\common\Express;
  19. use common\models\goods\Goods;
  20. use common\models\logistics\LogisticsSearch;
  21. use common\models\order\OrderExpress;
  22. use common\models\user\User;
  23. use addons\CloudStock\common\enums\CloudStockEnum;
  24. use addons\Coupon\common\models\AddonsCouponUserRelate;
  25. use common\enums\AddonsEnum;
  26. use common\enums\RabbitMqEnum;
  27. use common\models\mall\MallAddons;
  28. use common\models\user\UserAddress;
  29. use common\components\export\CsvTool;
  30. use common\enums\DownloadEnum;
  31. use common\models\common\Download;
  32. use common\helpers\StringHelper;
  33. use Yii;
  34. /**
  35. * This is the model class for table "{{%addons_cloud_stock_agent_order".
  36. *
  37. * @property int $id
  38. * @property int $mall_id 商城id
  39. * @property int $user_id 用户id
  40. * @property int $goods_id 商品ID
  41. * @property int $num 商品数量
  42. * @property string $address 收货人地址
  43. * @property string $express_no 发货单号
  44. * @property string $express_code 物流公司编号
  45. * @property int $send_status 0待发货;1已发货;2已完成;
  46. * @property string $mobile 收货人手机号码
  47. * @property string $name 收货人名称
  48. * @property int $status 状态[-1:删除;0:禁用;1启用]
  49. * @property int $created_at
  50. * @property int $updated_at
  51. * @property int $province_id
  52. * @property int $city_id
  53. * @property int $district_id
  54. * @property int $town_id
  55. * @property string $list 物流信息
  56. * @property int $table_express_status 物流状态0/未完成 1/已完成
  57. * @property int $express_status 当前物流状态(物流公司状态)
  58. * @property int $order_type 1:云仓自提;2:价差礼包自提
  59. * @property string $seller_remark 卖家备注
  60. * @property int $cancel_admin_id 取消自提的管理员id
  61. * @property int $is_shipping_refunded 是否已经退了运费
  62. * @property int $is_delivery_address_modified 是否修改过收货地址
  63. */
  64. class CloudStockAgentOrder extends BaseActiveRecord
  65. {
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public static function tableName()
  70. {
  71. return '{{%addons_cloud_stock_agent_order}}';
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function rules()
  77. {
  78. return [
  79. [['mall_id', 'user_id', 'goods_id', 'num', 'send_status', 'status', 'created_at', 'updated_at',
  80. 'province_id', 'city_id', 'district_id', 'town_id', 'table_express_status', 'express_status', 'trade_id', 'order_type', 'cancel_admin_id', 'is_shipping_refunded', 'is_delivery_address_modified'], 'integer'],
  81. [['name'], 'required'],
  82. [['address', 'express_no', 'express_code'], 'string', 'max' => 128],
  83. [['mobile'], 'string', 'max' => 45],
  84. [['name'], 'string', 'max' => 125],
  85. [['remark','order_no','trade_no', 'seller_remark'], 'string', 'max' => 225],
  86. [['list'], 'string'],
  87. [['pay_money'], 'number'],
  88. ];
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function attributeLabels()
  94. {
  95. return [
  96. 'id' => 'ID',
  97. 'mall_id' => '商城id',
  98. 'user_id' => '用户id',
  99. 'goods_id' => '商品ID',
  100. 'num' => '商品数量',
  101. 'address' => '收货人地址',
  102. 'express_no' => '发货单号',
  103. 'express_code' => '物流公司编号',
  104. 'send_status' => '0待发货;1已发货;2已完成;',
  105. 'mobile' => '收货人手机号码',
  106. 'name' => '收货人名称',
  107. 'status' => '状态[-1:删除;0:禁用;1启用]',
  108. 'created_at' => 'Created At',
  109. 'updated_at' => 'Updated At',
  110. 'province_id' => '省',
  111. 'city_id' => '市',
  112. 'district_id' => '区',
  113. 'town_id' => '镇',
  114. 'remark' => '用户备注',
  115. 'list' => '物流信息',
  116. 'table_express_status' => '物流状态0/未完成 1/已完成',
  117. 'express_status' => '当前物流状态(物流公司状态)',
  118. 'seller_remark' => '卖家备注',
  119. 'cancel_admin_id' => '取消自提的管理员id',
  120. 'is_shipping_refunded' => '是否已经退了运费',
  121. 'is_delivery_address_modified' => '是否已经修改过收货地址',
  122. ];
  123. }
  124. public function getUser()
  125. {
  126. return $this->hasOne(User::class, ['id' => 'user_id'])->select(['id', 'nickname', 'avatar_url', 'mobile']);
  127. }
  128. public function getGoods()
  129. {
  130. return $this->hasOne(Goods::class, ['id' => 'goods_id'])->select(['id', 'goods_name', 'cover_pic']);
  131. }
  132. public function getDetails()
  133. {
  134. return $this->hasMany(CloudStockAgentOrderDetails::class, ['order_id' => 'id']);
  135. }
  136. public static function setData(int $mall_id, array $data, array $express = null)
  137. {
  138. try {
  139. if (!empty($data['id'])) {
  140. $model = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $data['id']]);
  141. if (empty($model)) {
  142. self::$static_error = '数据异常';
  143. return false;
  144. }
  145. } else {
  146. $model = new self();
  147. $model->loadDefaultValues();
  148. $model->mall_id = $mall_id;
  149. }
  150. foreach ($data as $key => $val) {
  151. $model->$key = $val;
  152. }
  153. if (!$model->save()) {
  154. self::$static_error = '保存数据失败:' . $model->getErrorMessage();
  155. return false;
  156. }
  157. if (!empty($express) && empty(OrderExpress::getOne([
  158. ['cs_order_id' => $model->id]
  159. ]))) { // 发货
  160. $flag = OrderExpress::delivery([
  161. 'mall_id' => $model->mall_id,
  162. 'cs_order_id' => $model->id,
  163. 'buyer_id' => $model->user_id,
  164. 'buyer_name' => User::find()->where(['id' => $model->user_id])->select('nickname')->scalar() ?? '',
  165. 'operator_name' => '来自旺店通的发货',
  166. 'shipping_type' => ShippingTypeEnum::LOGISTICS,
  167. 'express_id' => $express['express_id'],
  168. 'express_name' => $express['express_name'] ?? '',
  169. 'express_no' => $model->express_no,
  170. 'memo' => '',
  171. 'order_detail_ids' => [],
  172. 'shipping_change' => '',
  173. 'customer_name' => '旺店通',
  174. 'order_id' => 0,
  175. ], false);
  176. }
  177. $cloudStockAgentOrderInfo = self::findOne(['mall_id' => $mall_id, 'id' => $data['id'], 'express_code' => $data['express_code'], 'express_no' => $data['express_no']]);
  178. if(!empty($cloudStockAgentOrderInfo)){
  179. $flag = OrderExpress::delivery([
  180. 'mall_id' => $model->mall_id,
  181. 'cs_order_id' => $model->id,
  182. 'buyer_id' => $model->user_id,
  183. 'buyer_name' => User::find()->where(['id' => $model->user_id])->select('nickname')->scalar() ?? '',
  184. 'operator_name' => '',
  185. 'shipping_type' => ShippingTypeEnum::LOGISTICS,
  186. 'express_no' => $model->express_no,
  187. 'memo' => '',
  188. 'order_detail_ids' => [],
  189. 'shipping_change' => '',
  190. 'customer_name' => '',
  191. 'order_id' => 0,
  192. ], false);
  193. }
  194. return $model;
  195. } catch (\Exception $e) {
  196. self::$static_error = '异常保存数据失败:' . $e->getMessage();
  197. return false;
  198. }
  199. }
  200. /**
  201. * 批量发货功能
  202. *
  203. * 该函数用于处理订单的批量发货操作
  204. */
  205. public static function asyncBatchDelivery($params)
  206. {
  207. if (empty($params)) {
  208. Yii::error('发货失败,内容为空');
  209. return null;
  210. }
  211. Yii::$app->db->close();
  212. $trans = Yii::$app->db->beginTransaction();
  213. try {
  214. $model = CloudStockOrderBatchDelivery::findOne(['id' => $params['id']]);
  215. if (empty($model)) throw new \Exception("批量发货id={$params['id']}数据查询为空");
  216. $express=Express::getOne([['id'=>$model->express_id]]);
  217. if (empty($express)) throw new \Exception("系统中没有该物流公司信息");
  218. // 读取csv文件内容
  219. $file = fopen($model->delivery_file,'r');
  220. while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
  221. $file_list[] = $data;
  222. }
  223. fclose($file);
  224. $time = time();
  225. $delivery_num = $success_delivery_num = 0;// 已处理的订单数量、处理成功数量
  226. foreach ($file_list as $key => $item) {
  227. if ($key == 0) continue;
  228. $order_no = trim($item[0]);
  229. $express_no = ltrim(trim($item[1]),"'");
  230. $delivery_num++;
  231. $success_status = true;
  232. $error_string = '';
  233. $error = ['mall_id' => $model->mall_id, 'batch_delivery_id' => $model->id, 'order_no'=>$order_no, 'express_no'=>$express_no];
  234. if (empty($order_no)) $error_string .= '订单号不能为空 ';
  235. if (empty($express_no)) $error_string .= '物流单号不能为空 ';
  236. if ($error_string) {
  237. $error['content'] = $error_string;
  238. CloudStockOrderBatchDeliveryError::setData($error);
  239. continue;
  240. }
  241. $order = self::getOne([['mall_id' => $model->mall_id,'order_no' => $order_no, 'status'=>[StatusEnum::ENABLED]]]);
  242. if (empty($order)) {
  243. $error['content'] = '查无此订单';
  244. CloudStockOrderBatchDeliveryError::setData($error);
  245. continue;
  246. }
  247. $flag = OrderExpress::delivery([
  248. 'mall_id' => $order->mall_id,
  249. 'cs_order_id' =>$order->id,
  250. 'buyer_id' => $order->user_id,
  251. 'buyer_name' => $order->name,
  252. 'operator_name' => $model->operator_name,
  253. 'shipping_type' => ShippingTypeEnum::LOGISTICS,
  254. 'express_id' => $model->express_id,
  255. 'express_name' => $model->express_name ?? '',
  256. 'express_no' => (string)$express_no,
  257. 'memo' => '',
  258. 'order_detail_ids' => [],
  259. 'shipping_change' => '',
  260. 'customer_name' => '旺店通',
  261. 'order_id' => 0,
  262. ], false);
  263. if ($flag === false) {
  264. $error['content'] = CloudStockOrderBatchDeliveryError::getStaticError();
  265. CloudStockOrderBatchDeliveryError::setData($error);
  266. $success_status = false;
  267. }
  268. $order->send_status=CloudStockEnum::SEND_STATUS_1;
  269. $order->express_no = $express_no;
  270. $order->express_code = $express->code;
  271. $orderResult=$order->save();
  272. if ($orderResult === false) {
  273. $error['content'] = CloudStockAgentOrder::getStaticError();
  274. CloudStockOrderBatchDeliveryError::setData($error);
  275. $success_status = false;
  276. }
  277. $success_status && $success_delivery_num++;
  278. }
  279. // 修改数据
  280. $model->delivery_num = $delivery_num;
  281. $model->success_delivery_num = $success_delivery_num;
  282. $model->delivery_status = StatusEnum::ENABLED;
  283. if (!$model->save()) throw new \Exception($model->getErrorMessage());
  284. $trans->commit();
  285. return true;
  286. } catch (\Exception $e) {
  287. $trans->rollBack();
  288. $exception = FormatHelper::exception($e, "订单批量发货事件");
  289. echo $exception;
  290. Yii::error($exception);
  291. return false;
  292. }
  293. }
  294. /**
  295. * @name:
  296. * @msg: 提货到线下
  297. * @param {int} $mall_id
  298. * @param {array} $data user_id:会员id;addr_id:收货地址id;goods_id:商品id;number:提货数量
  299. * @return {*}
  300. */
  301. public static function pickOffline(int $mall_id, array $data)
  302. {
  303. $addr = UserAddress::findOne(['user_id' => $data['user_id'], 'id' => $data['addr_id'], 'status' => StatusEnum::ENABLED]);
  304. if (empty($addr)) {
  305. self::$static_error = '收货地址不存在';
  306. return false;
  307. }
  308. // 数据验证
  309. $addr_full = $addr->province . $addr->city . $addr->district . $addr->town . $addr->detail;
  310. $order_no = StringHelper::generateOrderNo('CSP');
  311. $order_params = [
  312. 'mall_id' => $mall_id,
  313. 'user_id' => $data['user_id'],
  314. 'goods_id' => 0,
  315. 'num' => 0,
  316. 'address' => $addr_full,
  317. 'express_no' => '',
  318. 'express_code' => '',
  319. 'send_status' => CloudStockEnum::PICK_ORDER_STATUS0,
  320. 'mobile' => $addr->mobile,
  321. 'name' => $addr->name,
  322. 'province_id' => $addr->province_id,
  323. 'city_id' => $addr->city_id,
  324. 'district_id' => $addr->district_id,
  325. 'town_id' => $addr->town_id,
  326. 'status' => StatusEnum::ENABLED,
  327. 'remark' => $data['remark'] ?? '',
  328. 'order_no' => $order_no,
  329. 'order_type' => !empty($data['order_type']) ? $data['order_type'] : 1,
  330. 'pay_time' => !empty($data['pay_time']) ? $data['pay_time'] : 0,
  331. 'payment_type' => !empty($data['payment_type']) ? $data['payment_type'] : 0,
  332. ];
  333. $baseParams = ['mall_id' => $mall_id, 'user_id' => $data['user_id'], 'stock_agent' => $data['stock_agent']];
  334. $goodsService = new CloudStockAgentGoodsService($baseParams);
  335. $cartService = new CloudStockAgentCartService($baseParams);
  336. $orderService = new CloudStockAgentOrderService($baseParams);
  337. $levelService = new CloudStockLevelService($baseParams);
  338. // 订单详情数据
  339. $orderDetailsData = [];
  340. $isCart = false;
  341. // 单件自提
  342. if (!empty($data['goods_id']) && !empty($data['number'])) {
  343. $orderDetailsData[] = [
  344. 'user_id' => $data['user_id'],
  345. 'mall_id' => $mall_id,
  346. 'goods_id' => $data['goods_id'],
  347. 'order_id' => 0,
  348. 'num' => $data['number']
  349. ];
  350. } else { // 购物车自提
  351. // 查询购物车数据
  352. $cartList = $cartService->getCartList();
  353. if (empty($cartList)) {
  354. self::setStaticError("未选择提货商品");
  355. return false;
  356. }
  357. foreach ($cartList as $cartItem) {
  358. if (empty($cartItem['goods_id']) || empty($cartItem['num'])) {
  359. continue;
  360. }
  361. $orderDetailsData[] = [
  362. 'user_id' => $data['user_id'],
  363. 'mall_id' => $mall_id,
  364. 'goods_id' => $cartItem['goods_id'],
  365. 'order_id' => 0,
  366. 'num' => $cartItem['num']
  367. ];
  368. }
  369. if (empty($orderDetailsData)) {
  370. self::setStaticError("提货商品异常");
  371. return false;
  372. }
  373. $isCart = true;
  374. }
  375. // 参数验证
  376. if (!$orderService->checkLimit($cartService, $levelService, $goodsService, $orderDetailsData)) {
  377. self::setStaticError($orderService->getError());
  378. return false;
  379. }
  380. // 获取设置
  381. $configs = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_CLOUD_STOCK, 'basic');
  382. //开启运费
  383. if(!empty($configs['is_enable_freight_charges'])){
  384. if ($order_params['order_type'] == 1) {
  385. $order_params['send_status'] = CloudStockEnum::PICK_ORDER_STATUS3;
  386. }
  387. // 得到运费
  388. try {
  389. $freight = $orderService->getFreight($goodsService, $mall_id, $data['user_id'], $data['addr_id'], $orderDetailsData);
  390. }catch (\Exception $e) {
  391. self::setStaticError($e->getMessage());
  392. return false;
  393. }
  394. $order_params['pay_money'] = $freight;
  395. }
  396. $transaction = \Yii::$app->db->beginTransaction();
  397. $res_order = self::setData($mall_id, $order_params);
  398. if (false === $res_order) {
  399. $transaction->rollBack();
  400. return false;
  401. }
  402. foreach ($orderDetailsData as &$orderDetail) {
  403. $orderDetail['order_id'] = $res_order->id;
  404. $orderDetail['created_at'] = $orderDetail['updated_at'] = time();
  405. }
  406. unset($orderDetail);
  407. try {
  408. \Yii::$app->db->createCommand()->batchInsert(
  409. CloudStockAgentOrderDetails::tableName(),
  410. array_keys($orderDetailsData[0]),
  411. $orderDetailsData
  412. )->execute();
  413. }catch (\Exception $e) {
  414. \Yii::$app->custom->logs(FormatHelper::exception($e, '云库存订单details写入失败'), $orderDetailsData);
  415. $transaction->rollBack();
  416. return false;
  417. }
  418. $isCart && $cartService->delAll($res_order->id);
  419. $stock_params = [
  420. 'order_info' => $orderDetailsData,
  421. 'user_id' => $data['user_id'],
  422. 'order_id' => $res_order->id,
  423. 'order_type' => CloudStockEnum::STOCK_ORDER_TYPE_REPLENISH,
  424. ];
  425. $res_handle_stock = CloudStockGoodsStockLog::stockHandleV2($mall_id, $stock_params, CloudStockEnum::STOCK_CHANGE_TYPE203);
  426. if (false === $res_handle_stock) {
  427. $transaction->rollBack();
  428. self::$static_error = CloudStockGoodsStockLog::getStaticError();
  429. return false;
  430. }
  431. $agent_user = CloudStockAgent::find()
  432. ->where(['mall_id' => $mall_id, 'user_id' => $data['user_id'], 'status' => StatusEnum::ENABLED])
  433. ->one();
  434. $agent_user->total_order += 1;
  435. $res_agent_user = $agent_user->save();
  436. if (false === $res_agent_user) {
  437. $transaction->rollBack();
  438. self::$static_error = $agent_user->getErrorMessage();
  439. return false;
  440. }
  441. $transaction->commit();
  442. CloudStockAgent::fixStock($mall_id,$data['user_id']);
  443. // 发起自提事件
  444. if($res_order->send_status != CloudStockEnum::PICK_ORDER_STATUS3){
  445. $event = new FillOrderPickEvent($mall_id);
  446. $post_data = ['id' => $res_order->id];
  447. if (MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_WANG_DIAN_TONG)) { // 如果有安装旺店通插件,那么就将发货事件添加进来
  448. $event->listeners[] = 'addons\CloudStock\common\listeners\order\WangDianTongSyncListener';
  449. }
  450. \Yii::$app->services->events->dispatch($event, $post_data, $event->listeners);
  451. $sync_params = [
  452. 'mall_id' => $mall_id,
  453. 'user_id' => $data['user_id'],
  454. 'goods_id' => array_column($orderDetailsData, 'goods_id')
  455. ];
  456. \Yii::$app->services->rabbitMq->push(RabbitMqEnum::EXCHANGE_TASK, RabbitMqEnum::TASK_QUEUE, $sync_params, self::class, 'handleSync');
  457. }
  458. return $res_order;
  459. }
  460. /**
  461. * @name:
  462. * @msg: 提货到线下赠送优惠券,异步任务处理
  463. * @param {array} $params
  464. * @return {*}
  465. */
  466. public static function handleSync(array $params = null)
  467. {
  468. try {
  469. $is_install = MallAddons::isInstall($params['mall_id'], AddonsEnum::ADDONS_NAME_COUPON);
  470. if (!$is_install) {
  471. \Yii::error(AddonsEnum::ADDONS_NAME_WECHATLIVE . ' 应用未安装');
  472. \Yii::getLogger()->flush(true);
  473. return true;
  474. }
  475. if (is_array($params['goods_id'])) {
  476. foreach ($params['goods_id'] as $goodsId) {
  477. $res = AddonsCouponUserRelate::buyGoodsGiveCoupon($params['mall_id'], $goodsId, $params['user_id']);
  478. }
  479. } else {
  480. $res = AddonsCouponUserRelate::buyGoodsGiveCoupon($params['mall_id'], $params['goods_id'], $params['user_id']);
  481. }
  482. return true;
  483. } catch (\Exception $e) {
  484. var_dump("giveCoupon:" . $e->getMessage());
  485. return true;
  486. }
  487. }
  488. /**
  489. * 导出字段数组
  490. * @Author: hua
  491. * @DateTime: 2021/10/11 18:06
  492. * @Copyright: copyright (c) 2021 广东七件事集团
  493. * @return \string[][]
  494. */
  495. public static function fieldsLists($field = null){
  496. $fields = [
  497. 'order' => '订单ID',
  498. 'user_id' => '代理商用户id',
  499. 'nickname' => '代理商昵称',
  500. 'user_mobile' => '手机号',
  501. 'created_at' => '自提时间',
  502. 'goods_name' => '商品',
  503. 'num' => '商品数量',
  504. 'name' => '收货人名字',
  505. 'mobile' => '收货人手机号码',
  506. 'address' => '收货地址',
  507. 'express_name' => '快递公司',
  508. 'express_code' => '快递编码',
  509. 'express_no' => '快递单号',
  510. 'pay_money' => '运费',
  511. 'order_no' => '订单号',
  512. 'trade_no' => '支付流水号',
  513. 'out_trade_no' => '交易流水号',
  514. 'payment_type' => '支付方式',
  515. 'pay_time' => '支付时间',
  516. 'remark' => '买家备注',
  517. 'seller_remark' => '卖家备注',
  518. 'send_status' => '状态',
  519. 'order_type' => '自提类型',
  520. ];
  521. if ($field === null) return $fields;
  522. $temp = [];
  523. foreach ($field as $val) {
  524. if (isset($fields[$val])) $temp[$val] = $fields[$val];
  525. }
  526. return $temp;
  527. }
  528. /**
  529. * 导出
  530. */
  531. public static function exportOrder(array $data) {
  532. ini_set('memory_limit', '1024M');
  533. $download_id = $data['download_id'] ?? 0;
  534. $download = Download::findOne(['id' => $download_id]);
  535. if ($download) {
  536. try {
  537. $params = json_decode($download->params, true);
  538. $filename = $download->name;
  539. $type = $download->type;
  540. $fields = $params['fields'] ?? null;
  541. $exportField = self::fieldsLists($fields);
  542. $where[] = ['mall_id' => $params['mall_id'], 'status' => [StatusEnum::DISABLED, StatusEnum::ENABLED]];
  543. if (!empty($params['keyword'])) {
  544. $user_list = User::find()->where(['or',
  545. ['id' => $params['keyword']],
  546. ['like', 'mobile', $params['keyword']],
  547. ['like', 'nickname', $params['keyword']]])->select('id')->asArray()->all();
  548. $user_id_arr = array_column($user_list, 'id');
  549. $where[] = ['user_id' => $user_id_arr];
  550. }
  551. if ($params['status'] != '' || !empty($params['express_no']) || !empty($params['out_trade_no']) || !empty($params['order_no'])) {
  552. if ($params['status'] != '') {
  553. if (abs($params['status']) == CloudStockEnum::PICK_ORDER_STATUS4) {
  554. $where[] = ['=', 'send_status', CloudStockEnum::PICK_ORDER_STATUS4];
  555. $where[] = [$params['status'] > 0 ? '=' : '>', 'cancel_admin_id', 0];
  556. } else {
  557. $where[] = ['=', 'send_status', $params['status']];
  558. }
  559. }
  560. if (!empty($params['express_no'])) {
  561. $where[] = ['=', 'express_no', $params['express_no']];
  562. }
  563. if (!empty($params['out_trade_no'])) {
  564. $where[] = ['=', 'trade_no', $params['out_trade_no']];
  565. }
  566. if (!empty($params['order_no'])) {
  567. $where[] = ['=', 'order_no', $params['order_no']];
  568. }
  569. if (!empty($params['order_type'])) {
  570. $where[] = ['order_type' => $params['order_type']];
  571. }
  572. }
  573. if (!empty($params['created_at'])) {
  574. $where[] = ['between', 'created_at', strtotime(reset($params['created_at'])), strtotime(end($params['created_at']))];
  575. }
  576. if (isset($params['receiving_info']) && $params['receiving_info'] !== '') {
  577. $where[] = [
  578. 'or',
  579. ['like', 'mobile', $params['receiving_info']],
  580. ['like', 'name', $params['receiving_info']]
  581. ];
  582. }
  583. if (!empty($params['areaIds'])) {
  584. $where[] = [
  585. 'or',
  586. ['province_id' => $params['areaIds']],
  587. ['city_id' => $params['areaIds']],
  588. ['district_id' => $params['areaIds']]
  589. ];
  590. }
  591. $wheres['order'] = 'id desc';
  592. $wheres['with'] = [
  593. 'user',
  594. 'details' => function ($query) {
  595. $query
  596. ->with(['goods' => function ($query) {
  597. $query->select('id, cover_pic, goods_name');
  598. }]);
  599. }
  600. ];
  601. $wheres['where'] = $where;
  602. $model = self::find();
  603. self::paramPack($wheres, $model);
  604. $exportList = [];
  605. $exportHeader = array_values($exportField);
  606. $send_status_map = CloudStockEnum::getAgentOrdetStatusMap();
  607. $express_list = Express::getExpresses(); // 快递
  608. $payment_list = PayTypeEnum::getMap(); // 支付类型
  609. if (!empty($express_list)) $express_list = array_column($express_list, 'name', 'code');
  610. $firstList = [];
  611. foreach ($model->asArray()->batch(1000) as $batch) {
  612. $fieldsMap = array_keys($exportField);
  613. foreach ($batch as $item) {
  614. $exportItem = [];
  615. $userFieldMap = ['nickname', 'user_mobile'];
  616. $goodsFieldMap = ['goods_name', 'num'];
  617. foreach ($fieldsMap as $fieldName) {
  618. if (in_array($fieldName, $userFieldMap)) {
  619. self::handleUserField($exportItem, $item, $fieldName);
  620. } else {
  621. if ($fieldName === 'created_at' || $fieldName === 'pay_time') {
  622. $exportItem[$fieldName] = !empty($item[$fieldName]) ? date('Y-m-d H:i:s', $item[$fieldName]) : '';
  623. } elseif ($fieldName === 'send_status') {
  624. $exportItem[$fieldName] = $item[$fieldName] == CloudStockEnum::PICK_ORDER_STATUS4 && $item['cancel_admin_id'] > 0 ? '取消自取' : self::getFieldValue($send_status_map, $item[$fieldName]);
  625. } elseif ($fieldName == 'payment_type') {
  626. $exportItem[$fieldName] = self::getFieldValue($payment_list, $item['payment_type']);
  627. } elseif ($fieldName == 'express_name') {
  628. $exportItem[$fieldName] = self::getFieldValue($express_list, $item['express_code']);
  629. } elseif ($fieldName == 'order') {
  630. $exportItem[$fieldName] = self::getFieldValue($item, 'id');
  631. } elseif ($fieldName == 'order_type') {
  632. $exportItem[$fieldName] = $item[$fieldName] == 1 ? '云仓自提' : '价差礼包自提';
  633. } else {
  634. $exportItem[$fieldName] = self::getFieldValue($item, $fieldName);
  635. }
  636. }
  637. }
  638. if (!empty($item['details'])) {
  639. foreach ($item['details'] as $detail) {
  640. foreach ($fieldsMap as $fieldName) {
  641. if (in_array($fieldName, $goodsFieldMap)) {
  642. self::handleGoodsField($exportItem, $detail, $fieldName);
  643. } elseif ($fieldName == 'pay_money') {
  644. if (!isset($firstList[$item['id']])) {
  645. $exportItem[$fieldName] = self::getFieldValue($item, $fieldName);
  646. $firstList[$item['id']] = true;
  647. } else {
  648. $exportItem[$fieldName] = '';
  649. }
  650. }
  651. }
  652. $exportList[] = $exportItem;
  653. }
  654. } else {
  655. $exportList[] = $exportItem;
  656. }
  657. }
  658. }
  659. if (!empty($exportList)) {
  660. $csv = new CsvTool();
  661. $csv->filename = $filename;
  662. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
  663. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  664. $csv->header = $exportHeader;
  665. $csv->data = $exportList;
  666. $csv->export();
  667. $csv->updateDown($download, $params['mall_id']);
  668. }
  669. return true;
  670. } catch (\Exception $e) {
  671. $download->status = 3;
  672. $res = $download->save();
  673. self::setStaticError($e->getMessage());
  674. Yii::$app->custom->logs('云库存自提订单导出失败'. $e->getLine() . $e->getMessage(), $download_id);
  675. return $e->getMessage();
  676. }
  677. }
  678. }
  679. protected static function getFieldValue($array, $key, $default = '')
  680. {
  681. return $array[$key] ?? $default;
  682. }
  683. protected static function handleUserField(&$exportItem, $item, $fieldName) {
  684. $userFieldMap = ['nickname', 'user_mobile'];
  685. if (in_array($fieldName, $userFieldMap)) {
  686. if (empty($item['user'])) {
  687. $exportItem[$fieldName] = $fieldName == 'nickname' ? '代理商不存在' : '';
  688. } else {
  689. $userMobile = $fieldName == 'user_mobile' ? 'mobile' : $fieldName;
  690. $exportItem[$fieldName] = self::getFieldValue($item['user'], $userMobile);
  691. }
  692. }
  693. }
  694. protected static function handleGoodsField(&$exportItem, $detail, $fieldName) {
  695. $goodsFieldMap = ['goods_name', 'num'];
  696. if (in_array($fieldName, $goodsFieldMap)) {
  697. if ($fieldName == 'num') {
  698. $exportItem[$fieldName] = self::getFieldValue($detail, $fieldName);
  699. } else {
  700. $exportItem[$fieldName] = self::getFieldValue($detail['goods'], $fieldName);
  701. }
  702. }
  703. }
  704. public static function viewLogistics($id,$mall_id){
  705. $agent_order = CloudStockAgentOrder::findOne(['id'=>$id,'mall_id'=>$mall_id]);
  706. if(empty($agent_order)) throw new \Exception('自提订单不存在');
  707. $traces = [];
  708. $time = time();
  709. $hour = Yii::$app->services->setting->mall->get($mall_id, 'logistics.update');// 获取更新物流时间设置
  710. if (($agent_order['table_express_status'] == StatusEnum::DISABLED && $agent_order['updated_at'] + $hour * 3600 < $time)||(empty($agent_order['list']))) {
  711. $res = self::getExpressBird($agent_order);
  712. if (!empty($res['list'])) {
  713. $logistics = json_decode($res['list'], true);
  714. if (isset($logistics['Traces'])) {
  715. $traces = $logistics['Traces'];
  716. }
  717. $agent_order->list = $res['list'];
  718. if(isset($res['table_express_status']))$agent_order->table_express_status = $res['table_express_status'];
  719. $agent_order->express_status = $res['express_status'];
  720. }
  721. $agent_order->save();
  722. }else{
  723. $logistics = json_decode($agent_order['list'],true);
  724. if(isset($logistics['Traces'])){
  725. $traces = $logistics['Traces'];
  726. }
  727. }
  728. return $traces;
  729. }
  730. public static function getExpressBird($agent_order){
  731. $express_config = Yii::$app->services->setting->mall->get($agent_order['mall_id'],'logistics');
  732. $express['id'] =$agent_order['id'];
  733. $express['express_no'] = $agent_order['express_no'];
  734. $express['express_code'] = $agent_order['express_code'];
  735. $express['customer_name'] = mb_substr($agent_order['mobile'], 0 - 4);
  736. if(empty($express_config['kdniao_mch_id'])){
  737. $express_config = Yii::$app->services->setting->mall->get($agent_order['mall_id'],'logistics');
  738. $phone = mb_substr($agent_order['mobile'], 0 - 4);
  739. $new_express = LogisticsSearch::getExpressAliyun([
  740. 'mall_id' => $agent_order['mall_id'],
  741. 'type' => 'ZTO',
  742. 'no' => $express['express_no'] . (!empty($phone) ? ":{$phone}" : ''),
  743. 'id' => $express['id']
  744. ]);
  745. return $new_express;
  746. }else{
  747. return LogisticsSearch::getExpressBird($express, $express_config);
  748. }
  749. }
  750. }