StoreOrder.php 110 KB

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