StoreOrder.php 126 KB

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