jingcai-php/app/Model/Seller/Shop.php

109 lines
2.9 KiB
PHP
Executable File

<?php
namespace App\Model\Seller;
use App\Enums\BoolEnum;
use App\Enums\SellerLevel;
use App\Exceptions\JingCaiException;
use App\Model\BaseModel;
use App\Model\Config;
use App\Model\Traits\PasswordTrait;
use App\Utils\Helps;
use App\Utils\ThrowException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class Shop extends BaseModel
{
use PasswordTrait;
const SHOP_STATUS = [BoolEnum::NO => '关闭', BoolEnum::YES => '正常'];
protected $casts = [
'withdraw_type' => 'array',
];
protected $appends = [
'announcement_img_full_url'
];
public function shopExtra() {
return $this->hasOne(ShopExtra::class, 'shop_id', 'id');
}
public function agentSeller()
{
return $this->hasOne(Seller::class, 'id', 'agent_seller_id');
}
public function getAnnouncementImgFullUrlAttribute()
{
$avatar = $this->announcement_img_url;
if (!$avatar) {
return '';
}
return Helps::fullUrl($avatar);
}
public function balanceActive()
{
return $this->balance_withdraw + $this->balance_cash;
}
public static function generateShopSn($prefix = 'S')
{
$shopSn = new ShopSn();
$shopSn->save();
return $prefix . $shopSn->id;
}
public static function balanceRecharge($shopId, $money)
{
$balanceWithdraw = $money * Config::getShopRechargeWithdrawLv();
$balanceCash = $money - $balanceWithdraw;
return self::balanceIncr($shopId, $balanceCash, $balanceWithdraw);
}
public static function balanceIncr($shopId, $cash, $withdraw = 0)
{
return Shop::where('id', $shopId)->update([
'balance_withdraw' => DB::raw("balance_withdraw + {$withdraw}"),
'balance_cash' => DB::raw("balance_cash + {$cash}"),
]);
}
/**
* 减余额
* @param $money
* @return mixed
*/
public static function balanceReduce($shopId, $money)
{
DB::beginTransaction();
try {
/** @var Shop $shop */
$shop = Shop::lockForUpdate()->find($shopId);
ThrowException::isTrue($shop->balanceActive() < $money, '店铺余额不足');
// 先扣可提现,再扣不可提现
$reduceWithdraw = 0;
$reduceCash = 0;
if ($shop->balance_withdraw >= $money) {
$reduceWithdraw = $money;
} else {
$reduceWithdraw = $shop->balance_withdraw;
$reduceCash = $money - $shop->balance_withdraw;
}
$shop->balance_withdraw -= $reduceWithdraw;
$shop->balance_cash -= $reduceCash;
$shop->save();
DB::commit();
} catch (JingCaiException $exception) {
DB::rollBack();
throw $exception;
} catch (\Exception $exception) {
DB::rollBack();
throw $exception;
}
}
}