StoreOrder.php 112 KB

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