StoreOrder.php 101 KB

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