StoreOrder.php 118 KB

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