StoreOrder.php 105 KB

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