StoreOrder.php 102 KB

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