StoreOrder.php 98 KB

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