StoreOrder.php 111 KB

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