StoreOrder.php 123 KB

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