StoreOrder.php 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\store\StoreProductAttrValue;
  9. use app\admin\model\system\ShippingTemplatesFree;
  10. use app\admin\model\system\ShippingTemplatesRegion;
  11. use crmeb\basic\BaseModel;
  12. use think\facade\Cache;
  13. use crmeb\traits\ModelTrait;
  14. use think\facade\Log;
  15. use app\models\system\SystemStore;
  16. use app\models\routine\RoutineTemplate;
  17. use app\models\user\{
  18. User, UserAddress, UserBill, WechatUser
  19. };
  20. use crmeb\services\{
  21. SystemConfigService, WechatTemplateService, workerman\ChannelService
  22. };
  23. use crmeb\repositories\{
  24. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  25. };
  26. use app\admin\model\system\ShippingTemplates;
  27. /**
  28. * TODO 订单Model
  29. * Class StoreOrder
  30. * @package app\models\store
  31. */
  32. class StoreOrder extends BaseModel
  33. {
  34. /**
  35. * 数据表主键
  36. * @var string
  37. */
  38. protected $pk = 'id';
  39. /**
  40. * 模型名称
  41. * @var string
  42. */
  43. protected $name = 'store_order';
  44. use ModelTrait;
  45. protected $insert = ['add_time'];
  46. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付','gp_now_money'=>'报单金额','integral'=>'积分'];
  47. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  48. protected function setAddTimeAttr()
  49. {
  50. return time();
  51. }
  52. protected function setCartIdAttr($value)
  53. {
  54. return is_array($value) ? json_encode($value) : $value;
  55. }
  56. protected function getCartIdAttr($value)
  57. {
  58. return json_decode($value, true);
  59. }
  60. /**获取订单组信息
  61. * @param $cartInfo
  62. * @return array
  63. */
  64. public static function getOrderPriceGroup($cartInfo, $addr)
  65. {
  66. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  67. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  68. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  69. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  70. //如果满额包邮等于0
  71. if (!$storeFreePostage) {
  72. $storePostage = 0;
  73. } else {
  74. if ($addr) {
  75. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  76. $temp_num = [];
  77. foreach ($cartInfo as $cart) {
  78. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  79. if (!$temp) $temp = ShippingTemplates::get(1);
  80. if ($temp->getData('type') == 1) {
  81. $num = $cart['cart_num'];
  82. } elseif ($temp->getData('type') == 2) {
  83. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  84. } else {
  85. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  86. }
  87. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  88. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  89. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  90. if (!$region) {
  91. return self::setErrorInfo('运费模板不存在');
  92. }
  93. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  94. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  95. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  96. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  97. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  98. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  99. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  100. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  101. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  102. } else {
  103. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  104. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  105. }
  106. }
  107. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  108. $type = $storePostage = 0;
  109. foreach ($temp_num as $k => $v) {
  110. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  111. unset($temp_num[$k]);
  112. }
  113. }
  114. foreach ($temp_num as $v) {
  115. if ($type == 0) {
  116. if ($v['number'] <= $v['first']) {
  117. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  118. } else {
  119. if ($v['continue'] <= 0) {
  120. $storePostage = $storePostage;
  121. } else {
  122. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  123. }
  124. }
  125. $type = 1;
  126. } else {
  127. if ($v['continue'] <= 0) {
  128. $storePostage = $storePostage;
  129. } else {
  130. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  131. }
  132. }
  133. }
  134. } else {
  135. $storePostage = 0;
  136. }
  137. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  138. }
  139. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice');
  140. }
  141. /**获取某个字段总金额
  142. * @param $cartInfo
  143. * @param $key 键名
  144. * @return int|string
  145. */
  146. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  147. {
  148. $SumPrice = 0;
  149. foreach ($cartInfo as $cart) {
  150. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  151. }
  152. return $SumPrice;
  153. }
  154. /**
  155. * 拼团
  156. * @param $cartInfo
  157. * @return array
  158. */
  159. public static function getCombinationOrderPriceGroup($cartInfo)
  160. {
  161. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  162. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  163. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  164. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  165. if (!$storeFreePostage) {
  166. $storePostage = 0;
  167. } else {
  168. foreach ($cartInfo as $cart) {
  169. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  170. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  171. }
  172. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  173. }
  174. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  175. }
  176. /**
  177. * 拼团价格
  178. * @param $cartInfo
  179. * @return float
  180. */
  181. public static function getCombinationOrderTotalPrice($cartInfo)
  182. {
  183. $totalPrice = 0;
  184. foreach ($cartInfo as $cart) {
  185. if ($cart['combination_id']) {
  186. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  187. }
  188. }
  189. return (float)$totalPrice;
  190. }
  191. /**
  192. * 缓存订单信息
  193. * @param $uid
  194. * @param $cartInfo
  195. * @param $priceGroup
  196. * @param array $other
  197. * @param int $cacheTime
  198. * @return string
  199. * @throws \Psr\SimpleCache\InvalidArgumentException
  200. */
  201. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  202. {
  203. $key = md5(time());
  204. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  205. return $key;
  206. }
  207. /**
  208. * 获取订单缓存信息
  209. * @param $uid
  210. * @param $key
  211. * @return mixed|null
  212. * @throws \Psr\SimpleCache\InvalidArgumentException
  213. */
  214. public static function getCacheOrderInfo($uid, $key)
  215. {
  216. $cacheName = 'user_order_' . $uid . $key;
  217. if (!Cache::has($cacheName)) return null;
  218. return Cache::get($cacheName);
  219. }
  220. /**
  221. * 删除订单缓存
  222. * @param $uid
  223. * @param $key
  224. */
  225. public static function clearCacheOrderInfo($uid, $key)
  226. {
  227. Cache::delete('user_order_' . $uid . $key);
  228. }
  229. /**
  230. * 生成订单
  231. * @param $uid
  232. * @param $key
  233. * @param $addressId
  234. * @param $payType
  235. * @param bool $useIntegral
  236. * @param int $couponId
  237. * @param string $mark
  238. * @param int $combinationId
  239. * @param int $pinkId
  240. * @param int $seckill_id
  241. * @param int $bargain_id
  242. * @param bool $test
  243. * @param int $isChannel
  244. * @param int $shipping_type
  245. * @param string $real_name
  246. * @param string $phone
  247. * @return StoreOrder|bool|\think\Model
  248. * @throws \think\Exception
  249. * @throws \think\db\exception\DataNotFoundException
  250. * @throws \think\db\exception\ModelNotFoundException
  251. * @throws \think\exception\DbException
  252. */
  253. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  254. {
  255. self::beginTrans();
  256. try {
  257. $shipping_type = (int)$shipping_type;
  258. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  259. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  260. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  261. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  262. $userInfo = User::getUserInfo($uid);
  263. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  264. $cartGroup = self::getCacheOrderInfo($uid, $key);
  265. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  266. $cartInfo = $cartGroup['cartInfo'];
  267. $priceGroup = $cartGroup['priceGroup'];
  268. $other = $cartGroup['other'];
  269. $payPrice = (float)$priceGroup['totalPrice'];
  270. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  271. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  272. $payPostage = 0;
  273. } else {
  274. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  275. }
  276. if ($shipping_type === 1) {
  277. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  278. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  279. return self::setErrorInfo('地址选择有误!', true);
  280. } else {
  281. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  282. $addressInfo['real_name'] = $real_name;
  283. $addressInfo['phone'] = $phone;
  284. $addressInfo['province'] = '';
  285. $addressInfo['city'] = '';
  286. $addressInfo['district'] = '';
  287. $addressInfo['detail'] = '';
  288. }
  289. $cartIds = [];
  290. $totalNum = 0;
  291. $gainIntegral = 0;
  292. foreach ($cartInfo as $cart){
  293. if (!$test && !self::checkProductStock($uid, $cart['product_id'], $cart['cart_num'], $cart['product_attr_unique'], $cart['combination_id'], $cart['seckill_id'], $cart['bargain_id'])) {
  294. return false;
  295. }
  296. $cartIds[] = $cart['id'];
  297. $totalNum += $cart['cart_num'];
  298. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  299. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  300. if (!$combinationId) $combinationId = $cart['combination_id'];
  301. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  302. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  303. }
  304. $deduction = $seckill_id || $bargain_id || $combinationId;
  305. if ($deduction) {
  306. $couponId = 0;
  307. $useIntegral = false;
  308. if (!$test) {
  309. unset(self::$payType['offline']);
  310. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  311. }
  312. }
  313. //使用优惠劵
  314. $res1 = true;
  315. if ($couponId) {
  316. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  317. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  318. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  319. $flag = false;
  320. foreach ($coupons as $coupon) {
  321. if ($coupon['id'] == $couponId) {
  322. $flag = true;
  323. continue;
  324. }
  325. }
  326. if (!$flag)
  327. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  328. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  329. $res1 = StoreCouponUser::useCoupon($couponId);
  330. $couponPrice = $couponInfo['coupon_price'];
  331. } else {
  332. $couponId = 0;
  333. $couponPrice = 0;
  334. }
  335. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  336. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  337. $store_self_mention = sys_config('store_self_mention') ?? 0;
  338. if (!$store_self_mention) $shipping_type = 1;
  339. if ($shipping_type === 1) {
  340. //是否包邮
  341. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  342. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  343. } else if ($shipping_type === 2) {
  344. //门店自提没有邮费支付
  345. $priceGroup['storePostage'] = 0;
  346. $payPostage = 0;
  347. if (!$storeId && !$test) {
  348. return self::setErrorInfo('请选择门店', true);
  349. }
  350. }
  351. //积分抵扣
  352. $res2 = true;
  353. $SurplusIntegral = 0;
  354. if ($useIntegral && $userInfo['integral'] > 0) {
  355. $deductionPrice = (float)bcmul($userInfo['integral'], $other['integralRatio'], 2);
  356. if ($deductionPrice < $payPrice) {
  357. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  358. $usedIntegral = $userInfo['integral'];
  359. $SurplusIntegral = 0;
  360. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  361. } else {
  362. $deductionPrice = $payPrice;
  363. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  364. $SurplusIntegral = bcsub($userInfo['integral'], $usedIntegral, 2);
  365. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  366. $payPrice = 0;
  367. }
  368. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $userInfo['integral'], '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  369. } else {
  370. $deductionPrice = 0;
  371. $usedIntegral = 0;
  372. }
  373. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  374. if ($payPrice <= 0) $payPrice = 0;
  375. if ($test) {
  376. self::rollbackTrans();
  377. return [
  378. 'total_price' => $priceGroup['totalPrice'],
  379. 'pay_price' => $payPrice,
  380. 'pay_postage' => $payPostage,
  381. 'coupon_price' => $couponPrice,
  382. 'deduction_price' => $deductionPrice,
  383. 'SurplusIntegral' => $SurplusIntegral,
  384. ];
  385. }
  386. $orderInfo = [
  387. 'uid' => $uid,
  388. 'order_id' => $test ? 0 : self::getNewOrderId(),
  389. 'real_name' => $addressInfo['real_name'],
  390. 'user_phone' => $addressInfo['phone'],
  391. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  392. 'cart_id' => $cartIds,
  393. 'total_num' => $totalNum,
  394. 'total_price' => $priceGroup['totalPrice'],
  395. 'total_postage' => $priceGroup['storePostage'],
  396. 'coupon_id' => $couponId,
  397. 'coupon_price' => $couponPrice,
  398. 'pay_price' => $payPrice,
  399. 'pay_postage' => $payPostage,
  400. 'deduction_price' => $deductionPrice,
  401. 'paid' => 0,
  402. 'pay_type' => $payType,
  403. 'use_integral' => $usedIntegral,
  404. 'gain_integral' => $gainIntegral,
  405. 'mark' => htmlspecialchars($mark),
  406. 'combination_id' => $combinationId,
  407. 'pink_id' => $pinkId,
  408. 'seckill_id' => $seckill_id,
  409. 'bargain_id' => $bargain_id,
  410. 'cost' => $priceGroup['costPrice'],
  411. 'is_channel' => $isChannel,
  412. 'add_time' => time(),
  413. 'unique' => $key,
  414. 'shipping_type' => $shipping_type,
  415. 'is_gp' => input('gp',0),
  416. 'out_amount' => input('out_amount',0),
  417. 'team' => input('team',0),
  418. 'is_gp' => input('gp',0),
  419. ];
  420. if ($shipping_type === 2) {
  421. $orderInfo['verify_code'] = self::getStoreCode();
  422. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  423. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  424. }
  425. $order = self::create($orderInfo);
  426. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  427. $res5 = true;
  428. foreach ($cartInfo as $cart) {
  429. //减库存加销量
  430. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  431. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  432. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  433. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  434. }
  435. //保存购物车商品信息
  436. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  437. //购物车状态修改
  438. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  439. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  440. //自动设置默认地址
  441. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  442. self::clearCacheOrderInfo($uid, $key);
  443. self::commitTrans();
  444. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  445. return $order;
  446. } catch (\PDOException $e) {
  447. self::rollbackTrans();
  448. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  449. } catch (\Exception $e) {
  450. self::rollbackTrans();
  451. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  452. }
  453. }
  454. /**
  455. * 回退积分
  456. * @param $order 订单信息
  457. * @return bool
  458. */
  459. public static function RegressionIntegral($order)
  460. {
  461. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  462. if ($order['use_integral'] <= 0) return true;
  463. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  464. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  465. if (!$res) return self::setErrorInfo('回退积分增加失败');
  466. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  467. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  468. }
  469. /**
  470. * 回退库存和销量
  471. * @param $order 订单信息
  472. * @return bool
  473. * @throws \think\db\exception\DataNotFoundException
  474. * @throws \think\db\exception\ModelNotFoundException
  475. * @throws \think\exception\DbException
  476. */
  477. public static function RegressionStock($order)
  478. {
  479. if ($order['status'] == -2 || $order['is_del']) return true;
  480. $combinationId = $order['combination_id'];
  481. $seckill_id = $order['seckill_id'];
  482. $bargain_id = $order['bargain_id'];
  483. $res5 = true;
  484. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  485. foreach ($cartInfo as $cart) {
  486. //增库存减销量
  487. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  488. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  489. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id, isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  490. 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'] : '');
  491. }
  492. return $res5;
  493. }
  494. /**
  495. * 回退优惠卷
  496. * @param $order 订单信息
  497. * @return bool
  498. */
  499. public static function RegressionCoupon($order)
  500. {
  501. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  502. $res = true;
  503. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  504. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  505. }
  506. return $res;
  507. }
  508. /**
  509. * 取消订单
  510. * @param string order_id 订单id
  511. * @param $uid
  512. * @return bool
  513. * @throws \think\db\exception\DataNotFoundException
  514. * @throws \think\db\exception\ModelNotFoundException
  515. * @throws \think\exception\DbException
  516. */
  517. public static function cancelOrder($order_id, $uid)
  518. {
  519. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  520. if (!$order) return self::setErrorInfo('没有查到此订单');
  521. self::beginTrans();
  522. try {
  523. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  524. $order->is_del = 1;
  525. if ($res && $order->save()) {
  526. self::commitTrans();
  527. return true;
  528. } else
  529. return false;
  530. } catch (\Exception $e) {
  531. self::rollbackTrans();
  532. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  533. }
  534. }
  535. /**
  536. * 生成订单唯一id
  537. * @param $uid 用户uid
  538. * @return string
  539. */
  540. public static function getNewOrderId()
  541. {
  542. list($msec, $sec) = explode(' ', microtime());
  543. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  544. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  545. if (self::be(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  546. return $orderId;
  547. }
  548. /**
  549. * 修改订单号
  550. * @param $orderId
  551. * @return string
  552. */
  553. public static function changeOrderId($orderId)
  554. {
  555. $ymd = substr($orderId, 2, 8);
  556. $key = substr($orderId, 16);
  557. return 'wx' . $ymd . date('His') . $key;
  558. }
  559. /**
  560. * 查找购物车里的所有产品标题
  561. * @param $cartId 购物车id
  562. * @return bool|string
  563. */
  564. public static function getProductTitle($cartId)
  565. {
  566. $title = '';
  567. try {
  568. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  569. foreach ($orderCart as $item) {
  570. if (isset($item['cart_info']['productInfo']['store_name'])) {
  571. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  572. }
  573. }
  574. unset($item);
  575. if (!$title) {
  576. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  577. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  578. foreach ($productlist as $item) {
  579. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  580. }
  581. }
  582. if ($title) $title = substr($title, 0, strlen($title) - 1);
  583. unset($item);
  584. } catch (\Exception $e) {
  585. }
  586. return $title;
  587. }
  588. /**
  589. * 获取门店自提唯一核销码
  590. * @return bool|string
  591. */
  592. public static function getStoreCode()
  593. {
  594. list($msec, $sec) = explode(' ', microtime());
  595. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  596. if (strlen($num) < 12)
  597. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  598. else
  599. $num = substr($num, 0, 12);
  600. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  601. return $num;
  602. }
  603. /**
  604. * 余额支付
  605. * @param $order_id
  606. * @param $uid
  607. * @param string $formId
  608. * @return bool
  609. * @throws \think\Exception
  610. * @throws \think\db\exception\DataNotFoundException
  611. * @throws \think\db\exception\ModelNotFoundException
  612. * @throws \think\exception\DbException
  613. */
  614. public static function yuePay($order_id, $uid, $formId = '')
  615. {
  616. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  617. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  618. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  619. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  620. $userInfo = User::getUserInfo($uid);
  621. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  622. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  623. self::beginTrans();
  624. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  625. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  626. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  627. try {
  628. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  629. } catch (\Exception $e) {
  630. self::rollbackTrans();
  631. return self::setErrorInfo($e->getMessage());
  632. }
  633. $res = $res1 && $res2 && $res3;
  634. self::checkTrans($res);
  635. return $res;
  636. }
  637. /**
  638. * 积分支付
  639. * @param $order_id
  640. * @param $uid
  641. * @param string $formId
  642. * @return bool
  643. * @throws \think\Exception
  644. * @throws \think\db\exception\DataNotFoundException
  645. * @throws \think\db\exception\ModelNotFoundException
  646. * @throws \think\exception\DbException
  647. */
  648. public static function integralPay($order_id, $uid, $formId = '')
  649. {
  650. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  651. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  652. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  653. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  654. $userInfo = User::getUserInfo($uid);
  655. if ($userInfo['integral'] < $orderInfo['pay_price'])
  656. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '积分不足' . floatval($orderInfo['pay_price'])]);
  657. self::beginTrans();
  658. $res1 = false !== User::bcDec($uid, 'integral', $orderInfo['pay_price'], 'uid');
  659. $res2 = UserBill::expend('购买商品', $uid, 'integral', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '积分支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  660. $res3 = self::paySuccess($order_id, 'integral', $formId);//余额支付成功
  661. try {
  662. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  663. } catch (\Exception $e) {
  664. self::rollbackTrans();
  665. return self::setErrorInfo($e->getMessage());
  666. }
  667. $res = $res1 && $res2 && $res3;
  668. self::checkTrans($res);
  669. return $res;
  670. }
  671. /**
  672. * 报单余额支付
  673. * @param $order_id
  674. * @param $uid
  675. * @param string $formId
  676. * @return bool
  677. * @throws \think\Exception
  678. * @throws \think\db\exception\DataNotFoundException
  679. * @throws \think\db\exception\ModelNotFoundException
  680. * @throws \think\exception\DbException
  681. */
  682. public static function gp_now_moneyPay($order_id, $uid, $formId = '')
  683. {
  684. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  685. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  686. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  687. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  688. $userInfo = User::getUserInfo($uid);
  689. if ($userInfo['gp_now_money'] < $orderInfo['pay_price'])
  690. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '报单余额不足' . floatval($orderInfo['pay_price'])]);
  691. self::beginTrans();
  692. $res1 = false !== User::bcDec($uid, 'gp_now_money', $orderInfo['pay_price'], 'uid');
  693. $res2 = UserBill::expend('购买商品', $uid, 'gp_now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['gp_now_money'], '积分支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  694. $res3 = self::paySuccess($order_id, 'gp_now_money', $formId);//余额支付成功
  695. try {
  696. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  697. } catch (\Exception $e) {
  698. self::rollbackTrans();
  699. return self::setErrorInfo($e->getMessage());
  700. }
  701. $res = $res1 && $res2 && $res3;
  702. self::checkTrans($res);
  703. return $res;
  704. }
  705. /**
  706. * 微信支付 为 0元时
  707. * @param $order_id
  708. * @param $uid
  709. * @param string $formId
  710. * @return bool
  711. * @throws \think\Exception
  712. * @throws \think\db\exception\DataNotFoundException
  713. * @throws \think\db\exception\ModelNotFoundException
  714. * @throws \think\exception\DbException
  715. */
  716. public static function jsPayPrice($order_id, $uid, $formId = '')
  717. {
  718. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  719. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  720. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  721. $userInfo = User::getUserInfo($uid);
  722. self::beginTrans();
  723. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  724. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  725. $res = $res1 && $res2;
  726. self::checkTrans($res);
  727. return $res;
  728. }
  729. /**
  730. * 用户申请退款
  731. * @param $uni
  732. * @param $uid
  733. * @param string $refundReasonWap
  734. * @return bool
  735. */
  736. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  737. {
  738. $order = self::getUserOrderDetail($uid, $uni);
  739. if (!$order) return self::setErrorInfo('支付订单不存在!');
  740. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  741. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  742. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  743. self::beginTrans();
  744. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  745. $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');
  746. $res = $res1 && $res2;
  747. self::checkTrans($res);
  748. if (!$res)
  749. return self::setErrorInfo('申请退款失败!');
  750. else {
  751. try {
  752. if (in_array($order['is_channel'], [0, 2])) {
  753. //公众号发送模板消息通知客服
  754. WechatTemplateService::sendAdminNoticeTemplate([
  755. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  756. 'keyword1' => '退款申请',
  757. 'keyword2' => '已支付',
  758. 'keyword3' => date('Y/m/d H:i', time()),
  759. 'remark' => '请及时处理'
  760. ]);
  761. }
  762. if (in_array($order['is_channel'], [1, 2])) {
  763. //小程序 发送模板消息
  764. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  765. }
  766. //通知后台消息提醒
  767. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  768. } catch (\Exception $e) {
  769. }
  770. //发送短信
  771. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  772. return true;
  773. }
  774. }
  775. /**
  776. * //TODO 支付成功后
  777. * @param $orderId
  778. * @param $paytype
  779. * @param $notify
  780. * @return bool
  781. */
  782. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  783. {
  784. $order = self::where('order_id', $orderId)->find();
  785. $resPink = true;$resGp = true;
  786. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()]);//订单改为支付
  787. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  788. if ($order->is_gp && $res1 && !$order->refund_status) $resGp = StoreGp::createGp($order);//创建公排
  789. $oid = self::where('order_id', $orderId)->value('id');
  790. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  791. $now_money = User::where('uid', $order['uid'])->value('now_money');
  792. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  793. //支付成功后
  794. event('OrderPaySuccess', [$order, $formId]);
  795. $res = $res1 && $resPink && $resGp;
  796. return false !== $res;
  797. }
  798. /*
  799. * 线下支付消息通知
  800. * 待完善
  801. *
  802. * */
  803. public static function createOrderTemplate($order)
  804. {
  805. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  806. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  807. // 'first'=>'亲,您购买的商品已支付成功',
  808. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  809. // 'keyword2'=>implode(',',$goodsName),
  810. // 'keyword3'=>$order['order_id'],
  811. // 'remark'=>'点击查看订单详情'
  812. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  813. // RoutineTemplateService::sendAdminNoticeTemplate([
  814. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  815. // 'keyword1'=>'新订单',
  816. // 'keyword2'=>'线下支付',
  817. // 'keyword3'=>date('Y/m/d H:i',time()),
  818. // 'remark'=>'请及时处理'
  819. // ]);
  820. }
  821. /**
  822. * 获取订单详情
  823. * @param $uid
  824. * @param $key
  825. * @return array|\think\Model|null
  826. * @throws \think\db\exception\DataNotFoundException
  827. * @throws \think\db\exception\ModelNotFoundException
  828. * @throws \think\exception\DbException
  829. */
  830. public static function getUserOrderDetail($uid, $key)
  831. {
  832. return self::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 \think\db\exception\DataNotFoundException
  930. * @throws \think\db\exception\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 \think\db\exception\DataNotFoundException
  1107. * @throws \think\db\exception\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 \think\db\exception\DataNotFoundException
  1140. * @throws \think\db\exception\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 \think\db\exception\DataNotFoundException
  1197. * @throws \think\db\exception\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. * @return mixed
  1307. */
  1308. public static function getOrderTimeData()
  1309. {
  1310. $to_day = strtotime(date('Y-m-d'));//今日
  1311. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1312. $now_month = strtotime(date('Y-m'));//本月
  1313. //今日成交额
  1314. // $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;
  1315. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1316. //今日订单数
  1317. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1318. //昨日成交额
  1319. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1320. //昨日订单数
  1321. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1322. //本月成交额
  1323. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1324. //本月订单数
  1325. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1326. return $data;
  1327. }
  1328. /**
  1329. * 获取某个用户的订单统计数据
  1330. * @param $uid
  1331. * @return mixed
  1332. */
  1333. public static function getOrderData($uid)
  1334. {
  1335. //订单支付没有退款 数量
  1336. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1337. //订单支付没有退款 支付总金额
  1338. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1339. //订单待支付 数量
  1340. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1341. //订单待发货 数量
  1342. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1343. //订单待收货 数量
  1344. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1345. //订单待评价 数量
  1346. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1347. //订单已完成 数量
  1348. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1349. //订单退款
  1350. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1351. return $data;
  1352. }
  1353. /**
  1354. * 获取订单统计数据
  1355. * @param $uid
  1356. * @return mixed
  1357. */
  1358. public static function getOrderDataAdmin()
  1359. {
  1360. //订单支付没有退款 数量
  1361. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1362. //订单支付没有退款 支付总金额
  1363. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1364. //订单待支付 数量
  1365. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1366. //订单待发货 数量
  1367. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1368. //订单待收货 数量
  1369. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1370. //订单待评价 数量
  1371. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1372. //订单已完成 数量
  1373. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1374. //订单退款 数量
  1375. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1376. return $data;
  1377. }
  1378. /**
  1379. * 累计消费
  1380. * @param $uid
  1381. * @return float
  1382. */
  1383. public static function getOrderStatusSum($uid)
  1384. {
  1385. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1386. }
  1387. public static function getPinkOrderId($id)
  1388. {
  1389. return self::where('id', $id)->value('order_id');
  1390. }
  1391. /**
  1392. * 未支付订单自动取消
  1393. * @param int $limit 分页截取条数
  1394. * @param string $prefid 缓存名称
  1395. * @param int $expire 缓存时间
  1396. * @return string|null
  1397. * @throws \Psr\SimpleCache\InvalidArgumentException
  1398. */
  1399. public static function orderUnpaidCancel()
  1400. {
  1401. //系统预设取消订单时间段
  1402. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1403. //获取配置
  1404. $systemValue = SystemConfigService::more($keyValue);
  1405. //格式化数据
  1406. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1407. //检查是否有未支付的订单 未支付查询条件
  1408. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1409. if (!$unPidCount) return null;
  1410. try {
  1411. $res = true;
  1412. // 未支付查询条件
  1413. $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();
  1414. foreach ($orderList as $order) {
  1415. if ($order['seckill_id']) {
  1416. //优先使用单独配置的过期时间
  1417. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1418. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1419. unset($order_seckill_time);
  1420. } else if ($order['bargain_id']) {
  1421. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1422. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1423. unset($order_bargain_time);
  1424. } else if ($order['pink_id'] || $order['combination_id']) {
  1425. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1426. $res = $res && self::RegressionAll($order_pink_time, $order);
  1427. unset($order_pink_time);
  1428. } else {
  1429. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1430. }
  1431. }
  1432. if (!$res) throw new \Exception('更新错误');
  1433. unset($orderList, $res, $pages);
  1434. return null;
  1435. } catch (PDOException $e) {
  1436. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1437. throw new \Exception($e->getMessage());
  1438. } catch (\think\Exception $e) {
  1439. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1440. throw new \Exception($e->getMessage());
  1441. }
  1442. }
  1443. /**
  1444. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1445. * @param $time 预设时间
  1446. * @param $order 订单详情
  1447. * @return bool
  1448. * @throws \think\db\exception\DataNotFoundException
  1449. * @throws \think\db\exception\ModelNotFoundException
  1450. * @throws \think\exception\DbException
  1451. */
  1452. protected static function RegressionAll($time, $order)
  1453. {
  1454. if ($time == 0) return true;
  1455. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1456. $res1 = self::RegressionStock($order);
  1457. $res2 = self::RegressionIntegral($order);
  1458. $res3 = self::RegressionCoupon($order);
  1459. $res = $res1 && $res2 && $res3;
  1460. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1461. unset($res1, $res2, $res3);
  1462. return $res;
  1463. } else
  1464. return true;
  1465. }
  1466. /**
  1467. * 格式化数据
  1468. * @param array $array 原本数据键
  1469. * @param $value 需要格式化的数据
  1470. * @param int $default 默认值
  1471. * @return mixed
  1472. */
  1473. protected static function setValeTime(array $array, $value, $default = 0)
  1474. {
  1475. foreach ($array as $item) {
  1476. if (!isset($value[$item]))
  1477. $value[$item] = $default;
  1478. else if (is_string($value[$item]))
  1479. $value[$item] = (float)$value[$item];
  1480. }
  1481. return $value;
  1482. }
  1483. public static function getOrderTotalPrice($cartInfo)
  1484. {
  1485. $totalPrice = 0;
  1486. foreach ($cartInfo as $cart) {
  1487. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1488. }
  1489. return $totalPrice;
  1490. }
  1491. public static function getOrderCostPrice($cartInfo)
  1492. {
  1493. $costPrice = 0;
  1494. foreach ($cartInfo as $cart) {
  1495. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1496. }
  1497. return $costPrice;
  1498. }
  1499. public static function getCombinationOrderCostPrice($cartInfo)
  1500. {
  1501. $costPrice = 0;
  1502. foreach ($cartInfo as $cart) {
  1503. if ($cart['combination_id']) {
  1504. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1505. }
  1506. }
  1507. return (float)$costPrice;
  1508. }
  1509. public static function yueRefundAfter($order)
  1510. {
  1511. }
  1512. /**
  1513. * 获取余额支付的金额
  1514. * @param $uid
  1515. * @return float|int
  1516. */
  1517. public static function getOrderStatusYueSum($uid)
  1518. {
  1519. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1520. }
  1521. /**
  1522. * 砍价支付成功订单数量
  1523. * @param $bargain
  1524. * @return int
  1525. */
  1526. public static function getBargainPayCount($bargain)
  1527. {
  1528. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1529. }
  1530. /**
  1531. * 7天自动收货
  1532. * @return bool
  1533. */
  1534. public static function startTakeOrder()
  1535. {
  1536. //7天前时间戳
  1537. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1538. //0为取消自动收货功能
  1539. if ($systemDeliveryTime == 0) return true;
  1540. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1541. $model = new self;
  1542. $model = $model->alias('o');
  1543. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1544. $model = $model->where('o.paid', 1);
  1545. $model = $model->where('s.change_type', 'IN', ['delivery_goods', 'delivery_fictitious', 'delivery']);
  1546. $model = $model->where('s.change_time', '<', $sevenDay);
  1547. $model = $model->where('o.status', 1);
  1548. $model = $model->where('o.refund_status', 0);
  1549. $model = $model->where('o.is_del', 0);
  1550. $orderInfo = $model->column('id', 'id');
  1551. if (!count($orderInfo)) return true;
  1552. $res = true;
  1553. foreach ($orderInfo as $key => &$item) {
  1554. $order = self::get($item);
  1555. if ($order['status'] == 2) continue;
  1556. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1557. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1558. else continue;
  1559. if (!self::edit($data, $item, 'id')) continue;
  1560. try {
  1561. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1562. $res = $res && true;
  1563. } catch (\Exception $e) {
  1564. $res = $res && false;
  1565. }
  1566. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1567. }
  1568. if (!$res) {
  1569. throw new \Exception('');
  1570. }
  1571. }
  1572. /**
  1573. * 获取订单信息
  1574. * @param $id
  1575. * @param string $field
  1576. * @return array|null|\think\Model
  1577. * @throws \think\db\exception\DataNotFoundException
  1578. * @throws \think\db\exception\ModelNotFoundException
  1579. * @throws \think\exception\DbException
  1580. */
  1581. public static function getOrderInfo($id, $field = 'order_id')
  1582. {
  1583. return self::where('id', $id)->field($field)->find();
  1584. }
  1585. /**
  1586. * 订单每月统计数据
  1587. * @param $page
  1588. * @param $limit
  1589. * @return array
  1590. */
  1591. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1592. {
  1593. if (!$limit) return [];
  1594. $model = new self;
  1595. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1596. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1597. $model = $model->where('is_del', 0);
  1598. $model = $model->where('paid', 1);
  1599. $model = $model->where('refund_status', 0);
  1600. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1601. $model = $model->order('pay_time DESC');
  1602. if ($page) $model = $model->page($page, $limit);
  1603. return $model->select();
  1604. }
  1605. /**
  1606. * 前台订单管理订单列表获取
  1607. * @param $where
  1608. * @return mixed
  1609. */
  1610. public static function orderList($where)
  1611. {
  1612. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type')->where('is_del', 0);
  1613. if ($where['order'] != '') {
  1614. $model = $model->order(self::setOrder($where['order']));
  1615. } else {
  1616. $model = $model->order('a.id desc');
  1617. }
  1618. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1619. return self::tidyAdminOrder($data);
  1620. }
  1621. /**
  1622. * 前台订单管理 订单信息设置
  1623. * @param $data
  1624. * @param bool $status
  1625. * @return mixed
  1626. * @throws \think\db\exception\DataNotFoundException
  1627. * @throws \think\db\exception\ModelNotFoundException
  1628. * @throws \think\exception\DbException
  1629. */
  1630. public static function tidyAdminOrder($data, $status = false)
  1631. {
  1632. foreach ($data as &$item) {
  1633. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1634. foreach ($_info as $k => $v) {
  1635. if (!is_array($v['cart_info']))
  1636. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1637. }
  1638. foreach ($_info as $k => $v) {
  1639. 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']);
  1640. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1641. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1642. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1643. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1644. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1645. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1646. }
  1647. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1648. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1649. }
  1650. }
  1651. $item['_info'] = $_info;
  1652. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1653. // if($item['pink_id'] || $item['combination_id']){
  1654. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1655. // switch ($pinkStatus){
  1656. // case 1:
  1657. // $item['pink_name'] = '[拼团订单]正在进行中';
  1658. // $item['color'] = '#f00';
  1659. // break;
  1660. // case 2:
  1661. // $item['pink_name'] = '[拼团订单]已完成';
  1662. // $item['color'] = '#00f';
  1663. // break;
  1664. // case 3:
  1665. // $item['pink_name'] = '[拼团订单]未完成';
  1666. // $item['color'] = '#f0f';
  1667. // break;
  1668. // default:
  1669. // $item['pink_name'] = '[拼团订单]历史订单';
  1670. // $item['color'] = '#457856';
  1671. // break;
  1672. // }
  1673. // }elseif ($item['seckill_id']){
  1674. // $item['pink_name'] = '[秒杀订单]';
  1675. // $item['color'] = '#32c5e9';
  1676. // }elseif ($item['bargain_id']){
  1677. // $item['pink_name'] = '[砍价订单]';
  1678. // $item['color'] = '#12c5e9';
  1679. // }else{
  1680. // $item['pink_name'] = '[普通订单]';
  1681. // $item['color'] = '#895612';
  1682. // }
  1683. // if($item['paid']==1){
  1684. // switch ($item['pay_type']){
  1685. // case 'weixin':
  1686. // $item['pay_type_name']='微信支付';
  1687. // break;
  1688. // case 'yue':
  1689. // $item['pay_type_name']='余额支付';
  1690. // break;
  1691. // case 'offline':
  1692. // $item['pay_type_name']='线下支付';
  1693. // break;
  1694. // default:
  1695. // $item['pay_type_name']='其他支付';
  1696. // break;
  1697. // }
  1698. // }else{
  1699. // switch ($item['pay_type']){
  1700. // default:
  1701. // $item['pay_type_name']='未支付';
  1702. // break;
  1703. // case 'offline':
  1704. // $item['pay_type_name']='线下支付';
  1705. // $item['pay_type_info']=1;
  1706. // break;
  1707. // }
  1708. // }
  1709. if ($status) {
  1710. $status = [];
  1711. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1712. $status['_type'] = 9;
  1713. $status['_title'] = '线下付款';
  1714. $status['_msg'] = '商家处理中,请耐心等待';
  1715. $status['_class'] = 'nobuy';
  1716. } else if (!$item['paid']) {
  1717. $status['_type'] = 0;
  1718. $status['_title'] = '未支付';
  1719. //系统预设取消订单时间段
  1720. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1721. //获取配置
  1722. $systemValue = SystemConfigService::more($keyValue);
  1723. //格式化数据
  1724. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1725. if ($item['pink_id'] || $item['combination_id']) {
  1726. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1727. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1728. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1729. } else if ($item['seckill_id']) {
  1730. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1731. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1732. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1733. } else if ($item['bargain_id']) {
  1734. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1735. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1736. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1737. } else {
  1738. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1739. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1740. }
  1741. $status['_class'] = 'nobuy';
  1742. } else if ($item['refund_status'] == 1) {
  1743. $status['_type'] = -1;
  1744. $status['_title'] = '申请退款中';
  1745. $status['_msg'] = '商家审核中,请耐心等待';
  1746. $status['_class'] = 'state-sqtk';
  1747. } else if ($item['refund_status'] == 2) {
  1748. $status['_type'] = -2;
  1749. $status['_title'] = '已退款';
  1750. $status['_msg'] = '已为您退款,感谢您的支持';
  1751. $status['_class'] = 'state-sqtk';
  1752. } else if (!$item['status']) {
  1753. if ($item['pink_id']) {
  1754. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1755. $status['_type'] = 11;
  1756. $status['_title'] = '拼团中';
  1757. $status['_msg'] = '等待其他人参加拼团';
  1758. $status['_class'] = 'state-nfh';
  1759. } else {
  1760. $status['_type'] = 1;
  1761. $status['_title'] = '未发货';
  1762. $status['_msg'] = '商家未发货,请耐心等待';
  1763. $status['_class'] = 'state-nfh';
  1764. }
  1765. } else {
  1766. $status['_type'] = 1;
  1767. $status['_title'] = '未发货';
  1768. $status['_msg'] = '商家未发货,请耐心等待';
  1769. $status['_class'] = 'state-nfh';
  1770. }
  1771. } else if ($item['status'] == 1) {
  1772. if ($item['delivery_type'] == 'send') {//TODO 送货
  1773. $status['_type'] = 2;
  1774. $status['_title'] = '待收货';
  1775. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1776. $status['_class'] = 'state-ysh';
  1777. } else {//TODO 发货
  1778. $status['_type'] = 2;
  1779. $status['_title'] = '待收货';
  1780. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1781. $status['_class'] = 'state-ysh';
  1782. }
  1783. } else if ($item['status'] == 2) {
  1784. $status['_type'] = 3;
  1785. $status['_title'] = '待评价';
  1786. $status['_msg'] = '已收货,快去评价一下吧';
  1787. $status['_class'] = 'state-ypj';
  1788. } else if ($item['status'] == 3) {
  1789. $status['_type'] = 4;
  1790. $status['_title'] = '交易完成';
  1791. $status['_msg'] = '交易完成,感谢您的支持';
  1792. $status['_class'] = 'state-ytk';
  1793. }
  1794. if (isset($item['pay_type']))
  1795. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1796. if (isset($item['delivery_type']))
  1797. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1798. $item['_status'] = $status;
  1799. } else {
  1800. if ($item['paid'] == 0 && $item['status'] == 0) {
  1801. $item['status_name'] = '未支付';
  1802. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1803. $item['status_name'] = '未发货';
  1804. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1805. $item['status_name'] = '待收货';
  1806. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1807. $item['status_name'] = '待评价';
  1808. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1809. $item['status_name'] = '已完成';
  1810. }
  1811. }
  1812. // unset($item['refund_status']);
  1813. // else if($item['paid']==1 && $item['refund_status']==1){
  1814. // $item['status_name']=<<<HTML
  1815. //<b style="color:#f124c7">申请退款</b><br/>
  1816. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1817. //HTML;
  1818. // }else if($item['paid']==1 && $item['refund_status']==2){
  1819. // $item['status_name']='已退款';
  1820. // }
  1821. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1822. // $item['_status']=1;
  1823. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1824. // $item['_status']=2;
  1825. // }else if($item['paid']==1 && $item['refund_status']==1){
  1826. // $item['_status']=3;
  1827. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1828. // $item['_status']=4;
  1829. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1830. // $item['_status']=5;
  1831. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1832. // $item['_status']=6;
  1833. // }else if($item['paid']==1 && $item['refund_status']==2){
  1834. // $item['_status']=7;
  1835. // }
  1836. }
  1837. return $data;
  1838. }
  1839. /**
  1840. * 处理where条件
  1841. * @param $where
  1842. * @param $model
  1843. * @param string $aler
  1844. * @param string $join
  1845. * @return StoreOrder|null
  1846. */
  1847. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1848. {
  1849. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1850. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1851. if (isset($where['combination_id'])) {
  1852. if ($where['combination_id'] == '普通订单') {
  1853. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1854. }
  1855. if ($where['combination_id'] == '拼团订单') {
  1856. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1857. }
  1858. if ($where['combination_id'] == '秒杀订单') {
  1859. $model = $model->where($aler . 'seckill_id', ">", 0);
  1860. }
  1861. if ($where['combination_id'] == '砍价订单') {
  1862. $model = $model->where($aler . 'bargain_id', ">", 0);
  1863. }
  1864. }
  1865. if (isset($where['type'])) {
  1866. switch ($where['type']) {
  1867. case 1:
  1868. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1869. break;
  1870. case 2:
  1871. $model = $model->where($aler . 'combination_id', ">", 0);
  1872. break;
  1873. case 3:
  1874. $model = $model->where($aler . 'seckill_id', ">", 0);
  1875. break;
  1876. case 4:
  1877. $model = $model->where($aler . 'bargain_id', ">", 0);
  1878. break;
  1879. }
  1880. }
  1881. if (isset($where['real_name']) && $where['real_name'] != '')
  1882. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1883. if (isset($where['data']) && $where['data'] !== '')
  1884. $model = self::getModelTime($where, $model, $aler . 'add_time');
  1885. return $model;
  1886. }
  1887. /**
  1888. * 设置where条件
  1889. * @param $status
  1890. * @param null $model
  1891. * @param string $alert
  1892. * @return StoreOrder|null
  1893. */
  1894. public static function statusWhere($status, $model = null, $alert = '')
  1895. {
  1896. if ($model == null) $model = new self;
  1897. if ('' === $status)
  1898. return $model;
  1899. else if ($status == 0)//未支付
  1900. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1901. else if ($status == 1)//已支付 未发货
  1902. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1903. else if ($status == 2)//已支付 待收货
  1904. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  1905. else if ($status == 3)// 已支付 已收货 待评价
  1906. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  1907. else if ($status == 4)// 交易完成
  1908. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  1909. else if ($status == -1)//退款中
  1910. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  1911. else if ($status == -2)//已退款
  1912. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  1913. else if ($status == -3)//退款
  1914. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  1915. else
  1916. return $model;
  1917. }
  1918. /**
  1919. * 订单详情 管理员
  1920. * @param $orderId
  1921. * @param string $field
  1922. * @return array|null|\think\Model
  1923. * @throws \think\db\exception\DataNotFoundException
  1924. * @throws \think\db\exception\ModelNotFoundException
  1925. * @throws \think\exception\DbException
  1926. */
  1927. public static function getAdminOrderDetail($orderId, $field = '*')
  1928. {
  1929. return self::where('order_id', $orderId)->field($field)->find();
  1930. }
  1931. /**
  1932. * 获取指定时间区间的支付金额 管理员
  1933. * @param $start
  1934. * @param $stop
  1935. * @return float
  1936. */
  1937. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  1938. {
  1939. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  1940. }
  1941. /**
  1942. * 获取指定时间区间的支付订单数量 管理员
  1943. * @param $start
  1944. * @param $stop
  1945. * @return float
  1946. */
  1947. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  1948. {
  1949. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  1950. }
  1951. /**
  1952. * 获取当前时间到指定时间的支付金额 管理员
  1953. * @param $start 开始时间
  1954. * @param $stop 结束时间
  1955. * @return mixed
  1956. */
  1957. public static function chartTimePrice($start, $stop)
  1958. {
  1959. $model = new self;
  1960. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  1961. $model = $model->where('is_del', 0);
  1962. $model = $model->where('paid', 1);
  1963. $model = $model->where('refund_status', 0);
  1964. $model = $model->where('add_time', '>=', $start);
  1965. $model = $model->where('add_time', '<', $stop);
  1966. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  1967. $model = $model->order('add_time ASC');
  1968. return $model->select();
  1969. }
  1970. /**
  1971. * 获取当前时间到指定时间的支付订单数 管理员
  1972. * @param $start 开始时间
  1973. * @param $stop 结束时间
  1974. * @return mixed
  1975. */
  1976. public static function chartTimeNumber($start, $stop)
  1977. {
  1978. $model = new self;
  1979. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  1980. $model = $model->where('is_del', 0);
  1981. $model = $model->where('paid', 1);
  1982. $model = $model->where('refund_status', 0);
  1983. $model = $model->where('add_time', '>=', $start);
  1984. $model = $model->where('add_time', '<', $stop);
  1985. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  1986. $model = $model->order('add_time ASC');
  1987. return $model->select();
  1988. }
  1989. /**
  1990. * 修改支付方式为线下支付
  1991. * @param $orderId
  1992. * @return bool
  1993. */
  1994. public static function setOrderTypePayOffline($orderId)
  1995. {
  1996. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  1997. }
  1998. /**
  1999. * 线下付款
  2000. * @param $id
  2001. * @return $this
  2002. */
  2003. public static function updateOffline($id)
  2004. {
  2005. $count = self::where('id', $id)->count();
  2006. if (!$count) return self::setErrorInfo('订单不存在');
  2007. $count = self::where('id', $id)->where('paid', 0)->count();
  2008. if (!$count) return self::setErrorInfo('订单已支付');
  2009. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2010. return $res;
  2011. }
  2012. /**
  2013. * 向创建订单10分钟未付款的用户发送短信
  2014. */
  2015. public static function sendTen()
  2016. {
  2017. $switch = sys_config('unpaid_order_switch') ? true : false;
  2018. if($switch){
  2019. $list = self::where('paid', 0)
  2020. ->where('is_del', 0)
  2021. ->where('is_system_del', 0)
  2022. ->where('add_time', '>', time() - 900)
  2023. ->where('add_time', '<', time() - 600)
  2024. ->field('order_id,user_phone')
  2025. ->select();
  2026. if ($list) {
  2027. $list = $list->toArray();
  2028. foreach ($list as $phone) {
  2029. ShortLetterRepositories::send(true, $phone['user_phone'], ['order_id' => $phone['order_id']], 'ORDER_PAY_FALSE');
  2030. }
  2031. }
  2032. }
  2033. }
  2034. public function productInfo()
  2035. {
  2036. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2037. }
  2038. public static function setOrderProductReplyWhere($where)
  2039. {
  2040. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2041. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2042. })->with('productInfo', function ($query) use ($where) {
  2043. $alias = '';
  2044. if (isset($where['title']) && $where['title'] != '')
  2045. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2046. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2047. if ($where['is_reply'] >= 0) {
  2048. $query->where("{$alias}is_reply", $where['is_reply']);
  2049. } else {
  2050. $query->where("{$alias}is_reply", '>', 0);
  2051. }
  2052. }
  2053. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2054. $query->where($alias . 'product_id', $where['producr_id']);
  2055. $query->where("{$alias}is_del", 0);
  2056. });
  2057. return $model;
  2058. }
  2059. public static function getOrderProductReplyList($where)
  2060. {
  2061. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2062. $list = count($list) ? $list->toArray() : [];
  2063. foreach ($list as $key => $item) {
  2064. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2065. foreach ($item['productInfo'] as $k => $v) {
  2066. if (!$v['nickname'] && $v['uid']) {
  2067. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2068. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2069. }
  2070. $v['image'] = '';
  2071. $v['store_name'] = '';
  2072. if ($v['product_id']) {
  2073. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2074. if ($product) {
  2075. $v['image'] = $product['image'];
  2076. $v['store_name'] = $product['store_name'];
  2077. }
  2078. }
  2079. $list[$key]['productInfo'][$k] = $v;
  2080. }
  2081. }
  2082. }
  2083. $count = self::setOrderProductReplyWhere($where)->count();
  2084. return compact('list', 'count');
  2085. }
  2086. /**
  2087. * 验证加入购物车、生成订单时商品得库存以及是否能购买情况
  2088. * @param $uid
  2089. * @param $product_id
  2090. * @param int $cart_num
  2091. * @param string $product_attr_unique
  2092. * @param int $combination_id
  2093. * @param int $seckill_id
  2094. * @param int $bargain_id
  2095. * @return bool
  2096. * @throws \think\db\exception\DataNotFoundException
  2097. * @throws \think\db\exception\DbException
  2098. * @throws \think\db\exception\ModelNotFoundException
  2099. */
  2100. public static function checkProductStock($uid, $product_id, $cart_num = 1, $product_attr_unique = '', $combination_id = 0, $seckill_id = 0, $bargain_id = 0)
  2101. {
  2102. if ($cart_num < 1) $cart_num = 1;
  2103. if (!$product_attr_unique) return self::setErrorInfo('请选择商品属性');
  2104. if ($seckill_id) {
  2105. if (!StoreSeckill::isSeckillEnd($seckill_id))
  2106. return self::setErrorInfo('活动已结束');
  2107. $StoreSeckillinfo = StoreSeckill::getValidProduct($seckill_id);
  2108. if (!$StoreSeckillinfo)
  2109. return self::setErrorInfo('该产品已下架或删除');
  2110. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('seckill_id', $seckill_id)->sum('total_num');
  2111. if ($StoreSeckillinfo['num'] <= $userbuycount || $StoreSeckillinfo['num'] < $cart_num)
  2112. return self::setErrorInfo('每人限购' . $StoreSeckillinfo['num'] . '件');
  2113. $res = StoreProductAttrValue::where('product_id', $seckill_id)->where('unique', $product_attr_unique)->where('type', 1)->field('suk,quota')->find();
  2114. if ($cart_num > $res['quota'])
  2115. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2116. $product_stock = StoreProductAttrValue::where('product_id', $StoreSeckillinfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2117. if ($product_stock < $cart_num)
  2118. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2119. } elseif ($bargain_id) {
  2120. if (!StoreBargain::validBargain($bargain_id))
  2121. return self::setErrorInfo('该产品已下架或删除');
  2122. $StoreBargainInfo = StoreBargain::getBargain($bargain_id);
  2123. $res = StoreProductAttrValue::where('product_id', $bargain_id)->where('type', 2)->field('suk,quota')->find();
  2124. if ($cart_num > $res['quota'])
  2125. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2126. $product_stock = StoreProductAttrValue::where('product_id', $StoreBargainInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2127. if ($product_stock < $cart_num)
  2128. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2129. } elseif ($combination_id) {//拼团
  2130. $StoreCombinationInfo = StoreCombination::getCombinationOne($combination_id);
  2131. if (!$StoreCombinationInfo)
  2132. return self::setErrorInfo('该产品已下架或删除');
  2133. $userbuycount = StoreOrder::where('uid', $uid)->where('paid', 1)->where('combination_id', $combination_id)->count();
  2134. if ($StoreCombinationInfo['num'] <= $userbuycount || $StoreCombinationInfo['num'] < $cart_num)
  2135. return self::setErrorInfo('每人限购' . $StoreCombinationInfo['num'] . '件');
  2136. $res = StoreProductAttrValue::where('product_id', $combination_id)->where('unique', $product_attr_unique)->where('type', 3)->field('suk,quota')->find();
  2137. if ($cart_num > $res['quota'])
  2138. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2139. $product_stock = StoreProductAttrValue::where('product_id', $StoreCombinationInfo['product_id'])->where('suk', $res['suk'])->where('type', 0)->value('stock');
  2140. if ($product_stock < $cart_num)
  2141. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2142. } else {
  2143. if (!StoreProduct::isValidProduct($product_id))
  2144. return self::setErrorInfo('该产品已下架或删除');
  2145. if (!StoreProductAttr::issetProductUnique($product_id, $product_attr_unique))
  2146. return self::setErrorInfo('请选择有效的产品属性');
  2147. if (StoreProduct::getProductStock($product_id, $product_attr_unique) < $cart_num)
  2148. return self::setErrorInfo('该产品库存不足' . $cart_num);
  2149. }
  2150. return true;
  2151. }
  2152. }