You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

447 lines
14 KiB

  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_COMMENT = 4; // 待评价
  58. const TYPE_REFUND = 5; // 售后
  59. const TYPE_REFUSE = 6; // 拒绝退款
  60. const TYPE_OFF = 9; // 订单关闭
  61. /**
  62. * 格式化时间
  63. * @param $value
  64. * @return false|string
  65. */
  66. public function getCreatetimeAttr($value)
  67. {
  68. return date('Y-m-d H:i:s', $value);
  69. }
  70. /**
  71. * 格式化时间 paidtime
  72. * @return false|int|string
  73. */
  74. public function getPaidtimeAttr($value, $data)
  75. {
  76. return $data['have_paid'] > 0 ? date('Y-m-d H:i:s', $data['have_paid']) : 0;
  77. }
  78. /**
  79. * 格式化时间 deliveredtime
  80. * @return false|int|string
  81. */
  82. public function getDeliveredtimeAttr($value, $data)
  83. {
  84. return $data['have_delivered'] > 0 ? date('Y-m-d H:i:s', $data['have_delivered']) : 0;
  85. }
  86. /**
  87. * 格式化时间 receivedtime
  88. * @return false|int|string
  89. */
  90. public function getReceivedtimeAttr($value, $data)
  91. {
  92. return $data['have_received'] > 0 ? date('Y-m-d H:i:s', $data['have_received']) : 0;
  93. }
  94. /**
  95. * 格式化时间 commentedtime
  96. * @return false|int|string
  97. */
  98. public function getCommentedtimeAttr($value, $data)
  99. {
  100. return $data['have_commented'] > 0 ? date('Y-m-d H:i:s', $data['have_commented']) : 0;
  101. }
  102. /**
  103. * 支付类型
  104. */
  105. public function getPayTypeTextAttr($value, $data)
  106. {
  107. switch ($data['pay_type']) {
  108. case self::PAY_ONLINE:
  109. return __('Online');
  110. break;
  111. case self::PAY_OFFLINE:
  112. return __('Offline');
  113. break;
  114. case self::PAY_WXPAY:
  115. return __('wxPay');
  116. break;
  117. case self::PAY_ALIPAY:
  118. return __('aliPay');
  119. break;
  120. }
  121. }
  122. /**
  123. * 加密订单id
  124. * @param $value
  125. * @param $data
  126. * @return string
  127. */
  128. public function getOrderIdAttr($value, $data)
  129. {
  130. return Hashids::encodeHex($data['id']);
  131. }
  132. /**
  133. * 0=全部,1=待付款,2=待发货,3=待收货,4=待评价,5=售后
  134. * 获取当前的订单状态
  135. */
  136. public function getStateAttr($value, $data)
  137. {
  138. switch (true) {
  139. case $data['have_paid'] == self::PAID_NO && $data['status'] == self::STATUS_NORMAL:
  140. $state = self::TYPE_PAY;
  141. break;
  142. case $data['have_delivered'] == self::DELIVERED_NO && $data['status'] == self::STATUS_NORMAL:
  143. $state = self::TYPE_DELIVES;
  144. break;
  145. case $data['have_received'] == self::RECEIVED_NO && $data['status'] == self::STATUS_NORMAL:
  146. $state = self::TYPE_RECEIVE;
  147. break;
  148. case $data['have_commented'] == self::COMMENTED_NO && $data['status'] == self::STATUS_NORMAL:
  149. $state = self::TYPE_COMMENT;
  150. break;
  151. case $data['status'] == self::STATUS_REFUND && $data['refund_status'] == self::REFUND_STATUS_AGREE: // TODO 申请退款并且已通过同意,则订单为关闭状态
  152. case $data['status'] == self::STATUS_CANCEL:
  153. $state = self::TYPE_OFF;
  154. break;
  155. case $data['status'] == self::STATUS_REFUND && $data['refund_status'] == self::REFUND_STATUS_REFUSE:
  156. $state = self::TYPE_REFUSE;
  157. break;
  158. case $data['status'] == self::STATUS_REFUND:
  159. $state = self::TYPE_REFUND;
  160. break;
  161. default:
  162. $state = self::TYPE_ALL;
  163. break;
  164. }
  165. return $state;
  166. }
  167. /**
  168. * 退款状态
  169. */
  170. public function getRefundStatusTextAttr($value, $data)
  171. {
  172. $name = '';
  173. if ($data['status'] == self::STATUS_REFUND) {
  174. switch ($data['refund_status']) {
  175. case self::REFUND_STATUS_APPLY:
  176. $name = '申请中';
  177. break;
  178. case self::REFUND_STATUS_DELIVERY:
  179. $name = '通过申请/请发货';
  180. break;
  181. case self::REFUND_STATUS_AGREE:
  182. $name = '退款成功';
  183. break;
  184. case self::REFUND_STATUS_REFUSE:
  185. $name = '退款失败';
  186. break;
  187. }
  188. }
  189. return $name;
  190. }
  191. /**
  192. * 创建订单
  193. * @param $userId
  194. * @param $data
  195. * @return int
  196. * @throws \Exception
  197. */
  198. public function createOrder($userId, $data)
  199. {
  200. $data['userId'] = $userId;
  201. Hook::listen('create_order_before', $params, $data);
  202. list($products, $delivery, $coupon, $baseProductInfos, $address, $orderPrice, $specs, $numbers) = $params;
  203. // 获取雪花算法分布式id,方便以后扩展
  204. $snowflake = new Snowflake();
  205. $id = $snowflake->id();
  206. // 优惠费用
  207. $discountPrice = isset($coupon['value']) ? $coupon['value'] : 0;
  208. // 订单费用
  209. //$orderPrice;
  210. // 运费
  211. $deliveryPrice = Delivery::algorithm($delivery, $data['number']);
  212. // 总费用
  213. $totalPrice = bcadd(bcsub($orderPrice, $discountPrice, 2), $deliveryPrice, 2);
  214. $out_trade_no = date('Ymd',time()).uniqid().$userId;
  215. (new self)->save([
  216. 'id' => $id,
  217. 'user_id' => $userId,
  218. 'out_trade_no' => $out_trade_no,
  219. 'order_price' => $orderPrice,
  220. 'discount_price' => $discountPrice,
  221. 'delivery_price' => $deliveryPrice,
  222. 'total_price' => $totalPrice,
  223. 'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
  224. 'remark' => $data['remark'] ?? '',
  225. 'status' => self::STATUS_NORMAL,
  226. ]);
  227. (new OrderExtend)->save([
  228. 'user_id' => $userId,
  229. 'order_id' => $id,
  230. 'coupon_id' => $coupon ? $coupon['id'] : 0,
  231. 'coupon_json' => json_encode($coupon),
  232. 'delivery_id' => $delivery['id'],
  233. 'delivery_json' => json_encode($delivery),
  234. 'address_id' => $address['id'],
  235. 'address_json' => json_encode($address),
  236. ]);
  237. $orderProduct = $specNumber = [];
  238. foreach($products as $key => $product) {
  239. $orderProduct[] = [
  240. 'user_id' => $userId,
  241. 'order_id' => $id,
  242. 'product_id' => $product['id'],
  243. 'title' => $product['title'],
  244. 'image' => $product['image'],
  245. 'number' => $numbers[$key],
  246. 'spec' => $specs[$key] ?? '',
  247. 'price' => $baseProductInfos[$key]['sales_price'],
  248. //'product_json' => json_encode($product), // Todo 耗内存,损速度 (考虑去掉)
  249. 'createtime' => time(),
  250. 'updatetime' => time(),
  251. 'flash_id' => $data['flash_id'] ?? 0, // 秒杀id
  252. ];
  253. if (!empty($specs[$key])) {
  254. $specNumber[$specs[$key]] = $numbers[$key];
  255. } else {
  256. $specNumber[$key] = $numbers[$key];
  257. }
  258. }
  259. (new OrderProduct)->insertAll($orderProduct);
  260. $data['specNumber'] = $specNumber;
  261. Hook::listen('create_order_after', $products, $data);
  262. return [
  263. 'order_id' => Hashids::encodeHex($id),
  264. 'out_trade_no' => $out_trade_no
  265. ];
  266. }
  267. /**
  268. * 获取我的订单
  269. * @param int $userId 用户id
  270. * @param int $state 0=全部,1=待付款,2=待发货,3=待收货,4=待评价,5=售后
  271. */
  272. public function getOrdersByType($userId, $state = 0, $page = 1, $pageSize = 10)
  273. {
  274. $condition['user_id'] = ['=', $userId];
  275. switch ($state) {
  276. case self::TYPE_PAY:
  277. $condition['have_paid'] = ['=', self::PAID_NO];
  278. $condition['status'] = ['=', self::STATUS_NORMAL];
  279. $orderBy = 'createtime';
  280. break;
  281. case self::TYPE_DELIVES:
  282. $condition['have_paid'] = ['>', self::PAID_NO];
  283. $condition['have_delivered'] = ['=', self::DELIVERED_NO];
  284. $condition['status'] = ['=', self::STATUS_NORMAL];
  285. $orderBy = 'have_paid';
  286. break;
  287. case self::TYPE_RECEIVE:
  288. $condition['have_paid'] = ['>', self::PAID_NO];
  289. $condition['have_delivered'] = ['>', self::DELIVERED_NO];
  290. $condition['have_received'] = ['=', self::RECEIVED_NO];
  291. $condition['status'] = ['=', self::STATUS_NORMAL];
  292. $orderBy = 'have_delivered';
  293. break;
  294. case self::TYPE_COMMENT:
  295. $condition['have_paid'] = ['>', self::PAID_NO];
  296. $condition['have_delivered'] = ['>', self::DELIVERED_NO];
  297. $condition['have_received'] = ['>', self::RECEIVED_NO];
  298. $condition['have_commented'] = ['=', self::COMMENTED_NO];
  299. $condition['status'] = ['=', self::STATUS_NORMAL];
  300. $orderBy = 'have_received';
  301. break;
  302. case self::TYPE_REFUND:
  303. $condition['have_paid'] = ['>', self::PAID_NO];
  304. $condition['status'] = ['=', self::STATUS_REFUND];
  305. $condition['refund_status'] = ['<>', self::REFUND_STATUS_AGREE];
  306. $orderBy = 'createtime';
  307. break;
  308. default: //全部
  309. $orderBy = 'createtime';
  310. break;
  311. }
  312. $result = $this
  313. ->with([
  314. 'products' => function($query) {
  315. $query->field('id,title,image,number,price,spec,order_id,product_id');
  316. },
  317. 'extend' => function($query) {
  318. $query->field('order_id,express_number');
  319. },
  320. 'evaluate' => function($query) {
  321. $query->field('id,order_id,product_id');
  322. },
  323. 'refundProducts' => function($query) {
  324. $query->field('id,order_id,order_product_id');
  325. }
  326. ])
  327. ->where($condition)
  328. ->order([$orderBy => 'desc'])
  329. ->limit(($page - 1) * $pageSize, $pageSize)
  330. ->select();
  331. foreach ($result as &$item) {
  332. $item->append(['order_id','state', 'refund_status_text']);
  333. $item = $item->toArray();
  334. $evaluate = array_column($item['evaluate'], 'product_id');
  335. $refundProducts = array_column($item['refund_products'], 'order_product_id');
  336. unset($item['evaluate']);
  337. unset($item['refund_products']);
  338. foreach ($item['products'] as &$product) {
  339. $product['image'] = Config::getImagesFullUrl($product['image']);
  340. // 是否已评论
  341. if (in_array($product['id'], $evaluate)) {
  342. $product['evaluate'] = true;
  343. } else {
  344. $product['evaluate'] = false;
  345. }
  346. // 是否退货
  347. if ($item['refund_status'] == self::REFUND_STATUS_AGREE && in_array($product['order_product_id'], $refundProducts)) {
  348. $product['refund'] = true;
  349. } else {
  350. $product['refund'] = false;
  351. }
  352. }
  353. }
  354. return $result;
  355. }
  356. /**
  357. * 关联订单的商品
  358. */
  359. public function products()
  360. {
  361. return $this->hasMany('orderProduct', 'order_id', 'id');
  362. }
  363. /**
  364. * 关联扩展订单信息
  365. * @return \think\model\relation\HasOne
  366. */
  367. public function extend()
  368. {
  369. return $this->hasOne('orderExtend', 'order_id', 'id');
  370. }
  371. /**
  372. * 关联评价
  373. * @return \think\model\relation\HasOne
  374. */
  375. public function evaluate()
  376. {
  377. return $this->hasMany('evaluate', 'order_id', 'id');
  378. }
  379. /**
  380. * 关联退货信息
  381. * @return \think\model\relation\HasMany
  382. */
  383. public function refund()
  384. {
  385. return $this->hasOne('orderRefund', 'order_id', 'id');
  386. }
  387. /**
  388. * 关联退货的商品
  389. * @return \think\model\relation\HasMany
  390. */
  391. public function refundProducts()
  392. {
  393. return $this->hasMany('orderRefundProduct', 'order_id', 'id');
  394. }
  395. }