StoreOrder.php 120 KB

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