StoreOrder.php 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\store\StoreProductAttrValue;
  9. use app\admin\model\system\ShippingTemplatesFree;
  10. use app\admin\model\system\ShippingTemplatesRegion;
  11. use crmeb\basic\BaseModel;
  12. use think\facade\Cache;
  13. use crmeb\traits\ModelTrait;
  14. use think\facade\Log;
  15. use app\models\system\SystemStore;
  16. use app\models\routine\RoutineTemplate;
  17. use app\models\user\{
  18. User, UserAddress, UserBill, WechatUser
  19. };
  20. use crmeb\services\{
  21. SystemConfigService, WechatTemplateService, workerman\ChannelService
  22. };
  23. use crmeb\repositories\{
  24. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  25. };
  26. use app\admin\model\system\ShippingTemplates;
  27. /**
  28. * TODO 订单Model
  29. * Class StoreOrder
  30. * @package app\models\store
  31. */
  32. class StoreOrder extends BaseModel
  33. {
  34. /**
  35. * 数据表主键
  36. * @var string
  37. */
  38. protected $pk = 'id';
  39. /**
  40. * 模型名称
  41. * @var string
  42. */
  43. protected $name = 'store_order';
  44. use ModelTrait;
  45. protected $insert = ['add_time'];
  46. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付'];
  47. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  48. protected function setAddTimeAttr()
  49. {
  50. return time();
  51. }
  52. protected function setCartIdAttr($value)
  53. {
  54. return is_array($value) ? json_encode($value) : $value;
  55. }
  56. protected function getCartIdAttr($value)
  57. {
  58. return json_decode($value, true);
  59. }
  60. /**获取订单组信息
  61. * @param $cartInfo
  62. * @return array
  63. */
  64. public static function getOrderPriceGroup($cartInfo, $addr)
  65. {
  66. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  67. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  68. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  69. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  70. //如果满额包邮等于0
  71. if (!$storeFreePostage) {
  72. $storePostage = 0;
  73. } else {
  74. if ($addr) {
  75. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  76. $temp_num = [];
  77. foreach ($cartInfo as $cart) {
  78. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  79. if (!$temp) $temp = ShippingTemplates::get(1);
  80. if ($temp->getData('type') == 1) {
  81. $num = $cart['cart_num'];
  82. } elseif ($temp->getData('type') == 2) {
  83. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  84. } else {
  85. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  86. }
  87. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  88. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  89. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  90. if (!$region) {
  91. return self::setErrorInfo('运费模板不存在');
  92. }
  93. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  94. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  95. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  96. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  97. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  98. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  99. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  100. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  101. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  102. } else {
  103. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  104. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  105. }
  106. }
  107. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  108. $type = $storePostage = 0;
  109. foreach ($temp_num as $k => $v) {
  110. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  111. unset($temp_num[$k]);
  112. }
  113. }
  114. foreach ($temp_num as $v) {
  115. if ($type == 0) {
  116. if ($v['number'] <= $v['first']) {
  117. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  118. } else {
  119. if ($v['continue'] <= 0) {
  120. $storePostage = $storePostage;
  121. } else {
  122. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  123. }
  124. }
  125. $type = 1;
  126. } else {
  127. if ($v['continue'] <= 0) {
  128. $storePostage = $storePostage;
  129. } else {
  130. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  131. }
  132. }
  133. }
  134. } else {
  135. $storePostage = 0;
  136. }
  137. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  138. }
  139. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice');
  140. }
  141. /**获取某个字段总金额
  142. * @param $cartInfo
  143. * @param $key 键名
  144. * @return int|string
  145. */
  146. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  147. {
  148. $SumPrice = 0;
  149. foreach ($cartInfo as $cart) {
  150. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  151. }
  152. return $SumPrice;
  153. }
  154. /**
  155. * 拼团
  156. * @param $cartInfo
  157. * @return array
  158. */
  159. public static function getCombinationOrderPriceGroup($cartInfo)
  160. {
  161. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  162. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  163. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  164. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  165. if (!$storeFreePostage) {
  166. $storePostage = 0;
  167. } else {
  168. foreach ($cartInfo as $cart) {
  169. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  170. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  171. }
  172. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  173. }
  174. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  175. }
  176. /**
  177. * 拼团价格
  178. * @param $cartInfo
  179. * @return float
  180. */
  181. public static function getCombinationOrderTotalPrice($cartInfo)
  182. {
  183. $totalPrice = 0;
  184. foreach ($cartInfo as $cart) {
  185. if ($cart['combination_id']) {
  186. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  187. }
  188. }
  189. return (float)$totalPrice;
  190. }
  191. /**
  192. * 缓存订单信息
  193. * @param $uid
  194. * @param $cartInfo
  195. * @param $priceGroup
  196. * @param array $other
  197. * @param int $cacheTime
  198. * @return string
  199. * @throws \Psr\SimpleCache\InvalidArgumentException
  200. */
  201. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  202. {
  203. $key = md5(time());
  204. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  205. return $key;
  206. }
  207. /**
  208. * 获取订单缓存信息
  209. * @param $uid
  210. * @param $key
  211. * @return mixed|null
  212. * @throws \Psr\SimpleCache\InvalidArgumentException
  213. */
  214. public static function getCacheOrderInfo($uid, $key)
  215. {
  216. $cacheName = 'user_order_' . $uid . $key;
  217. if (!Cache::has($cacheName)) return null;
  218. return Cache::get($cacheName);
  219. }
  220. /**
  221. * 删除订单缓存
  222. * @param $uid
  223. * @param $key
  224. */
  225. public static function clearCacheOrderInfo($uid, $key)
  226. {
  227. Cache::delete('user_order_' . $uid . $key);
  228. }
  229. /**
  230. * 生成订单
  231. * @param $uid
  232. * @param $key
  233. * @param $addressId
  234. * @param $payType
  235. * @param bool $useIntegral
  236. * @param int $couponId
  237. * @param string $mark
  238. * @param int $combinationId
  239. * @param int $pinkId
  240. * @param int $seckill_id
  241. * @param int $bargain_id
  242. * @param bool $test
  243. * @param int $isChannel
  244. * @param int $shipping_type
  245. * @param string $real_name
  246. * @param string $phone
  247. * @return StoreOrder|bool|\think\Model
  248. * @throws \think\Exception
  249. * @throws \think\db\exception\DataNotFoundException
  250. * @throws \think\db\exception\ModelNotFoundException
  251. * @throws \think\exception\DbException
  252. */
  253. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  254. {
  255. self::beginTrans();
  256. try {
  257. $shipping_type = (int)$shipping_type;
  258. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  259. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  260. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  261. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  262. $userInfo = User::getUserInfo($uid);
  263. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  264. $cartGroup = self::getCacheOrderInfo($uid, $key);
  265. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  266. $cartInfo = $cartGroup['cartInfo'];
  267. $priceGroup = $cartGroup['priceGroup'];
  268. $other = $cartGroup['other'];
  269. $payPrice = (float)$priceGroup['totalPrice'];
  270. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  271. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  272. $payPostage = 0;
  273. } else {
  274. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  275. }
  276. if ($shipping_type === 1) {
  277. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  278. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  279. return self::setErrorInfo('地址选择有误!', true);
  280. } else {
  281. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  282. $addressInfo['real_name'] = $real_name;
  283. $addressInfo['phone'] = $phone;
  284. $addressInfo['province'] = '';
  285. $addressInfo['city'] = '';
  286. $addressInfo['district'] = '';
  287. $addressInfo['detail'] = '';
  288. }
  289. $cartIds = [];
  290. $totalNum = 0;
  291. $gainIntegral = 0;
  292. foreach ($cartInfo as $cart){
  293. if (!$test && !self::checkProductStock($uid, $cart['product_id'], $cart['cart_num'], $cart['product_attr_unique'], $cart['combination_id'], $cart['seckill_id'], $cart['bargain_id'])) {
  294. return false;
  295. }
  296. $cartIds[] = $cart['id'];
  297. $totalNum += $cart['cart_num'];
  298. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  299. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  300. if (!$combinationId) $combinationId = $cart['combination_id'];
  301. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  302. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  303. }
  304. $deduction = $seckill_id || $bargain_id || $combinationId;
  305. if ($deduction) {
  306. $couponId = 0;
  307. $useIntegral = false;
  308. if (!$test) {
  309. unset(self::$payType['offline']);
  310. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  311. }
  312. }
  313. //使用优惠劵
  314. $res1 = true;
  315. if ($couponId) {
  316. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  317. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  318. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  319. $flag = false;
  320. foreach ($coupons as $coupon) {
  321. if ($coupon['id'] == $couponId) {
  322. $flag = true;
  323. continue;
  324. }
  325. }
  326. if (!$flag)
  327. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  328. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  329. $res1 = StoreCouponUser::useCoupon($couponId);
  330. $couponPrice = $couponInfo['coupon_price'];
  331. } else {
  332. $couponId = 0;
  333. $couponPrice = 0;
  334. }
  335. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  336. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  337. $store_self_mention = sys_config('store_self_mention') ?? 0;
  338. if (!$store_self_mention) $shipping_type = 1;
  339. if ($shipping_type === 1) {
  340. //是否包邮
  341. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  342. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  343. } else if ($shipping_type === 2) {
  344. //门店自提没有邮费支付
  345. $priceGroup['storePostage'] = 0;
  346. $payPostage = 0;
  347. if (!$storeId && !$test) {
  348. return self::setErrorInfo('请选择门店', true);
  349. }
  350. }
  351. //积分抵扣
  352. $res2 = true;
  353. $SurplusIntegral = 0;
  354. if ($useIntegral && $userInfo['integral'] > 0) {
  355. $deductionPrice = (float)bcmul($userInfo['integral'], $other['integralRatio'], 2);
  356. if ($deductionPrice < $payPrice) {
  357. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  358. $usedIntegral = $userInfo['integral'];
  359. $SurplusIntegral = 0;
  360. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  361. } else {
  362. $deductionPrice = $payPrice;
  363. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  364. $SurplusIntegral = bcsub($userInfo['integral'], $usedIntegral, 2);
  365. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  366. $payPrice = 0;
  367. }
  368. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $userInfo['integral'], '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  369. } else {
  370. $deductionPrice = 0;
  371. $usedIntegral = 0;
  372. }
  373. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  374. if ($payPrice <= 0) $payPrice = 0;
  375. if ($test) {
  376. self::rollbackTrans();
  377. return [
  378. 'total_price' => $priceGroup['totalPrice'],
  379. 'pay_price' => $payPrice,
  380. 'pay_postage' => $payPostage,
  381. 'coupon_price' => $couponPrice,
  382. 'deduction_price' => $deductionPrice,
  383. 'SurplusIntegral' => $SurplusIntegral,
  384. ];
  385. }
  386. $orderInfo = [
  387. 'uid' => $uid,
  388. 'order_id' => $test ? 0 : self::getNewOrderId(),
  389. 'real_name' => $addressInfo['real_name'],
  390. 'user_phone' => $addressInfo['phone'],
  391. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  392. 'cart_id' => $cartIds,
  393. 'total_num' => $totalNum,
  394. 'total_price' => $priceGroup['totalPrice'],
  395. 'total_postage' => $priceGroup['storePostage'],
  396. 'coupon_id' => $couponId,
  397. 'coupon_price' => $couponPrice,
  398. 'pay_price' => $payPrice,
  399. 'pay_postage' => $payPostage,
  400. 'deduction_price' => $deductionPrice,
  401. 'paid' => 0,
  402. 'pay_type' => $payType,
  403. 'use_integral' => $usedIntegral,
  404. 'gain_integral' => $gainIntegral,
  405. 'mark' => htmlspecialchars($mark),
  406. 'combination_id' => $combinationId,
  407. 'pink_id' => $pinkId,
  408. 'seckill_id' => $seckill_id,
  409. 'bargain_id' => $bargain_id,
  410. 'cost' => $priceGroup['costPrice'],
  411. 'is_channel' => $isChannel,
  412. 'add_time' => time(),
  413. 'unique' => $key,
  414. 'shipping_type' => $shipping_type,
  415. 'is_gold'=>input('is_gold',0),
  416. ];
  417. if ($shipping_type === 2) {
  418. $orderInfo['verify_code'] = self::getStoreCode();
  419. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  420. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  421. }
  422. $order = self::create($orderInfo);
  423. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  424. $res5 = true;
  425. foreach ($cartInfo as $cart) {
  426. //减库存加销量
  427. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  428. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  429. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  430. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  431. }
  432. //保存购物车商品信息
  433. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  434. //购物车状态修改
  435. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  436. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  437. //自动设置默认地址
  438. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  439. self::clearCacheOrderInfo($uid, $key);
  440. self::commitTrans();
  441. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  442. return $order;
  443. } catch (\PDOException $e) {
  444. self::rollbackTrans();
  445. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  446. } catch (\Exception $e) {
  447. self::rollbackTrans();
  448. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  449. }
  450. }
  451. /**
  452. * 回退积分
  453. * @param $order 订单信息
  454. * @return bool
  455. */
  456. public static function RegressionIntegral($order)
  457. {
  458. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  459. if ($order['use_integral'] <= 0) return true;
  460. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  461. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  462. if (!$res) return self::setErrorInfo('回退积分增加失败');
  463. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  464. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  465. }
  466. /**
  467. * 回退库存和销量
  468. * @param $order 订单信息
  469. * @return bool
  470. * @throws \think\db\exception\DataNotFoundException
  471. * @throws \think\db\exception\ModelNotFoundException
  472. * @throws \think\exception\DbException
  473. */
  474. public static function RegressionStock($order)
  475. {
  476. if ($order['status'] == -2 || $order['is_del']) return true;
  477. $combinationId = $order['combination_id'];
  478. $seckill_id = $order['seckill_id'];
  479. $bargain_id = $order['bargain_id'];
  480. $res5 = true;
  481. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  482. foreach ($cartInfo as $cart) {
  483. //增库存减销量
  484. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  485. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  486. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  487. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  488. }
  489. return $res5;
  490. }
  491. /**
  492. * 回退优惠卷
  493. * @param $order 订单信息
  494. * @return bool
  495. */
  496. public static function RegressionCoupon($order)
  497. {
  498. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  499. $res = true;
  500. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  501. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  502. }
  503. return $res;
  504. }
  505. /**
  506. * 取消订单
  507. * @param string order_id 订单id
  508. * @param $uid
  509. * @return bool
  510. * @throws \think\db\exception\DataNotFoundException
  511. * @throws \think\db\exception\ModelNotFoundException
  512. * @throws \think\exception\DbException
  513. */
  514. public static function cancelOrder($order_id, $uid)
  515. {
  516. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  517. if (!$order) return self::setErrorInfo('没有查到此订单');
  518. self::beginTrans();
  519. try {
  520. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  521. $order->is_del = 1;
  522. if ($res && $order->save()) {
  523. self::commitTrans();
  524. return true;
  525. } else
  526. return false;
  527. } catch (\Exception $e) {
  528. self::rollbackTrans();
  529. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  530. }
  531. }
  532. /**
  533. * 生成订单唯一id
  534. * @param $uid 用户uid
  535. * @return string
  536. */
  537. public static function getNewOrderId()
  538. {
  539. list($msec, $sec) = explode(' ', microtime());
  540. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  541. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  542. if (self::be(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  543. return $orderId;
  544. }
  545. /**
  546. * 修改订单号
  547. * @param $orderId
  548. * @return string
  549. */
  550. public static function changeOrderId($orderId)
  551. {
  552. $ymd = substr($orderId, 2, 8);
  553. $key = substr($orderId, 16);
  554. return 'wx' . $ymd . date('His') . $key;
  555. }
  556. /**
  557. * 查找购物车里的所有产品标题
  558. * @param $cartId 购物车id
  559. * @return bool|string
  560. */
  561. public static function getProductTitle($cartId)
  562. {
  563. $title = '';
  564. try {
  565. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  566. foreach ($orderCart as $item) {
  567. if (isset($item['cart_info']['productInfo']['store_name'])) {
  568. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  569. }
  570. }
  571. unset($item);
  572. if (!$title) {
  573. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  574. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  575. foreach ($productlist as $item) {
  576. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  577. }
  578. }
  579. if ($title) $title = substr($title, 0, strlen($title) - 1);
  580. unset($item);
  581. } catch (\Exception $e) {
  582. }
  583. return $title;
  584. }
  585. /**
  586. * 获取门店自提唯一核销码
  587. * @return bool|string
  588. */
  589. public static function getStoreCode()
  590. {
  591. list($msec, $sec) = explode(' ', microtime());
  592. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  593. if (strlen($num) < 12)
  594. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  595. else
  596. $num = substr($num, 0, 12);
  597. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  598. return $num;
  599. }
  600. /**
  601. * 余额支付
  602. * @param $order_id
  603. * @param $uid
  604. * @param string $formId
  605. * @return bool
  606. * @throws \think\Exception
  607. * @throws \think\db\exception\DataNotFoundException
  608. * @throws \think\db\exception\ModelNotFoundException
  609. * @throws \think\exception\DbException
  610. */
  611. public static function yuePay($order_id, $uid, $formId = '')
  612. {
  613. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  614. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  615. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  616. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  617. $userInfo = User::getUserInfo($uid);
  618. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  619. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  620. self::beginTrans();
  621. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  622. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  623. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  624. try {
  625. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  626. } catch (\Exception $e) {
  627. self::rollbackTrans();
  628. return self::setErrorInfo($e->getMessage());
  629. }
  630. $res = $res1 && $res2 && $res3;
  631. self::checkTrans($res);
  632. return $res;
  633. }
  634. /**
  635. * 微信支付 为 0元时
  636. * @param $order_id
  637. * @param $uid
  638. * @param string $formId
  639. * @return bool
  640. * @throws \think\Exception
  641. * @throws \think\db\exception\DataNotFoundException
  642. * @throws \think\db\exception\ModelNotFoundException
  643. * @throws \think\exception\DbException
  644. */
  645. public static function jsPayPrice($order_id, $uid, $formId = '')
  646. {
  647. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  648. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  649. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  650. $userInfo = User::getUserInfo($uid);
  651. self::beginTrans();
  652. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  653. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  654. $res = $res1 && $res2;
  655. self::checkTrans($res);
  656. return $res;
  657. }
  658. /**
  659. * 用户申请退款
  660. * @param $uni
  661. * @param $uid
  662. * @param string $refundReasonWap
  663. * @return bool
  664. */
  665. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  666. {
  667. $order = self::getUserOrderDetail($uid, $uni);
  668. if (!$order) return self::setErrorInfo('支付订单不存在!');
  669. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  670. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  671. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  672. self::beginTrans();
  673. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  674. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  675. $res = $res1 && $res2;
  676. self::checkTrans($res);
  677. if (!$res)
  678. return self::setErrorInfo('申请退款失败!');
  679. else {
  680. try {
  681. if (in_array($order['is_channel'], [0, 2])) {
  682. //公众号发送模板消息通知客服
  683. WechatTemplateService::sendAdminNoticeTemplate([
  684. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  685. 'keyword1' => '退款申请',
  686. 'keyword2' => '已支付',
  687. 'keyword3' => date('Y/m/d H:i', time()),
  688. 'remark' => '请及时处理'
  689. ]);
  690. }
  691. if (in_array($order['is_channel'], [1, 2])) {
  692. //小程序 发送模板消息
  693. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  694. }
  695. //通知后台消息提醒
  696. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  697. } catch (\Exception $e) {
  698. }
  699. //发送短信
  700. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  701. return true;
  702. }
  703. }
  704. /**
  705. * //TODO 支付成功后
  706. * @param $orderId
  707. * @param $paytype
  708. * @param $notify
  709. * @return bool
  710. */
  711. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  712. {
  713. $order = self::where('order_id', $orderId)->find();
  714. $resPink = true;
  715. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()]);//订单改为支付
  716. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  717. $oid = self::where('order_id', $orderId)->value('id');
  718. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  719. $now_money = User::where('uid', $order['uid'])->value('now_money');
  720. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  721. self::gainUserIntegral($order);
  722. //支付成功后
  723. event('OrderPaySuccess', [$order, $formId]);
  724. $res = $res1 && $resPink;
  725. return false !== $res;
  726. }
  727. /*
  728. * 线下支付消息通知
  729. * 待完善
  730. *
  731. * */
  732. public static function createOrderTemplate($order)
  733. {
  734. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  735. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  736. // 'first'=>'亲,您购买的商品已支付成功',
  737. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  738. // 'keyword2'=>implode(',',$goodsName),
  739. // 'keyword3'=>$order['order_id'],
  740. // 'remark'=>'点击查看订单详情'
  741. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  742. // RoutineTemplateService::sendAdminNoticeTemplate([
  743. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  744. // 'keyword1'=>'新订单',
  745. // 'keyword2'=>'线下支付',
  746. // 'keyword3'=>date('Y/m/d H:i',time()),
  747. // 'remark'=>'请及时处理'
  748. // ]);
  749. }
  750. /**
  751. * 获取订单详情
  752. * @param $uid
  753. * @param $key
  754. * @return array|\think\Model|null
  755. * @throws \think\db\exception\DataNotFoundException
  756. * @throws \think\db\exception\ModelNotFoundException
  757. * @throws \think\exception\DbException
  758. */
  759. public static function getUserOrderDetail($uid, $key)
  760. {
  761. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  762. }
  763. /**
  764. * TODO 订单发货
  765. * @param array $postageData 发货信息
  766. * @param string $oid orderID
  767. */
  768. public static function orderPostageAfter($postageData, $oid)
  769. {
  770. $order = self::where('id', $oid)->find();
  771. if ($postageData['delivery_type'] == 'send') {//送货
  772. RoutineTemplate::sendOrderPostage($order);
  773. } else if ($postageData['delivery_type'] == 'express') {//发货
  774. RoutineTemplate::sendOrderPostage($order, 1);
  775. }
  776. }
  777. /** 收货后发送模版消息
  778. * @param $order
  779. */
  780. public static function orderTakeAfter($order)
  781. {
  782. $title = self::getProductTitle($order['cart_id']);
  783. if ($order['is_channel'] == 1) {//小程序
  784. RoutineTemplate::sendOrderTakeOver($order, $title);
  785. } else {
  786. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  787. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  788. 'first' => '亲,您的订单已收货',
  789. 'keyword1' => $order['order_id'],
  790. 'keyword2' => '已收货',
  791. 'keyword3' => date('Y-m-d H:i:s', time()),
  792. 'keyword4' => $title,
  793. 'remark' => '感谢您的光临!'
  794. ]);
  795. }
  796. }
  797. /**
  798. * 删除订单
  799. * @param $uni
  800. * @param $uid
  801. * @return bool
  802. */
  803. public static function removeOrder($uni, $uid)
  804. {
  805. $order = self::getUserOrderDetail($uid, $uni);
  806. if (!$order) return self::setErrorInfo('订单不存在!');
  807. $order = self::tidyOrder($order);
  808. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  809. return self::setErrorInfo('该订单无法删除!');
  810. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  811. //未支付和已退款的状态下才可以退积分退库存退优惠券
  812. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  813. event('StoreOrderRegressionAllAfter', [$order]);
  814. }
  815. event('UserOrderRemoved', $uni);
  816. return true;
  817. } else
  818. return self::setErrorInfo('订单删除失败!');
  819. }
  820. /**
  821. * //TODO 用户确认收货
  822. * @param $uni
  823. * @param $uid
  824. */
  825. public static function takeOrder($uni, $uid)
  826. {
  827. $order = self::getUserOrderDetail($uid, $uni);
  828. if (!$order) return self::setErrorInfo('订单不存在!');
  829. $order = self::tidyOrder($order);
  830. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  831. self::beginTrans();
  832. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  833. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  834. try {
  835. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  836. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  837. } catch (\Exception $e) {
  838. self::rollbackTrans();
  839. return self::setErrorInfo($e->getMessage());
  840. }
  841. self::commitTrans();
  842. event('UserLevelAfter', [User::get($uni)]);
  843. event('UserOrderTake', $uni);
  844. //短信通知
  845. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  846. return true;
  847. } else {
  848. self::rollbackTrans();
  849. return false;
  850. }
  851. }
  852. /**
  853. * 获取订单状态购物车等信息
  854. * @param $order
  855. * @param bool $detail 是否获取订单购物车详情
  856. * @param bool $isPic 是否获取订单状态图片
  857. * @return mixed
  858. * @throws \think\db\exception\DataNotFoundException
  859. * @throws \think\db\exception\ModelNotFoundException
  860. * @throws \think\exception\DbException
  861. */
  862. public static function tidyOrder($order, $detail = false, $isPic = false)
  863. {
  864. if ($detail == true && isset($order['id'])) {
  865. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  866. $info = [];
  867. foreach ($cartInfo as $k => $cart) {
  868. $cart = json_decode($cart, true);
  869. $cart['unique'] = $k;
  870. //新增是否评价字段
  871. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  872. array_push($info, $cart);
  873. unset($cart);
  874. }
  875. $order['cartInfo'] = $info;
  876. }
  877. $status = [];
  878. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  879. $status['_type'] = 9;
  880. $status['_title'] = '线下付款';
  881. $status['_msg'] = '商家处理中,请耐心等待';
  882. $status['_class'] = 'nobuy';
  883. } else if (!$order['paid']) {
  884. $status['_type'] = 0;
  885. $status['_title'] = '未支付';
  886. //系统预设取消订单时间段
  887. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  888. //获取配置
  889. $systemValue = SystemConfigService::more($keyValue);
  890. //格式化数据
  891. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  892. if ($order['pink_id'] || $order['combination_id']) {
  893. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  894. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  895. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  896. } else if ($order['seckill_id']) {
  897. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  898. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  899. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  900. } else if ($order['bargain_id']) {
  901. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  902. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  903. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  904. } else {
  905. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  906. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  907. }
  908. $status['_class'] = 'nobuy';
  909. } else if ($order['refund_status'] == 1) {
  910. $status['_type'] = -1;
  911. $status['_title'] = '申请退款中';
  912. $status['_msg'] = '商家审核中,请耐心等待';
  913. $status['_class'] = 'state-sqtk';
  914. } else if ($order['refund_status'] == 2) {
  915. $status['_type'] = -2;
  916. $status['_title'] = '已退款';
  917. $status['_msg'] = '已为您退款,感谢您的支持';
  918. $status['_class'] = 'state-sqtk';
  919. } else if (!$order['status']) {
  920. if ($order['pink_id']) {
  921. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  922. $status['_type'] = 1;
  923. $status['_title'] = '拼团中';
  924. $status['_msg'] = '等待其他人参加拼团';
  925. $status['_class'] = 'state-nfh';
  926. } else {
  927. $status['_type'] = 1;
  928. $status['_title'] = '未发货';
  929. $status['_msg'] = '商家未发货,请耐心等待';
  930. $status['_class'] = 'state-nfh';
  931. }
  932. } else {
  933. if ($order['shipping_type'] === 1) {
  934. $status['_type'] = 1;
  935. $status['_title'] = '未发货';
  936. $status['_msg'] = '商家未发货,请耐心等待';
  937. $status['_class'] = 'state-nfh';
  938. } else {
  939. $status['_type'] = 1;
  940. $status['_title'] = '待核销';
  941. $status['_msg'] = '待核销,请到核销点进行核销';
  942. $status['_class'] = 'state-nfh';
  943. }
  944. }
  945. } else if ($order['status'] == 1) {
  946. if ($order['delivery_type'] == 'send') {//TODO 送货
  947. $status['_type'] = 2;
  948. $status['_title'] = '待收货';
  949. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  950. $status['_class'] = 'state-ysh';
  951. } else {//TODO 发货
  952. $status['_type'] = 2;
  953. $status['_title'] = '待收货';
  954. if ($order['delivery_type'] == 'fictitious')
  955. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  956. else
  957. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  958. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  959. $status['_class'] = 'state-ysh';
  960. }
  961. } else if ($order['status'] == 2) {
  962. $status['_type'] = 3;
  963. $status['_title'] = '待评价';
  964. $status['_msg'] = '已收货,快去评价一下吧';
  965. $status['_class'] = 'state-ypj';
  966. } else if ($order['status'] == 3) {
  967. $status['_type'] = 4;
  968. $status['_title'] = '交易完成';
  969. $status['_msg'] = '交易完成,感谢您的支持';
  970. $status['_class'] = 'state-ytk';
  971. }
  972. if (isset($order['pay_type']))
  973. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  974. if (isset($order['delivery_type']))
  975. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  976. $order['_status'] = $status;
  977. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  978. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  979. $order['status_pic'] = '';
  980. //获取产品状态图片
  981. if ($isPic) {
  982. $order_details_images = sys_data('order_details_images') ?: [];
  983. foreach ($order_details_images as $image) {
  984. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  985. $order['status_pic'] = $image['pic'];
  986. break;
  987. }
  988. }
  989. }
  990. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  991. return $order;
  992. }
  993. /**
  994. * 设置订单查询状态
  995. * @param $status
  996. * @param int $uid
  997. * @param null $model
  998. * @return StoreOrder|null
  999. */
  1000. public static function statusByWhere($status, $uid = 0, $model = null)
  1001. {
  1002. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1003. if ($model == null) $model = new self;
  1004. if ('' === $status)
  1005. return $model;
  1006. else if ($status == 0)//未支付
  1007. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1008. else if ($status == 1)//待发货
  1009. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1010. else if ($status == 2)//待收货
  1011. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1012. else if ($status == 3)//待评价
  1013. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1014. else if ($status == 4)//已完成
  1015. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1016. else if ($status == -1)//退款中
  1017. return $model->where('paid', 1)->where('refund_status', 1);
  1018. else if ($status == -2)//已退款
  1019. return $model->where('paid', 1)->where('refund_status', 2);
  1020. else if ($status == -3)//退款
  1021. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1022. // else if($status == 11){
  1023. // return $model->where('order_id','IN',implode(',',$orderId));
  1024. // }
  1025. else
  1026. return $model;
  1027. }
  1028. /**
  1029. * 获取订单并分页
  1030. * @param $uid
  1031. * @param string $status
  1032. * @param int $page
  1033. * @param int $limit
  1034. * @return mixed
  1035. * @throws \think\db\exception\DataNotFoundException
  1036. * @throws \think\db\exception\ModelNotFoundException
  1037. * @throws \think\exception\DbException
  1038. */
  1039. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1040. {
  1041. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1042. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1043. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1044. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1045. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1046. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1047. foreach ($list as $k => $order) {
  1048. $list[$k] = self::tidyOrder($order, true);
  1049. }
  1050. return $list;
  1051. }
  1052. /**
  1053. * 获取推广人地下用户的订单金额
  1054. * @param string $uid
  1055. * @param string $status
  1056. * @return array
  1057. */
  1058. public static function getUserOrderCount($uid = '', $status = '')
  1059. {
  1060. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1061. return $res;
  1062. }
  1063. /** 订单收货处理积分
  1064. * @param $order
  1065. * @return bool
  1066. */
  1067. public static function gainUserIntegral($order, bool $open = true)
  1068. {
  1069. if ($order['gain_integral'] > 0) {
  1070. $userInfo = User::get($order['uid']);
  1071. $open && BaseModel::beginTrans();
  1072. $integral = bcadd($userInfo['integral'], $order['gain_integral'], 2);
  1073. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => $integral]);
  1074. $res2 = false != UserBill::income('购买商品赠送金豆', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], bcadd($userInfo['integral'], $order['gain_integral'], 2), '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1075. $res = $res1 && $res2;
  1076. $open && BaseModel::checkTrans($res);
  1077. RoutineTemplate::sendUserIntegral($order['uid'], $order, $order['gain_integral'], $integral);
  1078. return $res;
  1079. }
  1080. return true;
  1081. }
  1082. /**
  1083. * 搜索某个订单详细信息
  1084. * @param $uid
  1085. * @param $order_id
  1086. * @return bool|mixed
  1087. * @throws \think\db\exception\DataNotFoundException
  1088. * @throws \think\db\exception\ModelNotFoundException
  1089. * @throws \think\exception\DbException
  1090. */
  1091. public static function searchUserOrder($uid, $order_id)
  1092. {
  1093. $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
  1094. ->order('add_time DESC')->find();
  1095. if (!$order)
  1096. return false;
  1097. else
  1098. return self::tidyOrder($order->toArray(), true);
  1099. }
  1100. /**
  1101. * 订单评价信息记录
  1102. * @param $oid
  1103. * @return StoreOrderStatus|\think\Model
  1104. * @throws \Exception
  1105. */
  1106. public static function orderOver($oid)
  1107. {
  1108. $res = self::edit(['status' => '3'], $oid, 'id');
  1109. if (!$res) exception('评价后置操作失败!');
  1110. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1111. }
  1112. /**
  1113. * 设置订单产品评价完毕事件
  1114. * @param $oid
  1115. * @return StoreOrderStatus|\think\Model
  1116. * @throws \Exception
  1117. */
  1118. public static function checkOrderOver($oid)
  1119. {
  1120. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1121. //订单产品全部评价完成
  1122. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1123. event('StoreProductOrderOver', [$oid]);
  1124. return self::orderOver($oid);
  1125. }
  1126. }
  1127. public static function getOrderStatusNum($uid)
  1128. {
  1129. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1130. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1131. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1132. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1133. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1134. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1135. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1136. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1137. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1138. }
  1139. /**
  1140. * 获取当前订单中有没有拼团存在
  1141. * @param $pid
  1142. * @return int|string
  1143. */
  1144. public static function getIsOrderPink($pid = 0, $uid = 0)
  1145. {
  1146. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1147. }
  1148. /**
  1149. * 获取order_id
  1150. * @param $pid
  1151. * @return mixed
  1152. */
  1153. public static function getStoreIdPink($pid = 0, $uid = 0)
  1154. {
  1155. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1156. }
  1157. /**
  1158. * 删除当前用户拼团未支付的订单
  1159. */
  1160. public static function delCombination()
  1161. {
  1162. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1163. }
  1164. public static function getUserPrice($uid = 0)
  1165. {
  1166. if (!$uid) return 0;
  1167. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1168. $count = 0;
  1169. if ($price) {
  1170. foreach ($price as $v) {
  1171. $count = bcadd($count, $v, 2);
  1172. }
  1173. }
  1174. return $count;
  1175. }
  1176. /**
  1177. * 个人中心获取个人订单列表和订单搜索
  1178. * @param int $uid 用户uid
  1179. * @param int | string 查找订单类型
  1180. * @param int $first 分页
  1181. * @param int 每页显示多少条
  1182. * @param string $search 订单号
  1183. * @return array
  1184. * */
  1185. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1186. {
  1187. if ($search) {
  1188. $order = self::searchUserOrder($uid, $search) ?: [];
  1189. $list = $order == false ? [] : [$order];
  1190. } else {
  1191. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1192. }
  1193. foreach ($list as $k => $order) {
  1194. $list[$k] = self::tidyOrder($order, true);
  1195. if ($list[$k]['_status']['_type'] == 3) {
  1196. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1197. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1198. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1199. }
  1200. }
  1201. }
  1202. return $list;
  1203. }
  1204. /**
  1205. * 获取用户下级的订单
  1206. * @param int $xuid 下级用户用户uid
  1207. * @param int $uid 用户uid
  1208. * @param int $type 订单类型
  1209. * @param int $first 截取行数
  1210. * @param int $limit 展示条数
  1211. * @return array
  1212. * */
  1213. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1214. {
  1215. $list = [];
  1216. if (!$xUid) {
  1217. $arr = User::getOneSpreadUid($uid);
  1218. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1219. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1220. foreach ($list as $k => $order) {
  1221. $list[$k] = self::tidyOrder($order, true);
  1222. if ($list[$k]['_status']['_type'] == 3) {
  1223. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1224. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1225. }
  1226. }
  1227. }
  1228. return $list;
  1229. }
  1230. /**
  1231. * 获取 今日 昨日 本月 订单金额
  1232. * @return mixed
  1233. */
  1234. public static function getOrderTimeData()
  1235. {
  1236. $to_day = strtotime(date('Y-m-d'));//今日
  1237. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1238. $now_month = strtotime(date('Y-m'));//本月
  1239. //今日成交额
  1240. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1241. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1242. //今日订单数
  1243. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1244. //昨日成交额
  1245. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1246. //昨日订单数
  1247. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1248. //本月成交额
  1249. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1250. //本月订单数
  1251. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1252. return $data;
  1253. }
  1254. /**
  1255. * 获取某个用户的订单统计数据
  1256. * @param $uid
  1257. * @return mixed
  1258. */
  1259. public static function getOrderData($uid)
  1260. {
  1261. //订单支付没有退款 数量
  1262. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1263. //订单支付没有退款 支付总金额
  1264. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1265. //订单待支付 数量
  1266. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1267. //订单待发货 数量
  1268. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1269. //订单待收货 数量
  1270. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1271. //订单待评价 数量
  1272. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1273. //订单已完成 数量
  1274. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1275. //订单退款
  1276. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1277. return $data;
  1278. }
  1279. /**
  1280. * 获取订单统计数据
  1281. * @param $uid
  1282. * @return mixed
  1283. */
  1284. public static function getOrderDataAdmin()
  1285. {
  1286. //订单支付没有退款 数量
  1287. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1288. //订单支付没有退款 支付总金额
  1289. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1290. //订单待支付 数量
  1291. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1292. //订单待发货 数量
  1293. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1294. //订单待收货 数量
  1295. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1296. //订单待评价 数量
  1297. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1298. //订单已完成 数量
  1299. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1300. //订单退款 数量
  1301. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1302. return $data;
  1303. }
  1304. /**
  1305. * 累计消费
  1306. * @param $uid
  1307. * @return float
  1308. */
  1309. public static function getOrderStatusSum($uid)
  1310. {
  1311. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1312. }
  1313. public static function getPinkOrderId($id)
  1314. {
  1315. return self::where('id', $id)->value('order_id');
  1316. }
  1317. /**
  1318. * 未支付订单自动取消
  1319. * @param int $limit 分页截取条数
  1320. * @param string $prefid 缓存名称
  1321. * @param int $expire 缓存时间
  1322. * @return string|null
  1323. * @throws \Psr\SimpleCache\InvalidArgumentException
  1324. */
  1325. public static function orderUnpaidCancel()
  1326. {
  1327. //系统预设取消订单时间段
  1328. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1329. //获取配置
  1330. $systemValue = SystemConfigService::more($keyValue);
  1331. //格式化数据
  1332. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1333. //检查是否有未支付的订单 未支付查询条件
  1334. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1335. if (!$unPidCount) return null;
  1336. try {
  1337. $res = true;
  1338. // 未支付查询条件
  1339. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  1340. foreach ($orderList as $order) {
  1341. if ($order['seckill_id']) {
  1342. //优先使用单独配置的过期时间
  1343. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1344. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1345. unset($order_seckill_time);
  1346. } else if ($order['bargain_id']) {
  1347. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1348. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1349. unset($order_bargain_time);
  1350. } else if ($order['pink_id'] || $order['combination_id']) {
  1351. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1352. $res = $res && self::RegressionAll($order_pink_time, $order);
  1353. unset($order_pink_time);
  1354. } else {
  1355. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1356. }
  1357. }
  1358. if (!$res) throw new \Exception('更新错误');
  1359. unset($orderList, $res, $pages);
  1360. return null;
  1361. } catch (PDOException $e) {
  1362. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1363. throw new \Exception($e->getMessage());
  1364. } catch (\think\Exception $e) {
  1365. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1366. throw new \Exception($e->getMessage());
  1367. }
  1368. }
  1369. /**
  1370. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1371. * @param $time 预设时间
  1372. * @param $order 订单详情
  1373. * @return bool
  1374. * @throws \think\db\exception\DataNotFoundException
  1375. * @throws \think\db\exception\ModelNotFoundException
  1376. * @throws \think\exception\DbException
  1377. */
  1378. protected static function RegressionAll($time, $order)
  1379. {
  1380. if ($time == 0) return true;
  1381. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1382. $res1 = self::RegressionStock($order);
  1383. $res2 = self::RegressionIntegral($order);
  1384. $res3 = self::RegressionCoupon($order);
  1385. $res = $res1 && $res2 && $res3;
  1386. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1387. unset($res1, $res2, $res3);
  1388. return $res;
  1389. } else
  1390. return true;
  1391. }
  1392. /**
  1393. * 格式化数据
  1394. * @param array $array 原本数据键
  1395. * @param $value 需要格式化的数据
  1396. * @param int $default 默认值
  1397. * @return mixed
  1398. */
  1399. protected static function setValeTime(array $array, $value, $default = 0)
  1400. {
  1401. foreach ($array as $item) {
  1402. if (!isset($value[$item]))
  1403. $value[$item] = $default;
  1404. else if (is_string($value[$item]))
  1405. $value[$item] = (float)$value[$item];
  1406. }
  1407. return $value;
  1408. }
  1409. public static function getOrderTotalPrice($cartInfo)
  1410. {
  1411. $totalPrice = 0;
  1412. foreach ($cartInfo as $cart) {
  1413. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1414. }
  1415. return $totalPrice;
  1416. }
  1417. public static function getOrderCostPrice($cartInfo)
  1418. {
  1419. $costPrice = 0;
  1420. foreach ($cartInfo as $cart) {
  1421. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1422. }
  1423. return $costPrice;
  1424. }
  1425. public static function getCombinationOrderCostPrice($cartInfo)
  1426. {
  1427. $costPrice = 0;
  1428. foreach ($cartInfo as $cart) {
  1429. if ($cart['combination_id']) {
  1430. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1431. }
  1432. }
  1433. return (float)$costPrice;
  1434. }
  1435. public static function yueRefundAfter($order)
  1436. {
  1437. }
  1438. /**
  1439. * 获取余额支付的金额
  1440. * @param $uid
  1441. * @return float|int
  1442. */
  1443. public static function getOrderStatusYueSum($uid)
  1444. {
  1445. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1446. }
  1447. /**
  1448. * 砍价支付成功订单数量
  1449. * @param $bargain
  1450. * @return int
  1451. */
  1452. public static function getBargainPayCount($bargain)
  1453. {
  1454. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1455. }
  1456. /**
  1457. * 7天自动收货
  1458. * @return bool
  1459. */
  1460. public static function startTakeOrder()
  1461. {
  1462. //7天前时间戳
  1463. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1464. //0为取消自动收货功能
  1465. if ($systemDeliveryTime == 0) return true;
  1466. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1467. $model = new self;
  1468. $model = $model->alias('o');
  1469. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1470. $model = $model->where('o.paid', 1);
  1471. $model = $model->where('s.change_type', 'IN', ['delivery_goods', 'delivery_fictitious', 'delivery']);
  1472. $model = $model->where('s.change_time', '<', $sevenDay);
  1473. $model = $model->where('o.status', 1);
  1474. $model = $model->where('o.refund_status', 0);
  1475. $model = $model->where('o.is_del', 0);
  1476. $orderInfo = $model->column('id', 'id');
  1477. if (!count($orderInfo)) return true;
  1478. $res = true;
  1479. foreach ($orderInfo as $key => &$item) {
  1480. $order = self::get($item);
  1481. if ($order['status'] == 2) continue;
  1482. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1483. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1484. else continue;
  1485. if (!self::edit($data, $item, 'id')) continue;
  1486. try {
  1487. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1488. $res = $res && true;
  1489. } catch (\Exception $e) {
  1490. $res = $res && false;
  1491. }
  1492. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1493. }
  1494. if (!$res) {
  1495. throw new \Exception('');
  1496. }
  1497. }
  1498. /**
  1499. * 获取订单信息
  1500. * @param $id
  1501. * @param string $field
  1502. * @return array|null|\think\Model
  1503. * @throws \think\db\exception\DataNotFoundException
  1504. * @throws \think\db\exception\ModelNotFoundException
  1505. * @throws \think\exception\DbException
  1506. */
  1507. public static function getOrderInfo($id, $field = 'order_id')
  1508. {
  1509. return self::where('id', $id)->field($field)->find();
  1510. }
  1511. /**
  1512. * 订单每月统计数据
  1513. * @param $page
  1514. * @param $limit
  1515. * @return array
  1516. */
  1517. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1518. {
  1519. if (!$limit) return [];
  1520. $model = new self;
  1521. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1522. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1523. $model = $model->where('is_del', 0);
  1524. $model = $model->where('paid', 1);
  1525. $model = $model->where('refund_status', 0);
  1526. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1527. $model = $model->order('pay_time DESC');
  1528. if ($page) $model = $model->page($page, $limit);
  1529. return $model->select();
  1530. }
  1531. /**
  1532. * 前台订单管理订单列表获取
  1533. * @param $where
  1534. * @return mixed
  1535. */
  1536. public static function orderList($where)
  1537. {
  1538. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type')->where('is_del', 0);
  1539. if ($where['order'] != '') {
  1540. $model = $model->order(self::setOrder($where['order']));
  1541. } else {
  1542. $model = $model->order('a.id desc');
  1543. }
  1544. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1545. return self::tidyAdminOrder($data);
  1546. }
  1547. /**
  1548. * 前台订单管理 订单信息设置
  1549. * @param $data
  1550. * @param bool $status
  1551. * @return mixed
  1552. * @throws \think\db\exception\DataNotFoundException
  1553. * @throws \think\db\exception\ModelNotFoundException
  1554. * @throws \think\exception\DbException
  1555. */
  1556. public static function tidyAdminOrder($data, $status = false)
  1557. {
  1558. foreach ($data as &$item) {
  1559. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1560. foreach ($_info as $k => $v) {
  1561. if (!is_array($v['cart_info']))
  1562. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1563. }
  1564. foreach ($_info as $k => $v) {
  1565. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  1566. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1567. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1568. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1569. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1570. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1571. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1572. }
  1573. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1574. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1575. }
  1576. }
  1577. $item['_info'] = $_info;
  1578. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1579. // if($item['pink_id'] || $item['combination_id']){
  1580. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1581. // switch ($pinkStatus){
  1582. // case 1:
  1583. // $item['pink_name'] = '[拼团订单]正在进行中';
  1584. // $item['color'] = '#f00';
  1585. // break;
  1586. // case 2:
  1587. // $item['pink_name'] = '[拼团订单]已完成';
  1588. // $item['color'] = '#00f';
  1589. // break;
  1590. // case 3:
  1591. // $item['pink_name'] = '[拼团订单]未完成';
  1592. // $item['color'] = '#f0f';
  1593. // break;
  1594. // default:
  1595. // $item['pink_name'] = '[拼团订单]历史订单';
  1596. // $item['color'] = '#457856';
  1597. // break;
  1598. // }
  1599. // }elseif ($item['seckill_id']){
  1600. // $item['pink_name'] = '[秒杀订单]';
  1601. // $item['color'] = '#32c5e9';
  1602. // }elseif ($item['bargain_id']){
  1603. // $item['pink_name'] = '[砍价订单]';
  1604. // $item['color'] = '#12c5e9';
  1605. // }else{
  1606. // $item['pink_name'] = '[普通订单]';
  1607. // $item['color'] = '#895612';
  1608. // }
  1609. // if($item['paid']==1){
  1610. // switch ($item['pay_type']){
  1611. // case 'weixin':
  1612. // $item['pay_type_name']='微信支付';
  1613. // break;
  1614. // case 'yue':
  1615. // $item['pay_type_name']='余额支付';
  1616. // break;
  1617. // case 'offline':
  1618. // $item['pay_type_name']='线下支付';
  1619. // break;
  1620. // default:
  1621. // $item['pay_type_name']='其他支付';
  1622. // break;
  1623. // }
  1624. // }else{
  1625. // switch ($item['pay_type']){
  1626. // default:
  1627. // $item['pay_type_name']='未支付';
  1628. // break;
  1629. // case 'offline':
  1630. // $item['pay_type_name']='线下支付';
  1631. // $item['pay_type_info']=1;
  1632. // break;
  1633. // }
  1634. // }
  1635. if ($status) {
  1636. $status = [];
  1637. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1638. $status['_type'] = 9;
  1639. $status['_title'] = '线下付款';
  1640. $status['_msg'] = '商家处理中,请耐心等待';
  1641. $status['_class'] = 'nobuy';
  1642. } else if (!$item['paid']) {
  1643. $status['_type'] = 0;
  1644. $status['_title'] = '未支付';
  1645. //系统预设取消订单时间段
  1646. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1647. //获取配置
  1648. $systemValue = SystemConfigService::more($keyValue);
  1649. //格式化数据
  1650. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1651. if ($item['pink_id'] || $item['combination_id']) {
  1652. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1653. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1654. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1655. } else if ($item['seckill_id']) {
  1656. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1657. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1658. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1659. } else if ($item['bargain_id']) {
  1660. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1661. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1662. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1663. } else {
  1664. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1665. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1666. }
  1667. $status['_class'] = 'nobuy';
  1668. } else if ($item['refund_status'] == 1) {
  1669. $status['_type'] = -1;
  1670. $status['_title'] = '申请退款中';
  1671. $status['_msg'] = '商家审核中,请耐心等待';
  1672. $status['_class'] = 'state-sqtk';
  1673. } else if ($item['refund_status'] == 2) {
  1674. $status['_type'] = -2;
  1675. $status['_title'] = '已退款';
  1676. $status['_msg'] = '已为您退款,感谢您的支持';
  1677. $status['_class'] = 'state-sqtk';
  1678. } else if (!$item['status']) {
  1679. if ($item['pink_id']) {
  1680. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1681. $status['_type'] = 11;
  1682. $status['_title'] = '拼团中';
  1683. $status['_msg'] = '等待其他人参加拼团';
  1684. $status['_class'] = 'state-nfh';
  1685. } else {
  1686. $status['_type'] = 1;
  1687. $status['_title'] = '未发货';
  1688. $status['_msg'] = '商家未发货,请耐心等待';
  1689. $status['_class'] = 'state-nfh';
  1690. }
  1691. } else {
  1692. $status['_type'] = 1;
  1693. $status['_title'] = '未发货';
  1694. $status['_msg'] = '商家未发货,请耐心等待';
  1695. $status['_class'] = 'state-nfh';
  1696. }
  1697. } else if ($item['status'] == 1) {
  1698. if ($item['delivery_type'] == 'send') {//TODO 送货
  1699. $status['_type'] = 2;
  1700. $status['_title'] = '待收货';
  1701. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1702. $status['_class'] = 'state-ysh';
  1703. } else {//TODO 发货
  1704. $status['_type'] = 2;
  1705. $status['_title'] = '待收货';
  1706. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1707. $status['_class'] = 'state-ysh';
  1708. }
  1709. } else if ($item['status'] == 2) {
  1710. $status['_type'] = 3;
  1711. $status['_title'] = '待评价';
  1712. $status['_msg'] = '已收货,快去评价一下吧';
  1713. $status['_class'] = 'state-ypj';
  1714. } else if ($item['status'] == 3) {
  1715. $status['_type'] = 4;
  1716. $status['_title'] = '交易完成';
  1717. $status['_msg'] = '交易完成,感谢您的支持';
  1718. $status['_class'] = 'state-ytk';
  1719. }
  1720. if (isset($item['pay_type']))
  1721. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1722. if (isset($item['delivery_type']))
  1723. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1724. $item['_status'] = $status;
  1725. } else {
  1726. if ($item['paid'] == 0 && $item['status'] == 0) {
  1727. $item['status_name'] = '未支付';
  1728. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1729. $item['status_name'] = '未发货';
  1730. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1731. $item['status_name'] = '待收货';
  1732. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1733. $item['status_name'] = '待评价';
  1734. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1735. $item['status_name'] = '已完成';
  1736. }
  1737. }
  1738. // unset($item['refund_status']);
  1739. // else if($item['paid']==1 && $item['refund_status']==1){
  1740. // $item['status_name']=<<<HTML
  1741. //<b style="color:#f124c7">申请退款</b><br/>
  1742. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1743. //HTML;
  1744. // }else if($item['paid']==1 && $item['refund_status']==2){
  1745. // $item['status_name']='已退款';
  1746. // }
  1747. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1748. // $item['_status']=1;
  1749. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1750. // $item['_status']=2;
  1751. // }else if($item['paid']==1 && $item['refund_status']==1){
  1752. // $item['_status']=3;
  1753. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1754. // $item['_status']=4;
  1755. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1756. // $item['_status']=5;
  1757. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1758. // $item['_status']=6;
  1759. // }else if($item['paid']==1 && $item['refund_status']==2){
  1760. // $item['_status']=7;
  1761. // }
  1762. }
  1763. return $data;
  1764. }
  1765. /**
  1766. * 处理where条件
  1767. * @param $where
  1768. * @param $model
  1769. * @param string $aler
  1770. * @param string $join
  1771. * @return StoreOrder|null
  1772. */
  1773. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1774. {
  1775. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1776. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1777. if (isset($where['combination_id'])) {
  1778. if ($where['combination_id'] == '普通订单') {
  1779. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1780. }
  1781. if ($where['combination_id'] == '拼团订单') {
  1782. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1783. }
  1784. if ($where['combination_id'] == '秒杀订单') {
  1785. $model = $model->where($aler . 'seckill_id', ">", 0);
  1786. }
  1787. if ($where['combination_id'] == '砍价订单') {
  1788. $model = $model->where($aler . 'bargain_id', ">", 0);
  1789. }
  1790. }
  1791. if (isset($where['type'])) {
  1792. switch ($where['type']) {
  1793. case 1:
  1794. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1795. break;
  1796. case 2:
  1797. $model = $model->where($aler . 'combination_id', ">", 0);
  1798. break;
  1799. case 3:
  1800. $model = $model->where($aler . 'seckill_id', ">", 0);
  1801. break;
  1802. case 4:
  1803. $model = $model->where($aler . 'bargain_id', ">", 0);
  1804. break;
  1805. }
  1806. }
  1807. if (isset($where['real_name']) && $where['real_name'] != '')
  1808. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1809. if (isset($where['data']) && $where['data'] !== '')
  1810. $model = self::getModelTime($where, $model, $aler . 'add_time');
  1811. return $model;
  1812. }
  1813. /**
  1814. * 设置where条件
  1815. * @param $status
  1816. * @param null $model
  1817. * @param string $alert
  1818. * @return StoreOrder|null
  1819. */
  1820. public static function statusWhere($status, $model = null, $alert = '')
  1821. {
  1822. if ($model == null) $model = new self;
  1823. if ('' === $status)
  1824. return $model;
  1825. else if ($status == 0)//未支付
  1826. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1827. else if ($status == 1)//已支付 未发货
  1828. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1829. else if ($status == 2)//已支付 待收货
  1830. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  1831. else if ($status == 3)// 已支付 已收货 待评价
  1832. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  1833. else if ($status == 4)// 交易完成
  1834. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  1835. else if ($status == -1)//退款中
  1836. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  1837. else if ($status == -2)//已退款
  1838. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  1839. else if ($status == -3)//退款
  1840. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  1841. else
  1842. return $model;
  1843. }
  1844. /**
  1845. * 订单详情 管理员
  1846. * @param $orderId
  1847. * @param string $field
  1848. * @return array|null|\think\Model
  1849. * @throws \think\db\exception\DataNotFoundException
  1850. * @throws \think\db\exception\ModelNotFoundException
  1851. * @throws \think\exception\DbException
  1852. */
  1853. public static function getAdminOrderDetail($orderId, $field = '*')
  1854. {
  1855. return self::where('order_id', $orderId)->field($field)->find();
  1856. }
  1857. /**
  1858. * 获取指定时间区间的支付金额 管理员
  1859. * @param $start
  1860. * @param $stop
  1861. * @return float
  1862. */
  1863. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  1864. {
  1865. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  1866. }
  1867. /**
  1868. * 获取指定时间区间的支付订单数量 管理员
  1869. * @param $start
  1870. * @param $stop
  1871. * @return float
  1872. */
  1873. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  1874. {
  1875. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  1876. }
  1877. /**
  1878. * 获取当前时间到指定时间的支付金额 管理员
  1879. * @param $start 开始时间
  1880. * @param $stop 结束时间
  1881. * @return mixed
  1882. */
  1883. public static function chartTimePrice($start, $stop)
  1884. {
  1885. $model = new self;
  1886. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  1887. $model = $model->where('is_del', 0);
  1888. $model = $model->where('paid', 1);
  1889. $model = $model->where('refund_status', 0);
  1890. $model = $model->where('add_time', '>=', $start);
  1891. $model = $model->where('add_time', '<', $stop);
  1892. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  1893. $model = $model->order('add_time ASC');
  1894. return $model->select();
  1895. }
  1896. /**
  1897. * 获取当前时间到指定时间的支付订单数 管理员
  1898. * @param $start 开始时间
  1899. * @param $stop 结束时间
  1900. * @return mixed
  1901. */
  1902. public static function chartTimeNumber($start, $stop)
  1903. {
  1904. $model = new self;
  1905. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  1906. $model = $model->where('is_del', 0);
  1907. $model = $model->where('paid', 1);
  1908. $model = $model->where('refund_status', 0);
  1909. $model = $model->where('add_time', '>=', $start);
  1910. $model = $model->where('add_time', '<', $stop);
  1911. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  1912. $model = $model->order('add_time ASC');
  1913. return $model->select();
  1914. }
  1915. /**
  1916. * 修改支付方式为线下支付
  1917. * @param $orderId
  1918. * @return bool
  1919. */
  1920. public static function setOrderTypePayOffline($orderId)
  1921. {
  1922. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  1923. }
  1924. /**
  1925. * 线下付款
  1926. * @param $id
  1927. * @return $this
  1928. */
  1929. public static function updateOffline($id)
  1930. {
  1931. $count = self::where('id', $id)->count();
  1932. if (!$count) return self::setErrorInfo('订单不存在');
  1933. $count = self::where('id', $id)->where('paid', 0)->count();
  1934. if (!$count) return self::setErrorInfo('订单已支付');
  1935. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  1936. return $res;
  1937. }
  1938. /**
  1939. * 向创建订单10分钟未付款的用户发送短信
  1940. */
  1941. public static function sendTen()
  1942. {
  1943. $switch = sys_config('unpaid_order_switch') ? true : false;
  1944. if($switch){
  1945. $list = self::where('paid', 0)
  1946. ->where('is_del', 0)
  1947. ->where('is_system_del', 0)
  1948. ->where('add_time', '>', time() - 900)
  1949. ->where('add_time', '<', time() - 600)
  1950. ->field('order_id,user_phone')
  1951. ->select();
  1952. if ($list) {
  1953. $list = $list->toArray();
  1954. foreach ($list as $phone) {
  1955. ShortLetterRepositories::send(true, $phone['user_phone'], ['order_id' => $phone['order_id']], 'ORDER_PAY_FALSE');
  1956. }
  1957. }
  1958. }
  1959. }
  1960. public function productInfo()
  1961. {
  1962. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  1963. }
  1964. public static function setOrderProductReplyWhere($where)
  1965. {
  1966. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  1967. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  1968. })->with('productInfo', function ($query) use ($where) {
  1969. $alias = '';
  1970. if (isset($where['title']) && $where['title'] != '')
  1971. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  1972. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  1973. if ($where['is_reply'] >= 0) {
  1974. $query->where("{$alias}is_reply", $where['is_reply']);
  1975. } else {
  1976. $query->where("{$alias}is_reply", '>', 0);
  1977. }
  1978. }
  1979. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  1980. $query->where($alias . 'product_id', $where['producr_id']);
  1981. $query->where("{$alias}is_del", 0);
  1982. });
  1983. return $model;
  1984. }
  1985. public static function getOrderProductReplyList($where)
  1986. {
  1987. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  1988. $list = count($list) ? $list->toArray() : [];
  1989. foreach ($list as $key => $item) {
  1990. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  1991. foreach ($item['productInfo'] as $k => $v) {
  1992. if (!$v['nickname'] && $v['uid']) {
  1993. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  1994. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  1995. }
  1996. $v['image'] = '';
  1997. $v['store_name'] = '';
  1998. if ($v['product_id']) {
  1999. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2000. if ($product) {
  2001. $v['image'] = $product['image'];
  2002. $v['store_name'] = $product['store_name'];
  2003. }
  2004. }
  2005. $list[$key]['productInfo'][$k] = $v;
  2006. }
  2007. }
  2008. }
  2009. $count = self::setOrderProductReplyWhere($where)->count();
  2010. return compact('list', 'count');
  2011. }
  2012. /**
  2013. * 验证加入购物车、生成订单时商品得库存以及是否能购买情况
  2014. * @param $uid
  2015. * @param $product_id
  2016. * @param int $cart_num
  2017. * @param string $product_attr_unique
  2018. * @param int $combination_id
  2019. * @param int $seckill_id
  2020. * @param int $bargain_id
  2021. * @return bool
  2022. * @throws \think\db\exception\DataNotFoundException
  2023. * @throws \think\db\exception\DbException
  2024. * @throws \think\db\exception\ModelNotFoundException
  2025. */
  2026. public static function checkProductStock($uid, $product_id, $cart_num = 1, $product_attr_unique = '', $combination_id = 0, $seckill_id = 0, $bargain_id = 0)
  2027. {
  2028. if ($cart_num < 1) $cart_num = 1;
  2029. if (!$product_attr_unique) return self::setErrorInfo('请选择商品属性');
  2030. if ($seckill_id) {
  2031. if (!StoreSeckill::isSeckillEnd($seckill_id))
  2032. return self::setErrorInfo('活动已结束');
  2033. $StoreSeckillinfo = StoreSeckill::getValidProduct($seckill_id);
  2034. if (!$StoreSeckillinfo)
  2035. return self::setErrorInfo('该产品已下架或删除');
  2036. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('seckill_id', $seckill_id)->sum('total_num');
  2037. if ($StoreSeckillinfo['num'] <= $userbuycount || $StoreSeckillinfo['num'] < $cart_num)
  2038. return self::setErrorInfo('每人限购' . $StoreSeckillinfo['num'] . '件');
  2039. $res = StoreProductAttrValue::where('product_id', $seckill_id)->where('unique', $product_attr_unique)->where('type', 1)->field('suk,quota')->find();
  2040. if ($cart_num > $res['quota'])
  2041. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2042. $product_stock = StoreProductAttrValue::where('product_id', $StoreSeckillinfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2043. if ($product_stock < $cart_num)
  2044. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2045. } elseif ($bargain_id) {
  2046. if (!StoreBargain::validBargain($bargain_id))
  2047. return self::setErrorInfo('该产品已下架或删除');
  2048. $StoreBargainInfo = StoreBargain::getBargain($bargain_id);
  2049. $res = StoreProductAttrValue::where('product_id', $bargain_id)->where('type', 2)->field('suk,quota')->find();
  2050. if ($cart_num > $res['quota'])
  2051. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2052. $product_stock = StoreProductAttrValue::where('product_id', $StoreBargainInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2053. if ($product_stock < $cart_num)
  2054. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2055. } elseif ($combination_id) {//拼团
  2056. $StoreCombinationInfo = StoreCombination::getCombinationOne($combination_id);
  2057. if (!$StoreCombinationInfo)
  2058. return self::setErrorInfo('该产品已下架或删除');
  2059. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('combination_id', $combination_id)->count();
  2060. if ($StoreCombinationInfo['num'] <= $userbuycount || $StoreCombinationInfo['num'] < $cart_num)
  2061. return self::setErrorInfo('每人限购' . $StoreCombinationInfo['num'] . '件');
  2062. $res = StoreProductAttrValue::where('product_id', $combination_id)->where('unique', $product_attr_unique)->where('type', 3)->field('suk,quota')->find();
  2063. if ($cart_num > $res['quota'])
  2064. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2065. $product_stock = StoreProductAttrValue::where('product_id', $StoreCombinationInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2066. if ($product_stock < $cart_num)
  2067. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2068. } else {
  2069. if (!StoreProduct::isValidProduct($product_id))
  2070. return self::setErrorInfo('该产品已下架或删除');
  2071. if (!StoreProductAttr::issetProductUnique($product_id, $product_attr_unique))
  2072. return self::setErrorInfo('请选择有效的产品属性');
  2073. if (StoreProduct::getProductStock($product_id, $product_attr_unique) < $cart_num)
  2074. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2075. }
  2076. return true;
  2077. }
  2078. }