StoreOrder.php 102 KB

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