StoreOrder.php 106 KB

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