97 lines
3.0 KiB
PHP
97 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Exceptions\BizException;
|
|
use App\Models\Order;
|
|
use App\Models\OrderPackage;
|
|
use App\Models\OrderPackageProduct;
|
|
use Dcat\Admin\Contracts\LazyRenderable;
|
|
use Dcat\Admin\Traits\LazyWidget;
|
|
use Dcat\Admin\Widgets\Form;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class OrderPackageEdit extends Form implements LazyRenderable
|
|
{
|
|
use LazyWidget;
|
|
|
|
/**
|
|
* @param Model|Authenticatable|HasPermissions|null $user
|
|
*
|
|
* @return bool
|
|
*/
|
|
protected function authorize($user): bool
|
|
{
|
|
return $user->can('dcat.admin.order_packages.edit_custom');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$id = $this->payload['id'] ?? 0;
|
|
$packageProductId = $input['package_product_id'];
|
|
$quantity = $input['quantity']??0;
|
|
|
|
$orderPackage = OrderPackage::with('order')->findOrFail($id);
|
|
//如果订单已分润则不处理
|
|
if ($orderPackage->order->is_settle) {
|
|
throw new BizException('该发货单已无法修改数量');
|
|
}
|
|
//修改的数量不能大于当前数量,只能变小
|
|
$packageProduct = OrderPackageProduct::findOrFail($packageProductId);
|
|
if ($quantity == 0) {
|
|
throw new BizException('修改的数量不能为0');
|
|
}
|
|
if ($packageProduct->quantity <= $quantity) {
|
|
throw new BizException('修改的数量不能大于等于当前数量');
|
|
}
|
|
try {
|
|
DB::beginTransaction();
|
|
//更新当前包裹这个商品数量;
|
|
$packageProduct->update([
|
|
'quantity'=>$quantity,
|
|
]);
|
|
//回滚对应订单商品待发货数量;
|
|
$packageProduct->orderProduct->increment('remain_quantity', $packageProduct->quantity - $quantity);
|
|
|
|
//如果订单是已确认收货状态,则回滚到发货中;
|
|
if ($orderPackage->order->isCompleted()) {
|
|
$orderPackage->order()->update([
|
|
'status'=>Order::STATUS_PAID,
|
|
'shipping_state'=>Order::SHIPPING_STATE_PROCESSING,
|
|
'completed_at'=>null,
|
|
]);
|
|
}
|
|
|
|
DB::commit();
|
|
} catch (Throwable $th) {
|
|
DB::rollBack();
|
|
report($th);
|
|
return $this->response()->error('操作失败:'.$th->getMessage());
|
|
}
|
|
|
|
return $this->response()
|
|
->success(__('admin.update_succeeded'))
|
|
->refresh();
|
|
}
|
|
|
|
/**
|
|
* Build a form here.
|
|
*/
|
|
public function form()
|
|
{
|
|
$id = $this->payload['id'] ?? 0;
|
|
$this->select('package_product_id', '包裹商品')
|
|
->options(OrderPackageProduct::with('orderProduct')->where('order_package_id', $id)->get()->pluck('orderProduct.name', 'id'))
|
|
->required();
|
|
$this->number('quantity', '发货数量')->default(1)->min(1)->required();
|
|
}
|
|
}
|