StoreOrder.php 101 KB

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