StoreOrder.php 103 KB

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