StoreOrder.php 117 KB

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