StoreOrder.php 135 KB

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