StoreOrder.php 114 KB

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