StoreOrder.php 127 KB

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