StoreIntegralOrderServices.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\activity\integral;
  12. use app\dao\activity\integral\StoreIntegralOrderDao;
  13. use app\jobs\notice\PrintJob;
  14. use app\services\activity\lottery\LuckLotteryServices;
  15. use app\services\BaseServices;
  16. use app\services\diy\DiyServices;
  17. use app\services\message\notice\NoticeSmsService;
  18. use app\services\message\SystemMessageServices;
  19. use app\services\pay\PayServices;
  20. use app\services\product\sku\StoreProductAttrValueServices;
  21. use app\services\product\sku\StoreProductVirtualServices;
  22. use app\services\serve\ServeServices;
  23. use app\services\other\ExpressServices;
  24. use app\services\system\config\ConfigServices;
  25. use app\services\system\form\SystemFormServices;
  26. use app\services\user\UserServices;
  27. use app\services\user\UserAddressServices;
  28. use app\services\user\UserBillServices;
  29. use crmeb\services\FormBuilder as Form;
  30. use crmeb\services\printer\Printer;
  31. use crmeb\services\SystemConfigService;
  32. use crmeb\traits\ServicesTrait;
  33. use crmeb\utils\Arr;
  34. use think\exception\ValidateException;
  35. use think\facade\Log;
  36. /**
  37. * Class StoreIntegralOrderServices
  38. * @package app\services\activity\integral
  39. * @mixin StoreIntegralOrderDao
  40. */
  41. class StoreIntegralOrderServices extends BaseServices
  42. {
  43. use ServicesTrait;
  44. /**
  45. * 发货类型
  46. * @var string[]
  47. */
  48. public $deliveryType = ['send' => '商家配送', 'express' => '快递配送', 'fictitious' => '虚拟发货'];
  49. /**
  50. * StoreIntegralOrderServices constructor.
  51. * @param StoreIntegralOrderDao $dao
  52. */
  53. public function __construct(StoreIntegralOrderDao $dao)
  54. {
  55. $this->dao = $dao;
  56. }
  57. /**
  58. * 获取列表
  59. * @param array $where
  60. * @return array
  61. * @throws \think\db\exception\DataNotFoundException
  62. * @throws \think\db\exception\DbException
  63. * @throws \think\db\exception\ModelNotFoundException
  64. */
  65. public function getOrderList(array $where, array $field = ['*'], array $with = [])
  66. {
  67. [$page, $limit] = $this->getPageValue();
  68. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with);
  69. $count = $this->dao->count($where);
  70. $data = $this->tidyOrderList($data);
  71. $batch_url = "file/upload/1";
  72. return compact('data', 'count', 'batch_url');
  73. }
  74. /**
  75. * 获取导出数据
  76. * @param array $where
  77. * @param int $limit
  78. * @return array
  79. * @throws \think\db\exception\DataNotFoundException
  80. * @throws \think\db\exception\DbException
  81. * @throws \think\db\exception\ModelNotFoundException
  82. */
  83. public function getExportList(array $where, int $limit = 0)
  84. {
  85. if ($limit) {
  86. [$page] = $this->getPageValue();
  87. } else {
  88. [$page, $limit] = $this->getPageValue();
  89. }
  90. $data = $this->dao->getOrderList($where, ['*'], $page, $limit);
  91. $data = $this->tidyOrderList($data);
  92. return $data;
  93. }
  94. /**
  95. * 前端订单列表
  96. * @param array $where
  97. * @param array|string[] $field
  98. * @param array $with
  99. * @return array
  100. * @throws \think\db\exception\DataNotFoundException
  101. * @throws \think\db\exception\DbException
  102. * @throws \think\db\exception\ModelNotFoundException
  103. */
  104. public function getOrderApiList(array $where, array $field = ['*'], array $with = [])
  105. {
  106. [$page, $limit] = $this->getPageValue();
  107. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with);
  108. $data = $this->tidyOrderList($data);
  109. return $data;
  110. }
  111. /**
  112. * 订单详情数据格式化
  113. * @param $order
  114. * @return mixed
  115. */
  116. public function tidyOrder($order)
  117. {
  118. $order['_add_time'] = $order['add_time'] = date('Y-m-d H:i:s', $order['add_time']);
  119. if ($order['status'] == 1) {
  120. $order['status_name'] = '未发货';
  121. } else if ($order['status'] == 2) {
  122. $order['status_name'] = '待收货';
  123. } else if ($order['status'] == 3) {
  124. $order['status_name'] = '已完成';
  125. }
  126. return $order;
  127. }
  128. /**
  129. * 数据转换
  130. * @param array $data
  131. * @return array
  132. */
  133. public function tidyOrderList(array $data)
  134. {
  135. foreach ($data as &$item) {
  136. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  137. if ($item['status'] == 1) {
  138. $item['status_name'] = '未发货';
  139. } else if ($item['status'] == 2) {
  140. $item['status_name'] = '待收货';
  141. } else if ($item['status'] == 3) {
  142. $item['status_name'] = '已完成';
  143. }
  144. }
  145. return $data;
  146. }
  147. /**
  148. * 创建订单
  149. * @param $uid
  150. * @param $addressId
  151. * @param string $mark
  152. * @param $user
  153. * @param $num
  154. * @param $productInfo
  155. * @throws \Exception
  156. */
  157. public function createOrder($uid, $addressId, $payType, $mark, $userInfo, $num, $productInfo, $customForm)
  158. {
  159. if ($productInfo['product_type'] == 0 && !$addressId) {
  160. throw new ValidateException('请选择收货地址!');
  161. }
  162. if ($addressId) {
  163. /** @var UserAddressServices $addressServices */
  164. $addressServices = app()->make(UserAddressServices::class);
  165. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  166. throw new ValidateException('地址选择有误!');
  167. $addressInfo = $addressInfo->toArray();
  168. } else {
  169. $addressInfo = [];
  170. }
  171. $total_price = bcmul($productInfo['attrInfo']['price'], $num, 2);
  172. $total_integral = bcmul($productInfo['attrInfo']['integral'], $num, 2);
  173. if ($total_integral > $userInfo['integral']) throw new ValidateException('积分不足!');
  174. if ($total_price <= 0) {
  175. $paid = 1;
  176. $orderInfo['pay_time'] = time();
  177. $payType = 'integral';
  178. } else {
  179. $paid = 0;
  180. }
  181. $productInfo['cart_num'] = $num;
  182. $orderInfo = [
  183. 'uid' => $uid,
  184. 'order_id' => $this->getNewOrderId(),
  185. 'real_name' => $addressInfo['real_name'] ?? '',
  186. 'user_phone' => $addressInfo['phone'] ?? '',
  187. 'user_address' => $addressInfo ? $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'] : '',
  188. 'product_id' => $productInfo['id'],
  189. 'image' => $productInfo['attrInfo']['image'] ?? '',
  190. 'store_name' => $productInfo['title'],
  191. 'suk' => $productInfo['attrInfo']['suk'] ?? '',
  192. 'unique' => $productInfo['attrInfo']['unique'] ?? '',
  193. 'total_num' => $num,
  194. 'price' => $productInfo['attrInfo']['price'] ?? '',
  195. 'total_price' => $total_price,
  196. 'integral' => $productInfo['attrInfo']['integral'] ?? '',
  197. 'total_integral' => $total_integral,
  198. 'paid' => $paid,
  199. 'pay_type' => $payType,
  200. 'add_time' => time(),
  201. 'status' => 1,
  202. 'mark' => $mark,
  203. 'channel_type' => $userInfo['user_type'],
  204. 'product_type' => $productInfo['product_type'],
  205. 'custom_form' => json_encode($customForm),
  206. 'cart_info' => json_encode([$productInfo])
  207. ];
  208. $order = $this->transaction(function () use ($orderInfo, $userInfo, $productInfo, $uid, $num, $total_integral, $total_price) {
  209. //创建订单
  210. $order = $this->dao->save($orderInfo);
  211. if (!$order) {
  212. throw new ValidateException('订单生成失败!');
  213. }
  214. //扣库存
  215. $this->decGoodsStock($productInfo, $num);
  216. //减积分
  217. $this->deductIntegral($userInfo, $total_integral, (int)$userInfo['uid'], $order->id);
  218. if ($total_price <= 0) {
  219. //卡密发放
  220. if ($orderInfo['product_type']) {
  221. $this->sendCard((int)$order->id);
  222. //修改订单状态
  223. $this->dao->update((int)$order->id, ['status' => 3]);
  224. }
  225. }
  226. return $order;
  227. });
  228. /** @var StoreIntegralOrderStatusServices $statusService */
  229. $statusService = app()->make(StoreIntegralOrderStatusServices::class);
  230. $statusService->save([
  231. 'oid' => $order['id'],
  232. 'change_type' => 'cache_key_create_order',
  233. 'change_message' => '订单生成',
  234. 'change_time' => time()
  235. ]);
  236. return $order;
  237. }
  238. /**
  239. * 抵扣积分
  240. * @param array $userInfo
  241. * @param bool $useIntegral
  242. * @param array $priceData
  243. * @param int $uid
  244. * @param string $key
  245. */
  246. public function deductIntegral(array $userInfo, $priceIntegral, int $uid, string $orderId)
  247. {
  248. $res2 = true;
  249. if ($userInfo['integral'] > 0) {
  250. /** @var UserServices $userServices */
  251. $userServices = app()->make(UserServices::class);
  252. if ($userInfo['integral'] > $priceIntegral) {
  253. $integral = bcsub((string)$userInfo['integral'], (string)$priceIntegral);
  254. } else {
  255. $integral = 0;
  256. }
  257. $res2 = $userServices->update($uid, ['integral' => $integral]);
  258. /** @var UserBillServices $userBillServices */
  259. $userBillServices = app()->make(UserBillServices::class);
  260. $res3 = $userBillServices->income('storeIntegral_use_integral', $uid, (int)$priceIntegral, (int)$integral, $orderId);
  261. $res2 = $res2 && false != $res3;
  262. }
  263. if (!$res2) {
  264. throw new ValidateException('使用积分抵扣失败!');
  265. }
  266. }
  267. /**未支付积分订单退积分
  268. * @return bool|void
  269. * @throws \think\db\exception\DataNotFoundException
  270. * @throws \think\db\exception\DbException
  271. * @throws \think\db\exception\ModelNotFoundException
  272. */
  273. public function rebatePointsOrders()
  274. {
  275. $where['is_del'] = 0;
  276. $where['is_system_del'] = 0;
  277. $where['paid'] = 0;
  278. $where['is_price'] = 1;
  279. $where['is_integral'] = 1;
  280. $list = $this->dao->getIntegralOrderList($where);
  281. //系统预设取消订单时间段
  282. $keyValue = ['rebate_points_orders_time', 'order_cancel_time'];
  283. //获取配置
  284. $systemValue = SystemConfigService::more($keyValue);
  285. //格式化数据
  286. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  287. $order_cancel_time = $systemValue['rebate_points_orders_time'] ?: $systemValue['order_cancel_time'];
  288. /** @var UserServices $userServices */
  289. $userServices = app()->make(UserServices::class);
  290. /** @var UserBillServices $userBillServices */
  291. $userBillServices = app()->make(UserBillServices::class);
  292. $order_cancel_time = (int)bcmul((string)$order_cancel_time, '3600', 0);
  293. foreach ($list as $key => $item) {
  294. if (($item['add_time'] + $order_cancel_time) < time()) {
  295. try {
  296. $this->transaction(function () use ($item, $userServices, $userBillServices) {
  297. $user_integral = $userServices->value(['uid' => $item['uid']], 'integral');
  298. $res = $userServices->incUpdate(['uid' => $item['uid']], 'integral', (int)$item['integral']);
  299. $integral = bcadd((string)$user_integral, (string)$item['integral']);
  300. $res1 = $userBillServices->income('integral_refund', $item['uid'], (int)$item['integral'], (int)$integral, $item['id']);
  301. //修改订单状态
  302. $res = $res && $res1 && $this->dao->update($item['id'], ['is_del' => 1, 'is_system_del' => 1, 'mark' => '积分订单未支付已超过系统预设时间']);
  303. });
  304. } catch (\Throwable $e) {
  305. Log::error('未支付积分订单退积分失败,失败原因:' . $e->getMessage(), $e->getTrace());
  306. }
  307. }
  308. }
  309. return true;
  310. }
  311. /**
  312. * 扣库存
  313. * @param array $cartInfo
  314. * @param int $combinationId
  315. * @param int $seckillId
  316. * @param int $bargainId
  317. */
  318. public function decGoodsStock(array $productInfo, int $num)
  319. {
  320. $res5 = true;
  321. /** @var StoreIntegralServices $StoreIntegralServices */
  322. $StoreIntegralServices = app()->make(StoreIntegralServices::class);
  323. try {
  324. $res5 = $res5 && $StoreIntegralServices->decIntegralStock((int)$num, $productInfo['attrInfo']['product_id'] ?? 0, $productInfo['attrInfo']['unique'] ?? '');
  325. if (!$res5) {
  326. throw new ValidateException('库存不足!');
  327. }
  328. } catch (\Throwable $e) {
  329. throw new ValidateException('库存不足!');
  330. }
  331. }
  332. /**
  333. * 发送卡密
  334. * @param int $id
  335. * @param array $orderInfo
  336. * @return bool
  337. */
  338. public function sendCard(int $id, $orderInfo = [])
  339. {
  340. if (!$id && !$orderInfo) return false;
  341. if (!$orderInfo) {
  342. $orderInfo = $this->dao->get($id);
  343. }
  344. if ($orderInfo['fictitious'] && $orderInfo['fictitious'] == 'fictitious') {
  345. return true;
  346. }
  347. try {
  348. switch ($orderInfo['product_type']) {
  349. case 1:
  350. /** @var SystemMessageServices $SystemMessageServices */
  351. $SystemMessageServices = app()->make(SystemMessageServices::class);
  352. /** @var StoreIntegralOrderStatusServices $statusService */
  353. $statusService = app()->make(StoreIntegralOrderStatusServices::class);
  354. $orderInfo['cart_info'] = is_string($orderInfo['cart_info']) ? json_decode($orderInfo['cart_info'], true) : $orderInfo['cart_info'];
  355. $title = $content = $disk_info = $virtual_info = '';
  356. $unique = $orderInfo['unique'];
  357. //活动订单共用原商品规格卡密
  358. /** @var StoreProductAttrValueServices $skuValueServices */
  359. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  360. $attrValue = $skuValueServices->getUniqueByActivityUnique($unique, (int)$orderInfo['product_id'], 4, ['unique', 'disk_info']);
  361. if ($attrValue) {
  362. $disk_info = $attrValue['disk_info'] ?? '';
  363. $unique = $attrValue['unique'] ?? '';
  364. }
  365. if ($disk_info) {
  366. $title = '虚拟密钥发放';
  367. $content = '您购买的密钥商品已支付成功,';
  368. if ($orderInfo['total_price'] > 0) {
  369. $content .= '支付金额' . $orderInfo['total_price'] . '元,';
  370. } elseif ($orderInfo['total_integral'] > 0) {
  371. $content .= '支付积分' . $orderInfo['total_integral'];
  372. }
  373. $content .= ',订单号:' . $orderInfo['order_id'] . ',密钥:' . $disk_info . ',感谢您的光临!';
  374. $virtual_info = '密钥自动发放:' . $disk_info;
  375. $value = '密钥:' . $disk_info;
  376. // $remark = '密钥自动发放:' . $disk_info;
  377. } else {
  378. /** @var StoreProductVirtualServices $virtualService */
  379. $virtualService = app()->make(StoreProductVirtualServices::class);
  380. $cardList = $virtualService->getOrderCardList(['store_id' => $orderInfo['store_id'], 'attr_unique' => $unique, 'uid' => 0], (int)$orderInfo['total_num']);
  381. $title = '虚拟卡密发放';
  382. $virtual_info = '卡密已自动发放';
  383. $value = '';
  384. // $remark = '卡密已自动发放';
  385. if ($cardList) {
  386. $content = '您购买的密钥商品已支付成功,';
  387. if ($orderInfo['total_price'] > 0) {
  388. $content .= '支付金额' . $orderInfo['total_price'] . '元,';
  389. } elseif ($orderInfo['total_integral'] > 0) {
  390. $content .= '支付积分' . $orderInfo['total_integral'];
  391. }
  392. $content .= ',订单号:' . $orderInfo['order_id'];
  393. $update = [];
  394. $update['order_id'] = $orderInfo['order_id'];
  395. $update['uid'] = $orderInfo['uid'];
  396. $update['order_type'] = 2;
  397. foreach ($cardList as $virtual) {
  398. $virtualService->update($virtual['id'], $update);
  399. $content .= ',卡号:' . $virtual['card_no'] . ';密码:' . $virtual['card_pwd'] . "\n";
  400. $virtual_info .= ',卡号:' . $virtual['card_no'] . ';密码:' . $virtual['card_pwd'] . ';';
  401. $value .= '卡号:' . $virtual['card_no'] . ';密码:' . $virtual['card_pwd'];
  402. // $remark .= ',卡号:' . $virtual['card_no'] . ';密码:' . $virtual['card_pwd'] . ';';
  403. }
  404. $content .= ',感谢您的光临!';
  405. }
  406. }
  407. //修改订单虚拟备注
  408. $this->dao->update(['id' => $orderInfo['id']], ['status' => 1, 'delivery_type' => 'fictitious', 'virtual_info' => $virtual_info]);
  409. $data['id'] = $orderInfo['id'];
  410. $data['uid'] = $orderInfo['uid'];
  411. $data['order_id'] = $orderInfo['order_id'];
  412. $data['title'] = $title;
  413. $data['value'] = $value;
  414. $data['content'] = $content;
  415. $data['is_integral'] = 1;
  416. event('notice.notice', [$data, 'kami_deliver_goods_code']);
  417. $statusService->save([
  418. 'oid' => $orderInfo['id'],
  419. 'change_type' => 'delivery_fictitious',
  420. 'change_message' => '卡密自动发货',
  421. 'change_time' => time()
  422. ]);
  423. break;
  424. }
  425. } catch (\Throwable $e) {
  426. Log::error('订单虚拟商品自动发放失败,原因:' . $e->getMessage());
  427. }
  428. return true;
  429. }
  430. /**
  431. * 使用雪花算法生成订单ID
  432. * @return string
  433. * @throws \Exception
  434. */
  435. public function getNewOrderId(string $prefix = 'wx')
  436. {
  437. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  438. //32位
  439. if (PHP_INT_SIZE == 4) {
  440. $id = abs($snowflake->id());
  441. } else {
  442. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->id();
  443. }
  444. return $prefix . $id;
  445. }
  446. /**
  447. *获取订单数量
  448. * @param array $where
  449. * @return mixed
  450. */
  451. public function orderCount(array $where)
  452. {
  453. //全部订单
  454. $data['statusAll'] = (string)$this->dao->count($where + ['is_system_del' => 0]);
  455. //未发货
  456. $data['unshipped'] = (string)$this->dao->count($where + ['status' => 1, 'is_system_del' => 0]);
  457. //待收货
  458. $data['untake'] = (string)$this->dao->count($where + ['status' => 2, 'is_system_del' => 0]);
  459. //待评价
  460. // $data['unevaluate'] = (string)$this->dao->count(['status' => 3, 'time' => $where['time'], 'is_system_del' => 0]);
  461. //交易完成
  462. $data['complete'] = (string)$this->dao->count($where + ['status' => 3, 'is_system_del' => 0]);
  463. return $data;
  464. }
  465. /**
  466. * 打印订单
  467. * @param int $id
  468. * @return bool|mixed|string
  469. * @throws \think\db\exception\DataNotFoundException
  470. * @throws \think\db\exception\DbException
  471. * @throws \think\db\exception\ModelNotFoundException
  472. */
  473. public function orderPrint(int $id)
  474. {
  475. $order = $this->dao->get($id);
  476. if (!$order) {
  477. throw new ValidateException('订单没有查到,无法打印!');
  478. }
  479. /** @var ConfigServices $configServices */
  480. $configServices = app()->make(ConfigServices::class);
  481. [$switch, $name, $configData] = $configServices->getPrintingConfig();
  482. if (!$switch) {
  483. throw new ValidateException('请先开启小票打印');
  484. }
  485. foreach ($configData as $value) {
  486. if (!$value) {
  487. throw new ValidateException('请先配置小票打印开发者');
  488. }
  489. }
  490. $printer = new Printer($name, $configData);
  491. $res = $printer->setIntegralPrinterContent([
  492. 'name' => sys_config('site_name'),
  493. 'orderInfo' => is_object($order) ? $order->toArray() : $order,
  494. ])->startPrinter();
  495. if (!$res) {
  496. throw new ValidateException($printer->getError());
  497. }
  498. return $res;
  499. }
  500. /**
  501. * 获取订单确认数据
  502. * @param array $user
  503. * @param $cartId
  504. * @return mixed
  505. */
  506. public function getOrderConfirmData(array $user, $unique, $num)
  507. {
  508. /** @var StoreProductAttrValueServices $StoreProductAttrValueServices */
  509. $StoreProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
  510. $attrValue = $StoreProductAttrValueServices->uniqueByField($unique, 4);
  511. if (!$attrValue) {
  512. throw new ValidateException('请重新选择商品规格');
  513. }
  514. /** @var StoreIntegralServices $storeIntrgralServices */
  515. $storeIntrgralServices = app()->make(StoreIntegralServices::class);
  516. $productInfo = $storeIntrgralServices->getIntegralOne((int)$attrValue['product_id']);
  517. if (!$productInfo) {
  518. throw new ValidateException('该商品已下架');
  519. }
  520. if ($productInfo['once_num'] < $num && $productInfo['once_num'] != -1) {
  521. throw new ValidateException('每个订单限购' . $productInfo['once_num'] . '件');
  522. }
  523. $data = [];
  524. $attrValue = is_object($attrValue) ? $attrValue->toArray() : $attrValue;
  525. $productInfo['attrInfo'] = $attrValue;
  526. $productInfo['unique'] = $attrValue['unique'];
  527. $productInfo['store_name'] = $productInfo['title'];
  528. $data['now_money'] = $user['now_money'];
  529. $data['integral'] = $user['integral'];
  530. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  531. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  532. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  533. $data['num'] = $num;
  534. $data['total_integral'] = bcmul($num, $attrValue['integral'], 0);
  535. $data['total_price'] = bcmul($num, $attrValue['price'], 2);
  536. $data['productInfo'] = $productInfo;
  537. $data['custom_form'] = [];
  538. if (isset($productInfo['system_form_id']) && $productInfo['system_form_id']) {
  539. /** @var SystemFormServices $systemFormServices */
  540. $systemFormServices = app()->make(SystemFormServices::class);
  541. $formInfo = $systemFormServices->value(['id' => $productInfo['system_form_id']], 'value');
  542. if ($formInfo) {
  543. $data['custom_form'] = is_string($formInfo) ? json_decode($formInfo, true) : $formInfo;
  544. }
  545. }
  546. return $data;
  547. }
  548. /**
  549. * 删除订单
  550. * @param $uni
  551. * @param $uid
  552. * @return bool
  553. */
  554. public function removeOrder(string $order_id, int $uid)
  555. {
  556. $order = $this->getUserOrderDetail($order_id, $uid);
  557. if ($order['status'] != 3)
  558. throw new ValidateException('该订单无法删除!');
  559. $order->is_del = 1;
  560. /** @var StoreIntegralOrderStatusServices $statusService */
  561. $statusService = app()->make(StoreIntegralOrderStatusServices::class);
  562. $res = $statusService->save([
  563. 'oid' => $order['id'],
  564. 'change_type' => 'remove_order',
  565. 'change_message' => '删除订单',
  566. 'change_time' => time()
  567. ]);
  568. if ($order->save() && $res) {
  569. return true;
  570. } else
  571. throw new ValidateException('订单删除失败!');
  572. }
  573. /**
  574. * 订单发货
  575. * @param int $id
  576. * @param array $data
  577. * @return bool
  578. */
  579. public function delivery(int $id, array $data)
  580. {
  581. $orderInfo = $this->dao->get($id);
  582. if (!$orderInfo) {
  583. throw new ValidateException('订单未能查到,不能发货!');
  584. }
  585. if ($orderInfo['paid'] != 1) {
  586. throw new ValidateException('订单未支付');
  587. }
  588. if ($orderInfo->is_del) {
  589. throw new ValidateException('订单已删除,不能发货!');
  590. }
  591. if ($orderInfo->status != 1) {
  592. throw new ValidateException('订单已发货请勿重复操作!');
  593. }
  594. $type = (int)$data['type'];
  595. unset($data['type']);
  596. switch ($type) {
  597. case 1:
  598. //发货
  599. $this->orderDeliverGoods($id, $data, $orderInfo);
  600. break;
  601. case 2:
  602. $this->orderDelivery($id, $data, $orderInfo);
  603. break;
  604. case 3:
  605. $this->orderVirtualDelivery($id, $data, $orderInfo);
  606. break;
  607. default:
  608. throw new ValidateException('暂时不支持其他发货类型');
  609. }
  610. // 小程序订单管理
  611. event('order.routine.shipping', ['integral', $orderInfo, $type, $data['delivery_id'], $data['delivery_name']]);
  612. return true;
  613. }
  614. /**
  615. * 虚拟发货
  616. * @param int $id
  617. * @param array $data
  618. */
  619. public function orderVirtualDelivery(int $id, array $data)
  620. {
  621. $data['delivery_type'] = 'fictitious';
  622. $data['status'] = 2;
  623. unset($data['sh_delivery_name'], $data['sh_delivery_id'], $data['delivery_name'], $data['delivery_id']);
  624. //保存信息
  625. /** @var StoreIntegralOrderStatusServices $services */
  626. $services = app()->make(StoreIntegralOrderStatusServices::class);
  627. $this->transaction(function () use ($id, $data, $services) {
  628. $this->dao->update($id, $data);
  629. $services->save([
  630. 'oid' => $id,
  631. 'change_type' => 'delivery_fictitious',
  632. 'change_message' => '已虚拟发货',
  633. 'change_time' => time()
  634. ]);
  635. });
  636. }
  637. /**
  638. * 订单配送
  639. * @param int $id
  640. * @param array $data
  641. */
  642. public function orderDelivery(int $id, array $data, $orderInfo)
  643. {
  644. $data['delivery_type'] = 'send';
  645. $data['delivery_name'] = $data['sh_delivery_name'];
  646. $data['delivery_id'] = $data['sh_delivery_id'];
  647. $data['delivery_uid'] = $data['sh_delivery_uid'];
  648. //获取核销码
  649. $data['verify_code'] = $this->getStoreCode();
  650. unset($data['sh_delivery_name'], $data['sh_delivery_id'], $data['sh_delivery_uid']);
  651. if (!$data['delivery_name']) {
  652. throw new ValidateException('请输入送货人姓名');
  653. }
  654. if (!$data['delivery_id']) {
  655. throw new ValidateException('请输入送货人电话号码');
  656. }
  657. if (!$data['delivery_uid']) {
  658. throw new ValidateException('请输入送货人信息');
  659. }
  660. if (!check_phone($data['delivery_id'])) {
  661. throw new ValidateException('请输入正确的送货人电话号码');
  662. }
  663. $data['status'] = 2;
  664. $orderInfo->delivery_type = $data['delivery_type'];
  665. $orderInfo->delivery_name = $data['delivery_name'];
  666. $orderInfo->delivery_id = $data['delivery_id'];
  667. $orderInfo->status = $data['status'];
  668. /** @var StoreIntegralOrderStatusServices $services */
  669. $services = app()->make(StoreIntegralOrderStatusServices::class);
  670. $this->transaction(function () use ($id, $data, $services) {
  671. $this->dao->update($id, $data);
  672. //记录订单状态
  673. $services->save([
  674. 'oid' => $id,
  675. 'change_type' => 'delivery',
  676. 'change_time' => time(),
  677. 'change_message' => '已配送 发货人:' . $data['delivery_name'] . ' 发货人电话:' . $data['delivery_id']
  678. ]);
  679. });
  680. return true;
  681. }
  682. /**
  683. * 订单快递发货
  684. * @param int $id
  685. * @param array $data
  686. */
  687. public function orderDeliverGoods(int $id, array $data, $orderInfo)
  688. {
  689. if (!$data['delivery_name']) {
  690. throw new ValidateException('请选择快递公司');
  691. }
  692. $data['delivery_type'] = 'express';
  693. if ($data['express_record_type'] == 2) {//电子面单
  694. if (!$data['delivery_code']) {
  695. throw new ValidateException('快递公司编缺失');
  696. }
  697. if (!$data['express_temp_id']) {
  698. throw new ValidateException('请选择电子面单模板');
  699. }
  700. if (!$data['to_name']) {
  701. throw new ValidateException('请填写寄件人姓名');
  702. }
  703. if (!$data['to_tel']) {
  704. throw new ValidateException('请填写寄件人电话');
  705. }
  706. if (!$data['to_addr']) {
  707. throw new ValidateException('请填写寄件人地址');
  708. }
  709. /** @var ServeServices $ServeServices */
  710. $ServeServices = app()->make(ServeServices::class);
  711. $expData['com'] = $data['delivery_code'];
  712. $expData['to_name'] = $orderInfo->real_name;
  713. $expData['to_tel'] = $orderInfo->user_phone;
  714. $expData['to_addr'] = $orderInfo->user_address;
  715. $expData['from_name'] = $data['to_name'];
  716. $expData['from_tel'] = $data['to_tel'];
  717. $expData['from_addr'] = $data['to_addr'];
  718. $expData['siid'] = sys_config('config_export_siid');
  719. $expData['temp_id'] = $data['express_temp_id'];
  720. $expData['count'] = $orderInfo->total_num;
  721. $expData['cargo'] = $orderInfo->store_name . '(' . $orderInfo->suk . ')*' . $orderInfo->total_num;
  722. $expData['order_id'] = $orderInfo->order_id;
  723. if (!sys_config('config_export_open', 0)) {
  724. throw new ValidateException('系统通知:电子面单已关闭,请选择其他发货方式!');
  725. }
  726. $dump = $ServeServices->express()->dump($expData);
  727. $orderInfo->delivery_id = $dump['kuaidinum'];
  728. $data['express_dump'] = json_encode([
  729. 'com' => $expData['com'],
  730. 'from_name' => $expData['from_name'],
  731. 'from_tel' => $expData['from_tel'],
  732. 'from_addr' => $expData['from_addr'],
  733. 'temp_id' => $expData['temp_id'],
  734. 'cargo' => $expData['cargo'],
  735. ]);
  736. $data['delivery_id'] = $dump['kuaidinum'];
  737. } else {
  738. if (!$data['delivery_id']) {
  739. throw new ValidateException('请输入快递单号');
  740. }
  741. $orderInfo->delivery_id = $data['delivery_id'];
  742. }
  743. $data['status'] = 2;
  744. $orderInfo->delivery_type = $data['delivery_type'];
  745. $orderInfo->delivery_name = $data['delivery_name'];
  746. $orderInfo->status = $data['status'];
  747. /** @var StoreIntegralOrderStatusServices $services */
  748. $services = app()->make(StoreIntegralOrderStatusServices::class);
  749. $this->transaction(function () use ($id, $data, $services) {
  750. $res = $this->dao->update($id, $data);
  751. $res = $res && $services->save([
  752. 'oid' => $id,
  753. 'change_time' => time(),
  754. 'change_type' => 'delivery_goods',
  755. 'change_message' => '已发货 快递公司:' . $data['delivery_name'] . ' 快递单号:' . $data['delivery_id']
  756. ]);
  757. if (!$res) {
  758. throw new ValidateException('发货失败:数据保存不成功');
  759. }
  760. });
  761. return true;
  762. }
  763. /**
  764. * 核销订单生成核销码
  765. * @return false|string
  766. */
  767. public function getStoreCode()
  768. {
  769. mt_srand();
  770. [$msec, $sec] = explode(' ', microtime());
  771. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  772. if (strlen($num) < 12)
  773. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  774. else
  775. $num = substr($num, 0, 12);
  776. if ($this->dao->count(['verify_code' => $num])) {
  777. return $this->getStoreCode();
  778. }
  779. return $num;
  780. }
  781. /**
  782. * 获取修改配送信息表单结构
  783. * @param int $id
  784. * @return array
  785. * @throws \FormBuilder\Exception\FormBuilderException
  786. */
  787. public function distributionForm(int $id)
  788. {
  789. if (!$orderInfo = $this->dao->get($id))
  790. throw new ValidateException('订单不存在');
  791. $f[] = Form::input('order_id', '订单号', $orderInfo->getData('order_id'))->disabled(1);
  792. switch ($orderInfo['delivery_type']) {
  793. case 'send':
  794. $f[] = Form::input('delivery_name', '送货人姓名', $orderInfo->getData('delivery_name'))->required('请输入送货人姓名');
  795. $f[] = Form::input('delivery_id', '送货人电话', $orderInfo->getData('delivery_id'))->required('请输入送货人电话');
  796. break;
  797. case 'express':
  798. /** @var ExpressServices $expressServices */
  799. $expressServices = app()->make(ExpressServices::class);
  800. $f[] = Form::select('delivery_name', '快递公司', (string)$orderInfo->getData('delivery_name'))->setOptions(array_map(function ($item) {
  801. $item['value'] = $item['label'];
  802. return $item;
  803. }, $expressServices->expressSelectForm(['is_show' => 1])))->required('请选择快递公司');
  804. $f[] = Form::input('delivery_id', '快递单号', $orderInfo->getData('delivery_id'))->required('请填写快递单号');
  805. break;
  806. }
  807. return create_form('配送信息', $f, $this->url('/marketing/integral/order/distribution/' . $id), 'PUT');
  808. }
  809. /**
  810. * 用户订单收货
  811. * @param string $order_id
  812. * @param int $uid
  813. * @return array|\think\Model
  814. * @throws \think\db\exception\DataNotFoundException
  815. * @throws \think\db\exception\DbException
  816. * @throws \think\db\exception\ModelNotFoundException
  817. */
  818. public function takeOrder(string $order_id, int $uid)
  819. {
  820. $order = $this->dao->getUserOrderDetail($order_id, $uid);
  821. if (!$order) {
  822. throw new ValidateException('订单不存在!');
  823. }
  824. if ($order['status'] != 2) {
  825. throw new ValidateException('订单状态错误!');
  826. }
  827. $order->status = 3;
  828. /** @var StoreIntegralOrderStatusServices $statusService */
  829. $statusService = app()->make(StoreIntegralOrderStatusServices::class);
  830. $res = $order->save() && $statusService->save([
  831. 'oid' => $order['id'],
  832. 'change_type' => 'user_take_delivery',
  833. 'change_message' => '用户已收货',
  834. 'change_time' => time()
  835. ]);
  836. if (!$res) {
  837. throw new ValidateException('收货失败');
  838. }
  839. return $order;
  840. }
  841. /**
  842. * 修改配送信息
  843. * @param int $id 订单id
  844. * @return mixed
  845. */
  846. public function updateDistribution(int $id, array $data)
  847. {
  848. $order = $this->dao->get($id);
  849. if (!$order) {
  850. throw new ValidateException('数据不存在!');
  851. }
  852. switch ($order['delivery_type']) {
  853. case 'send':
  854. if (!$data['delivery_name']) {
  855. throw new ValidateException('请输入送货人姓名');
  856. }
  857. if (!$data['delivery_id']) {
  858. throw new ValidateException('请输入送货人电话号码');
  859. }
  860. if (!check_phone($data['delivery_id'])) {
  861. throw new ValidateException('请输入正确的送货人电话号码');
  862. }
  863. break;
  864. case 'express':
  865. if (!$data['delivery_name']) {
  866. throw new ValidateException('请选择快递公司');
  867. }
  868. if (!$data['delivery_id']) {
  869. throw new ValidateException('请输入快递单号');
  870. }
  871. break;
  872. default:
  873. throw new ValidateException('未发货,请先发货再修改配送信息');
  874. break;
  875. }
  876. /** @var StoreIntegralOrderStatusServices $statusService */
  877. $statusService = app()->make(StoreIntegralOrderStatusServices::class);
  878. $statusService->save([
  879. 'oid' => $id,
  880. 'change_type' => 'distribution',
  881. 'change_message' => '修改发货信息为' . $data['delivery_name'] . '号' . $data['delivery_id'],
  882. 'change_time' => time()
  883. ]);
  884. return $this->dao->update($id, $data);
  885. }
  886. /**
  887. * 支付成功
  888. * @param array $orderInfo
  889. * @param string $paytype
  890. * @return bool
  891. */
  892. public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
  893. {
  894. $updata = ['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()];
  895. if ($other && isset($other['trade_no'])) {
  896. $updata['trade_no'] = $other['trade_no'];
  897. }
  898. $res1 = $this->dao->update($orderInfo['id'], $updata);
  899. if ($res1) {
  900. //卡密发放
  901. if ($orderInfo['product_type']) {
  902. $this->sendCard((int)$orderInfo['id']);
  903. //修改订单状态
  904. $this->dao->update((int)$orderInfo['id'], ['status' => 3]);
  905. }
  906. }
  907. $res = $res1;
  908. PrintJob::dispatchDo('IntegralDoJob', [$orderInfo['id']]);
  909. return false !== $res;
  910. }
  911. /**
  912. * 获取全部积分商品订单
  913. * @return array
  914. * @throws \think\db\exception\DataNotFoundException
  915. * @throws \think\db\exception\DbException
  916. * @throws \think\db\exception\ModelNotFoundException
  917. */
  918. public function getAllIntegralOrderList(array $where)
  919. {
  920. $list = $this->dao->getIntegralOrderList($where);
  921. return $list;
  922. }
  923. }