Order.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. namespace addons\unishop\model;
  3. use addons\unishop\extend\Hashids;
  4. use addons\unishop\extend\Snowflake;
  5. use think\Hook;
  6. use think\Model;
  7. use traits\model\SoftDelete;
  8. /**
  9. * 收货地址模型
  10. * Class Favorite
  11. * @package addons\unishop\model
  12. */
  13. class Order extends Model
  14. {
  15. use SoftDelete;
  16. protected $deleteTime = 'deletetime';
  17. // 表名
  18. protected $name = 'unishop_order';
  19. // 开启自动写入时间戳字段
  20. protected $autoWriteTimestamp = 'int';
  21. // 定义时间戳字段名
  22. protected $createTime = 'createtime';
  23. protected $updateTime = 'updatetime';
  24. // 隐藏属性
  25. protected $hidden = [
  26. 'id',
  27. 'user_id'
  28. ];
  29. // 支付类型
  30. const PAY_ONLINE = 1; // 在线支付
  31. const PAY_OFFLINE = 2; // 线下支付 或 货到付款
  32. const PAY_WXPAY = 3; // 微信支付
  33. const PAY_ALIPAY = 4; // 支付宝支付
  34. // 订单状态
  35. const STATUS_NORMAL = 1; // 正常
  36. const STATUS_CANCEL = 0; // 用户取消订单
  37. const STATUS_REFUND = -1; // 申请售后
  38. // 申请售后状态 0=无,1=申请中,2=通过(让用户发货)或无需退货,3=通过,4=拒绝
  39. const REFUND_STATUS_NONE = 0;
  40. const REFUND_STATUS_APPLY = 1;
  41. const REFUND_STATUS_DELIVERY = 2;
  42. const REFUND_STATUS_AGREE = 3;
  43. const REFUND_STATUS_REFUSE = 4;
  44. // 是否支付
  45. const PAID_NO = 0; // 否
  46. // 是否发货 delivered
  47. const DELIVERED_NO = 0; // 否
  48. // 是否评论
  49. const COMMENTED_NO = 0; // 否
  50. // 是否收货
  51. const RECEIVED_NO = 0; // 否
  52. // 订单类型
  53. const TYPE_ALL = 0; // 全部
  54. const TYPE_PAY = 1; // 待付款
  55. // const TYPE_DELIVES = 2; // 待发货
  56. const TYPE_RECEIVE = 3; // 待核销
  57. const TYPE_FINISH = 4; // 已完成
  58. const TYPE_NOCOMMENT = 40; // 待评价
  59. const TYPE_COMMENTED = 41; // 已评价
  60. // const TYPE_REFUND = 5; // 售后
  61. // const TYPE_REFUSE = 6; // 拒绝退款
  62. // const TYPE_OFF = 9; // 订单关闭
  63. const TYPE_CANCEL = 20; //订单取消(已支付+未支付)
  64. /**
  65. * 格式化时间
  66. * @param $value
  67. * @return false|string
  68. */
  69. public function getCreatetimeAttr($value)
  70. {
  71. return date('Y-m-d H:i:s', $value);
  72. }
  73. /**
  74. * 格式化时间 paidtime
  75. * @return false|int|string
  76. */
  77. public function getPaidtimeAttr($value, $data)
  78. {
  79. return $data['have_paid'] > 0 ? date('Y-m-d H:i:s', $data['have_paid']) : '';
  80. }
  81. /**
  82. * 格式化时间 deliveredtime
  83. * @return false|int|string
  84. */
  85. public function getDeliveredtimeAttr($value, $data)
  86. {
  87. return $data['have_delivered'] > 0 ? date('Y-m-d H:i:s', $data['have_delivered']) : '';
  88. }
  89. /**
  90. * 格式化时间 receivedtime
  91. * @return false|int|string
  92. */
  93. public function getReceivedtimeAttr($value, $data)
  94. {
  95. return $data['have_received'] > 0 ? date('Y-m-d H:i:s', $data['have_received']) : '';
  96. }
  97. /**
  98. * 格式化时间 commentedtime
  99. * @return false|int|string
  100. */
  101. public function getCommentedtimeAttr($value, $data)
  102. {
  103. return $data['have_commented'] > 0 ? date('Y-m-d H:i:s', $data['have_commented']) : '';
  104. }
  105. /**
  106. * 支付类型
  107. */
  108. public function getPayTypeTextAttr($value, $data)
  109. {
  110. switch ($data['pay_type']) {
  111. case self::PAY_ONLINE:
  112. return __('Online');
  113. break;
  114. case self::PAY_OFFLINE:
  115. return __('Offline');
  116. break;
  117. case self::PAY_WXPAY:
  118. return __('wxPay');
  119. break;
  120. case self::PAY_ALIPAY:
  121. return __('aliPay');
  122. break;
  123. }
  124. }
  125. /**
  126. * 加密订单id
  127. * @param $value
  128. * @param $data
  129. * @return string
  130. */
  131. public function getOrderIdAttr($value, $data)
  132. {
  133. return Hashids::encodeHex($data['id']);
  134. }
  135. /**
  136. * 0=全部,1=待付款,2=待发货,3=待收货,4=待评价,5=售后
  137. * * 0=全部,1=待付款,3=待核销,4=已完成
  138. * 获取当前的订单状态
  139. */
  140. public function getStateAttr($value, $data)
  141. {
  142. switch (true) {
  143. case $data['have_paid'] == self::PAID_NO && $data['status'] == self::STATUS_NORMAL:
  144. $state = self::TYPE_PAY;
  145. break;
  146. /*case $data['have_delivered'] == self::DELIVERED_NO && $data['status'] == self::STATUS_NORMAL:
  147. $state = self::TYPE_DELIVES;
  148. break;*/
  149. case $data['have_paid'] != self::PAID_NO && $data['have_received'] == self::RECEIVED_NO && $data['status'] == self::STATUS_NORMAL:
  150. $state = self::TYPE_RECEIVE;
  151. break;
  152. case $data['have_paid'] != self::PAID_NO && $data['have_received'] != self::RECEIVED_NO && $data['have_commented'] == self::COMMENTED_NO && $data['status'] == self::STATUS_NORMAL:
  153. $state = self::TYPE_NOCOMMENT;
  154. break;
  155. case $data['have_paid'] != self::PAID_NO && $data['have_received'] != self::RECEIVED_NO && $data['have_commented'] != self::COMMENTED_NO && $data['status'] == self::STATUS_NORMAL:
  156. $state = self::TYPE_COMMENTED;
  157. break;
  158. case $data['status'] == self::STATUS_CANCEL:
  159. $state = self::TYPE_CANCEL;
  160. break;
  161. //case $data['status'] == self::STATUS_REFUND && $data['refund_status'] == self::REFUND_STATUS_AGREE: // TODO 申请退款并且已通过同意,则订单为关闭状态
  162. /* case $data['status'] == self::STATUS_REFUND && $data['refund_status'] == self::REFUND_STATUS_REFUSE:
  163. $state = self::TYPE_REFUSE;
  164. break;
  165. case $data['status'] == self::STATUS_REFUND:
  166. $state = self::TYPE_REFUND;
  167. break;*/
  168. default:
  169. $state = self::TYPE_ALL;
  170. break;
  171. }
  172. return $state;
  173. }
  174. //获取当前的订单状态,中文
  175. public function getStatetextAttr($state,$refund_status){
  176. $data = [
  177. 1 => '待付款',
  178. 3 => '待核销',
  179. 41 => '已评价',
  180. 40 => '待评价',
  181. 20 => '已取消',
  182. ];
  183. if($state == 20 && $refund_status == 3){
  184. return '已退款';
  185. }
  186. return isset($data[$state]) ? $data[$state] : $state;
  187. }
  188. /**
  189. * 退款状态
  190. */
  191. public function getRefundStatusTextAttr($value, $data)
  192. {
  193. $name = '';
  194. if ($data['status'] == self::STATUS_REFUND) {
  195. switch ($data['refund_status']) {
  196. case self::REFUND_STATUS_APPLY:
  197. $name = '申请中';
  198. break;
  199. case self::REFUND_STATUS_DELIVERY:
  200. $name = '通过申请/请发货';
  201. break;
  202. case self::REFUND_STATUS_AGREE:
  203. $name = '退款成功';
  204. break;
  205. case self::REFUND_STATUS_REFUSE:
  206. $name = '退款失败';
  207. break;
  208. }
  209. }
  210. return $name;
  211. }
  212. /**
  213. * 创建订单
  214. * @param $userId
  215. * @param $data
  216. * @return int
  217. * @throws \Exception
  218. */
  219. public function createOrder($userId, $data)
  220. {
  221. $data['userId'] = $userId;
  222. Hook::listen('create_order_before', $params, $data);
  223. list($products, $delivery, $coupon, $baseProductInfos, $address, $orderPrice, $specs, $numbers) = $params;
  224. // 获取雪花算法分布式id,方便以后扩展
  225. $snowflake = new Snowflake();
  226. $id = $snowflake->id();
  227. // 优惠费用
  228. // $discountPrice = isset($coupon['value']) ? $coupon['value'] : 0;
  229. $discountPrice = 0;
  230. // 订单费用
  231. //$orderPrice;
  232. // 运费
  233. // $deliveryPrice = Delivery::algorithm($delivery, array_sum($numbers));
  234. $deliveryPrice = '0';
  235. // 总费用
  236. $totalPrice = bcadd(bcsub($orderPrice, $discountPrice, 2), $deliveryPrice, 2);
  237. $out_trade_no = date('Ymd',time()).uniqid().$userId;
  238. $db_pay_type = [
  239. 'wallet' => 2,
  240. 'wechat' => 3,
  241. 'alipay' => 4,
  242. ];
  243. (new self)->save([
  244. 'id' => $id,
  245. 'user_id' => $userId,
  246. 'out_trade_no' => $out_trade_no,
  247. 'order_price' => $orderPrice,
  248. 'discount_price' => $discountPrice,
  249. 'delivery_price' => $deliveryPrice,
  250. 'total_price' => $totalPrice,
  251. 'pay_type' => $db_pay_type[$data['pay_type']],
  252. 'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
  253. 'remark' => $data['remark'] ?? '',
  254. 'status' => self::STATUS_NORMAL,
  255. ]);
  256. (new OrderExtend)->save([
  257. 'user_id' => $userId,
  258. 'order_id' => $id,
  259. 'coupon_id' => $coupon ? $coupon['id'] : 0,
  260. 'coupon_json' => json_encode($coupon),
  261. 'delivery_id' => $delivery ? $delivery['id'] : 0,
  262. 'delivery_json' => json_encode($delivery),
  263. // 'address_id' => $address['id'],
  264. // 'address_json' => json_encode($address),
  265. ]);
  266. $orderProduct = $specNumber = [];
  267. foreach($products as $key => $product) {
  268. $orderProduct[] = [
  269. 'user_id' => $userId,
  270. 'order_id' => $id,
  271. 'product_id' => $product['id'],
  272. 'title' => $product['title'],
  273. 'image' => $product['image'],
  274. 'number' => $numbers[$key],
  275. 'spec' => $specs[$key] ?? '',
  276. 'price' => $baseProductInfos[$key]['sales_price'],
  277. //'product_json' => json_encode($product), // Todo 耗内存,损速度 (考虑去掉)
  278. 'createtime' => time(),
  279. 'updatetime' => time(),
  280. 'flash_id' => $data['flash_id'] ?? 0, // 秒杀id
  281. ];
  282. if (!empty($specs[$key])) {
  283. $specNumber[$specs[$key]] = $numbers[$key];
  284. } else {
  285. $specNumber[$key] = $numbers[$key];
  286. }
  287. }
  288. (new OrderProduct)->insertAll($orderProduct);
  289. $data['specNumber'] = $specNumber;
  290. Hook::listen('create_order_after', $products, $data);
  291. return [
  292. 'order_id' => Hashids::encodeHex($id),
  293. 'out_trade_no' => $out_trade_no
  294. ];
  295. }
  296. /**
  297. * 获取我的订单
  298. * @param int $userId 用户id
  299. * @param int $state 0=全部,1=待付款,3=待核销,4=已完成,40=待评价
  300. */
  301. public function getOrdersByType($userId, $state = 0, $page = 1, $pageSize = 10)
  302. {
  303. $condition['user_id'] = ['=', $userId];
  304. switch ($state) {
  305. case self::TYPE_PAY: //1=待付款
  306. $condition['have_paid'] = ['=', self::PAID_NO];
  307. $condition['status'] = ['=', self::STATUS_NORMAL];
  308. $orderBy = 'createtime';
  309. break;
  310. /*case self::TYPE_DELIVES:
  311. $condition['have_paid'] = ['>', self::PAID_NO];
  312. $condition['have_delivered'] = ['=', self::DELIVERED_NO];
  313. $condition['status'] = ['=', self::STATUS_NORMAL];
  314. $orderBy = 'have_paid';
  315. break;*/
  316. case self::TYPE_RECEIVE: //3=待核销
  317. $condition['have_paid'] = ['>', self::PAID_NO];
  318. $condition['have_delivered'] = ['>', self::DELIVERED_NO];
  319. $condition['have_received'] = ['=', self::RECEIVED_NO];
  320. $condition['status'] = ['=', self::STATUS_NORMAL];
  321. $orderBy = 'have_delivered';
  322. break;
  323. case self::TYPE_FINISH: //4=已完成
  324. $condition['have_paid'] = ['>', self::PAID_NO];
  325. $condition['have_delivered'] = ['>', self::DELIVERED_NO];
  326. $condition['have_received'] = ['>', self::RECEIVED_NO];
  327. // $condition['have_commented'] = ['=', self::COMMENTED_NO];
  328. $condition['status'] = ['=', self::STATUS_NORMAL];
  329. $orderBy = 'have_received';
  330. break;
  331. case self::TYPE_NOCOMMENT: //40=待评价
  332. $condition['have_paid'] = ['>', self::PAID_NO];
  333. $condition['have_delivered'] = ['>', self::DELIVERED_NO];
  334. $condition['have_received'] = ['>', self::RECEIVED_NO];
  335. $condition['have_commented'] = ['=', self::COMMENTED_NO];
  336. $condition['status'] = ['=', self::STATUS_NORMAL];
  337. $orderBy = 'have_received';
  338. break;
  339. /*case self::TYPE_REFUND:
  340. $condition['have_paid'] = ['>', self::PAID_NO];
  341. $condition['status'] = ['=', self::STATUS_REFUND];
  342. $condition['refund_status'] = ['<>', self::REFUND_STATUS_AGREE];
  343. $orderBy = 'createtime';
  344. break;*/
  345. default: //全部
  346. $orderBy = 'createtime';
  347. break;
  348. }
  349. $result = $this
  350. ->with([
  351. 'products' => function($query) {
  352. $query->field('id,title,image,number,price,spec,order_id,product_id');
  353. },
  354. /*'extend' => function($query) {
  355. $query->field('order_id,express_number,express_company');
  356. },*/
  357. 'evaluate' => function($query) {
  358. $query->field('id,order_id,product_id');
  359. },
  360. /*'refundProducts' => function($query) {
  361. $query->field('id,order_id,order_product_id');
  362. }*/
  363. ])
  364. ->where($condition)
  365. ->order([$orderBy => 'desc'])
  366. ->limit(($page - 1) * $pageSize, $pageSize)
  367. ->select();
  368. foreach ($result as &$item) {
  369. $item->append(['order_id','state']);
  370. $item['state_text'] = $this->getStatetextAttr($item['state'],$item['refund_status']);//状态中文
  371. $item = $item->toArray();
  372. $evaluate = array_column($item['evaluate'], 'product_id');
  373. // $refundProducts = array_column($item['refund_products'], 'order_product_id');
  374. unset($item['evaluate']);
  375. // unset($item['refund_products']);
  376. foreach ($item['products'] as &$product) {
  377. $product['image'] = Config::getImagesFullUrl($product['image']);
  378. // 是否已评论
  379. if (in_array($product['id'], $evaluate)) {
  380. $product['evaluate'] = true;
  381. } else {
  382. $product['evaluate'] = false;
  383. }
  384. // 是否退货
  385. /*if ($item['refund_status'] == self::REFUND_STATUS_AGREE && in_array($product['order_product_id'], $refundProducts)) {
  386. $product['refund'] = true;
  387. } else {
  388. $product['refund'] = false;
  389. }*/
  390. }
  391. }
  392. return $result;
  393. }
  394. /**
  395. * 关联订单的商品
  396. */
  397. public function products()
  398. {
  399. return $this->hasMany('orderProduct', 'order_id', 'id');
  400. }
  401. /**
  402. * 关联扩展订单信息
  403. * @return \think\model\relation\HasOne
  404. */
  405. public function extend()
  406. {
  407. return $this->hasOne('orderExtend', 'order_id', 'id');
  408. }
  409. /**
  410. * 关联评价
  411. * @return \think\model\relation\HasOne
  412. */
  413. public function evaluate()
  414. {
  415. return $this->hasMany('evaluate', 'order_id', 'id');
  416. }
  417. /**
  418. * 关联退货信息
  419. * @return \think\model\relation\HasMany
  420. */
  421. public function refund()
  422. {
  423. return $this->hasOne('orderRefund', 'order_id', 'id');
  424. }
  425. /**
  426. * 关联退货的商品
  427. * @return \think\model\relation\HasMany
  428. */
  429. public function refundProducts()
  430. {
  431. return $this->hasMany('orderRefundProduct', 'order_id', 'id');
  432. }
  433. }