HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/dev-beg.teky.com.co/app/Http/Controllers/InventoriesController.php
<?php

namespace App\Http\Controllers;

use App\Item;
use App\Zone;
use App\Storage;
use App\Location;
use App\Inventory;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Common\Entity\Style\CellAlignment;
use Box\Spout\Common\Entity\Style\Color;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Entity\Row;

class InventoriesController extends Controller
{
    public $msj_rollback_import = "";
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($zone_id,$storage_id)
    {
        abort_unless(\Gate::allows('inventory_access'), 403);
        $zone = Zone::where('id', $zone_id)->first();
        $storage = Storage::where('id', $storage_id)->first();
        $inventories = Inventory::where('storage_id', $storage_id)->with(['storage','item','location'])->get();
        return view('inventories.list', compact('inventories', 'storage_id','zone_id', 'zone', 'storage'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($zone_id,$storage_id)
    {
        abort_unless(\Gate::allows('inventory_create'), 403);
        $zone = Zone::where('id', $zone_id)->first();
        $storage = Storage::where('id', $storage_id)->first();
        $items = Item::where('active', true)->orderBy('name', 'asc')->get();
        $locations = Location::where([['storage_id', $storage_id], ['active', true]])
                            ->whereNotExists(function($query)
                            {
                                $query->select(DB::raw(1))->from('inventories')->whereRaw('locations.id = inventories.location_id');
                            })
                            ->get();
        return view('inventories.create', compact('storage_id','items','locations','zone_id', 'zone', 'storage'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        abort_unless(\Gate::allows('inventory_create'), 403);
        try {
            if (!Inventory::where([['storage_id',$request->input('storage_id')],['location_id',$request->input('location_id')]])->first()) {
                Inventory::create(array_slice($request->all(), 1));
                return response(array("status" => true, "type" => "success", "title" => "", "message" => __('created_successfully'), "data" => null));
            } else {
                return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('location_full'), "data" => null));
            }
        } catch (\Throwable $th) {
            return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('error_creating'), "data" => null));
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        abort_unless(\Gate::allows('inventory_show'), 403);
        return redirect()->back();
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($zone_id,$storage_id,$inventory_id)
    {
        abort_unless(\Gate::allows('inventory_edit'), 403);
        $inventory = Inventory::with('item')->findOrFail($inventory_id);
        $items = Item::where('active', true)->orderBy('name', 'asc')->get();
        $locations = Location::where([['storage_id', $storage_id], ['active', true]])->get();
        $zone = Zone::where('id', $zone_id)->first();
        $storage = Storage::where('id', $storage_id)->first();
        return view('inventories.edit', compact('storage_id', 'inventory', 'items', 'locations','zone_id', 'zone', 'storage'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$zone_id,$storage_id,$inventory_id)
    {
        abort_unless(\Gate::allows('inventory_edit'), 403);
        try {
            if (!Inventory::where([['id', '!=', $inventory_id],['storage_id',$request->input('storage_id')],['location_id',$request->input('location_id')]])->first()) {
                Inventory::where('id', $inventory_id)->update(array_slice($request->all(), 2));
                return response(array("status" => true, "type" => "success", "title" => "", "message" => __('updated_successfully'), "data" => null));
            } else {
                return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('location_full'), "data" => null));
            }
        } catch (\Throwable $th) {
            return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('error_updating'), "data" => null));
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($zone_id,$storage_id,$inventory_id)
    {
        abort_unless(\Gate::allows('inventory_destroy'), 403);
        try {
            Inventory::where('id', $inventory_id)->delete();
            return response(array("status" => true, "type" => "success", "title" => "", "message" => __('deleted_successfully'), "data" => null));
        } catch (\Illuminate\Database\QueryException $e) {
            return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('delete_relation_data'), "data" => null));
        }
    }

    public function exportTemplate()
    {
        $writer = WriterEntityFactory::createXLSXWriter();
        $current_date = Carbon::instance(Carbon::now())->format('Y-m-d');
        $writer->openToBrowser("template_".$current_date.".xlsx");
        $sheet = $writer->getCurrentSheet();
        $sheet->setName(__('inventory'));
        $style = (new StyleBuilder())
           ->setFontBold()
           ->setFontSize(10)
           ->setFontColor(Color::BLACK)
           ->setShouldWrapText()
           ->setCellAlignment(CellAlignment::CENTER)
           ->setBackgroundColor(Color::rgb(245, 245, 245))
           ->build();
        $defaultStyle = (new StyleBuilder())
            ->setFormat('@')
            ->build();
        $cells = [
            WriterEntityFactory::createCell(__('item_code'), $defaultStyle),
            WriterEntityFactory::createCell(__('storage_code'), $defaultStyle),
            WriterEntityFactory::createCell(__('location_code'), $defaultStyle),
            WriterEntityFactory::createCell(__('quantity_available'), $defaultStyle),
            WriterEntityFactory::createCell(__('reorder_point'), $defaultStyle),
            WriterEntityFactory::createCell(__('lead_time'), $defaultStyle),
            WriterEntityFactory::createCell(__('lot_size'), $defaultStyle),
            WriterEntityFactory::createCell(__('max_stock_level'), $defaultStyle),
        ];

        $singleRow = WriterEntityFactory::createRow($cells,$style);
        $writer->addRow($singleRow);

        $values = ['12FG', '45HE', '89JK','10','1','2','3','4'];
        $rowFromValues = WriterEntityFactory::createRowFromArray($values, $defaultStyle);
        $writer->addRow($rowFromValues);

        $writer->close();
    }

    public function getValueRow($cells,$index = false)
    {
        if($index !== false){
            return $cells[$index]->getValue();
        }
        return $cells->getValue();
    }

    function is_digits($element) {
        return preg_match('/^[0-9]*$/', $element);
    }

    public function validateCell($cells,$cnt)
    {
        $item = null;
        $storage = null;
        $location = null;
        foreach ($cells as $key => $cell) {
            $value = $this->getValueRow($cell);
            if (($key == 0 || $key == 1 || $key == 2) && trim($value) == "") {
                $this->msj_rollback_import = __('cell_empty', ['column' => $key + 1, 'cell' => $cnt]);
                return false;
                break;
            }

            if($key == 0 && !$item = Item::where('code', $value)->first()){
                $this->msj_rollback_import = __('cell_ids', ['field' => __('item_code'), 'cell' => $cnt]);
                return false;
                break;
            }

            if($key == 1 && !$storage = Storage::where([['code', $value],['active',true]])->first()){
                $this->msj_rollback_import = __('cell_ids', ['field' => __('storage_code'), 'cell' => $cnt]);
                return false;
                break;
            }

            if($storage && $key == 2 && !$location = Location::where([['storage_id', $storage->id],['code', $value],['active',true]])->first()){
                $this->msj_rollback_import = __('cell_ids', ['field' => __('location_code'), 'cell' => $cnt]);
                return false;
                break;
            }

            if($item && $storage && Inventory::where([['storage_id', $storage->id],['location_id', $location->id]])->first()){
                $this->msj_rollback_import = __('relation_already_exist', ['cell' => $cnt]);
                return false;
                break;
            }

            if(($key == 3 || $key == 4 || $key == 7) && !$this->is_digits($value)){
                $this->msj_rollback_import = __('cell_int', ['column' => $key + 1, 'cell' => $cnt]);
                return false;
                break;
            }
        }
        $inventory = new \stdClass();
        $inventory->item_id = $item->id;
        $inventory->storage_id = $storage->id;
        $inventory->location_id = $location->id;
        $inventory->quantity_available = trim($this->getValueRow($cells,3));
        $inventory->reorder_point = trim($this->getValueRow($cells,4));
        $inventory->lead_time = trim($this->getValueRow($cells,5));
        $inventory->lot_size = trim($this->getValueRow($cells,6));
        $inventory->max_stock_level = trim($this->getValueRow($cells,7));
        return json_decode(json_encode($inventory), true);
    }

    public function importTemplate(Request $request)
    {
        DB::beginTransaction();
        try {
            $reader = ReaderEntityFactory::createXLSXReader();
            $reader->open($request->file_inventory);
            $cnt = 0;
            foreach ($reader->getSheetIterator() as $key_sheet => $sheet) {
                if($key_sheet == 1){
                    foreach ($sheet->getRowIterator() as $row) {
                        if($cnt > 0){
                            $cells = $row->getCells();
                            if($inventory = $this->validateCell($cells,$cnt+1)){
                                Inventory::create($inventory);
                            }else{
                                DB::rollback();
                                return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => $this->msj_rollback_import, "data" => null));
                                break;
                            }
                        }
                        $cnt++;
                    }
                }
            }
            DB::commit();
            $reader->close();
            return response(array("status" => true, "type" => "success", "title" => "", "message" => __('import_successfully', ["cnt" => $cnt-1]), "data" => null));
        } catch (\Throwable $e) {
            DB::rollback();
            return response(array("status" => false, "type" => "error", "title" => "Oops...", "message" => __('error_upload_file'), "data" => $e->getMessage()));
        }
    }
}