Files
duolamaojiazhen/application/api/logic/PointsLogic.php
2026-01-30 18:48:13 +08:00

120 lines
3.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\api\logic;
use app\api\model\OrderPoints;
use think\Db;
use think\Exception;
use app\common\server\UrlServer;
use app\api\logic\UserLogic;
class PointsLogic
{
//获取积分的分类
public static function classify(){
return Db::name('printer_type')->where('del',0)->select();
}
//获取到积分的商品列表
public static function goodslist($clsssId){
$where=[
'brand_id'=>$clsssId,
'del'=>0
];
$goods = Db::name('printer_goods')
->where($where)
->select();
foreach($goods as &$item){
$item['images']=UrlServer::getFileUrl($item['images']);
}
return $goods;
}
//根据ID获取到积分商品
public static function goodsIofo($id){
$data=Db::name('printer_goods')->where('id',$id)->find();
$data['images']=UrlServer::getFileUrl($data['images']);
return $data;
}
/**
* 积分商品下单(扣减积分并生成订单)
* @param array $data ['id','name','price','user_id','number'(可选)]
* @return array
*/
public static function goodsSub($data){
if(empty($data) || !is_array($data)){
return ['code'=>0,'msg'=>'参数错误'];
}
// 基础校验
if(empty($data['id']) || empty($data['user_id']) || !isset($data['price'])){
return ['code'=>0,'msg'=>'参数不完整'];
}
$number = isset($data['number']) && intval($data['number'])>0 ? intval($data['number']) : 1;
$price = floatval($data['price']);
$needIntegral = $price * $number;
Db::startTrans();
try{
// 加锁读取用户积分
$user = Db::name('user')->where('id',$data['user_id'])->lock(true)->find();
if(!$user){
throw new Exception('用户不存在');
}
if($user['user_integral'] < $needIntegral){
throw new Exception('积分不足');
}
$orderData = [
'name' => $data['name'] ?? '',
'goods_id' => $data['id'],
'price' => $price,
'number' => $number,
'user_id' => $data['user_id'],
'create_time' => time(),
'address_id' => $data['addressId'],
'state' => 1
];
$insert = Db::name('printer_order')->insert($orderData);
if(!$insert){
throw new Exception('下单失败');
}
// 扣减积分
Db::name('user')
->where('id',$data['user_id'])
->setDec('user_integral', $needIntegral);
Db::commit();
return ['code'=>1,'msg'=>'兑换成功'];
}catch (\Exception $e){
Db::rollback();
return ['code'=>0,'msg'=>$e->getMessage()];
}
}
//获取积分订单
public static function orderList($userId, $state = null)
{
$order = new OrderPoints();
$query = $order->with([
'address' => function($query){
$query->where('del',0)->field('id,address');
},
'pointsGoods' => function($query){
$query->where('del',0)->field('id,images');
}
])->where('user_id', $userId);
// 如果传了state参数才添加state条件否则查询全部
if($state !== null && $state !== ''){
$query = $query->where('state', $state);
}
$orderArray = $query->paginate(10);
return $orderArray;
}
}