StoreOrder.php 102 KB

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