積分商品兌換

Tang-Wei發表於2021-11-19
<?php

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\Order;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function createOrder()
    {
        $user = $this->request->user();
        $order_sn = get_order_sn('P');
        $goods_id = $this->request->input('goods_id', 1);
        $test = Goods::where('id', $goods_id)->first();
        $goods_integral = $test->integral * $goods_number;
        $order_status = 1;
        $sign_name = '兌換' . mb_substr($test->name, 0, 8, 'utf-8');
        $order = [
            'order_sn' => $order_sn,
            'store_id' => $store_id,
            'goods_id' => $goods_id,
            'goods_number' => $goods_number,
            'goods_integral' => $goods_integral,
            'user_id' => $user->id,
            'order_status' => $order_status,
        ];
        try {
            DB::beginTransaction();
            if ($user->point < $goods_integral) {
                return api_throw('當前賬戶積分餘額不足!');
            }
            User::where('id', $user->id)->update(['point' => $user->point - $goods_integral]);
            $newUser = User::where('id', $user->id)->first();
            UsersSign::create([
                'user_id' => $user->id,
                'sign_name' => $sign_name,
                'sign_num' => '-' . $goods_integral,
                'sign_date' => 0,
                'before_change' => $user->point,
                'before_after' => $newUser->point,
            ]);
            Order::create($order);
            $goods = Goods::where('id', $goods_id)->first();
            if ($goods->stock == 0){
                return api_throw('該商品庫存不足');
            }
            Goods::where('id', $goods_id)->decrement('stock', 1);
            DB::commit();
            return api_return();
        } catch (\Exception $exception) {
            DB::rollBack();
            return api_throw('兌換失敗,' . $exception->getMessage());
    } }
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章