StoreOrder.php 121 KB

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