StoreOrder.php 112 KB

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