StoreOrder.php 115 KB

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