StoreOrder.php 107 KB

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