StoreOrder.php 121 KB

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