StoreOrder.php 101 KB

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