StoreOrder.php 115 KB

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