'下架', self::STATUS_UP => '上架', ]; protected static function boot() { parent::boot(); self::created(function ($model) { self::addStock($model, $model->stock, true); }); } /** * Notes: 操作员 * * @Author: 玄尘 * @Date: 2023/1/11 13:57 * @return BelongsToMany */ public function clerks(): BelongsToMany { return $this->belongsToMany( User::class, (new AreaClerk())->getTable())->using(AreaClerk::class ); } /** * Notes: 操作员 * * @Author: 玄尘 * @Date: 2023/1/11 15:53 * @return HasMany */ public function areaClerks(): HasMany { return $this->hasMany(AreaClerk::class); } /** * Notes: 关联库存变动表 * * @Author: 玄尘 * @Date: 2023/1/11 14:54 * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function stocks(): HasMany { return $this->hasMany(AreaStock::class); } /** * Notes: 关联提货券 * * @Author: 玄尘 * @Date: 2023/1/11 15:43 * @return HasMany */ public function areaCodes(): HasMany { return $this->hasMany(AreaCode::class); } /** * Notes: 增加库存 * * @Author: 玄尘 * @Date: 2023/1/11 14:50 * @param $number */ public static function addStock($area, $number, $isCreate = false) { $stock = $area->stock; if ($isCreate) { $all = $number; } else { $area->increment('stock', $number); $all = bcadd($number, $stock); } $area->stocks()->create([ 'amount' => $number, 'stock' => $all, ]); return true; } /** * Notes: 生成提货码 * * @Author: 玄尘 * @Date: 2023/1/11 16:00 * @param $num */ public function generate($user_id, $num) { try { if (! $num) { throw new \Exception('缺少数量'); } $canStockNum = bcsub($this->stock, $this->areaCodes()->count()); if ($canStockNum < $num) { throw new \Exception('可生成数量不足,您还可以释放'.$canStockNum); } while ($num > 0) { $data[] = [ 'area_id' => $this->id, 'manage_id' => $user_id, 'code' => Str::random(14), 'status' => AreaCode::STATUS_INIT, 'created_at' => now(), 'updated_at' => now(), ]; --$num; } AreaCode::insert($data); return true; } catch (\Exception $exception) { return $exception->getMessage(); } } public function scopeManager(Builder $query, $userid): Builder { return $query->where('user_id', $userid); } }