87 lines
2.8 KiB
PHP
87 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Document;
|
|
use App\Models\DocumentProduct;
|
|
use App\Models\Product;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\View\View;
|
|
|
|
class DocumentController extends Controller
|
|
{
|
|
/**
|
|
* Display a listing of the resource.
|
|
*/
|
|
public function index(): View
|
|
{
|
|
$documents = Document::orderBy('id','desc')->paginate(5);
|
|
|
|
return view('document.index', compact('documents'));
|
|
}
|
|
|
|
/**
|
|
* Show the form for creating a new resource.
|
|
*/
|
|
public function create(): View
|
|
{
|
|
return view('document.create');
|
|
}
|
|
|
|
/**
|
|
* Store a newly created resource in storage.
|
|
*/
|
|
public function store(Request $request): RedirectResponse
|
|
{
|
|
$request->validate([
|
|
'date' => 'required|date',
|
|
'type' => 'required|integer',
|
|
'quantity' => 'required|integer',
|
|
'product_id' => 'required|integer'
|
|
]);
|
|
|
|
$document = Document::create($request->post());
|
|
$product = Product::where(['id' => $request->post('product_id')])->first();
|
|
|
|
if (!empty($product)) {
|
|
$documentProduct = new DocumentProduct();
|
|
$documentProduct->product_id = $product->id;
|
|
$documentProduct->document_id = $document->id;
|
|
$documentProduct->quantity = $request->post('quantity');
|
|
$documentProduct->past_quantity = $product->quantity;
|
|
$documentProduct->save();
|
|
}
|
|
|
|
return redirect()->route('documents.show')->with('success','Document has been created successfully.');
|
|
}
|
|
|
|
public function apply($id): RedirectResponse
|
|
{
|
|
$document = Document::where(['id' => $id])->first();
|
|
// print_r($document->documentProducts);die();
|
|
if ($document->status == Document::STATUS_NOT_APPLIED) {
|
|
$documentProducts = $document->documentProducts;
|
|
if (!empty($documentProducts)) {
|
|
foreach ($documentProducts as $documentProduct) {
|
|
switch ($document->type){
|
|
case Document::TYPE_TO:
|
|
$documentProduct->product->quantity += $documentProduct->quantity;
|
|
$documentProduct->product->save();
|
|
case Document::TYPE_FROM:
|
|
if ($documentProduct->product->quantity >= $documentProduct->quantity) {
|
|
$documentProduct->quantity -= $documentProduct->quantity;
|
|
$documentProduct->product->save();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
$document->status = Document::STATUS_APPLIED;
|
|
$document->save();
|
|
}
|
|
|
|
return redirect()->route('documents.show')->with('success','Document has been applied successfully.');
|
|
}
|
|
}
|