StoreOrder.php 103 KB

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