403Webshell
Server IP : 14.225.204.176  /  Your IP : 216.73.216.252
Web Server : nginx/1.24.0
System : Linux nodejs-ybgk 6.8.0-40-generic #40-Ubuntu SMP PREEMPT_DYNAMIC Fri Jul 5 10:34:03 UTC 2024 x86_64
User : root ( 0)
PHP Version : 8.1.34
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/html/php/thanhphuong/app/Http/Controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/php/thanhphuong/app/Http/Controllers/WarrantyController.php
<?php

namespace App\Http\Controllers;

use App\Customer;
use App\GeneralSetting;
use App\Product;
use App\Product_Sale;
use App\ProductWarranty;
use App\Sale;
use App\Unit;
use App\Warehouse;
use App\Warranty;
use Auth;
use Carbon\Carbon;
use App\ProductVariant;
use App\Variant;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Keygen\Keygen;
use Spatie\Permission\Models\Role;

class WarrantyController extends Controller
{
    public function index(Request $request)
    {
        $start_date = $request->input('start_date', date('Y-m').'-01');
        $end_date = $request->input('end_date', date('Y-m-d'));
        $start_date = date('Y-m-d', strtotime(str_replace('/', '-', $start_date)));
        $end_date = date('Y-m-d', strtotime(str_replace('/', '-', $end_date)));

        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('warranties-index')) {
            $lims_warranty_list = Warranty::orderBy('id', 'desc')
                ->whereDate('created_at', '>=' , $start_date)
                ->whereDate('created_at', '<=' , $end_date)
                ->get();
            $permissions = Role::findByName($role->name)->permissions;
            foreach ($permissions as $permission) {
                $all_permission[] = $permission->name;
            }
            if (empty($all_permission)) {
                $all_permission[] = 'dummy text';
            }

            return view('warranty.index', compact('start_date', 'end_date', 'lims_warranty_list', 'all_permission'));
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function indexExport(Request $request)
    {
        $start_date = $request->input('start_date', date('Y-m').'-01');
        $end_date = $request->input('end_date', date('Y-m-d'));
        $start_date = date('Y-m-d', strtotime(str_replace('/', '-', $start_date)));
        $end_date = date('Y-m-d', strtotime(str_replace('/', '-', $end_date)));

        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('warranties-index')) {
            $lims_warranty_list = Warranty::orderBy('id', 'desc')
                ->whereDate('created_at', '>=' , $start_date)
                ->whereDate('created_at', '<=' , $end_date)
                ->get();
            $permissions = Role::findByName($role->name)->permissions;
            foreach ($permissions as $permission) {
                $all_permission[] = $permission->name;
            }
            if (empty($all_permission)) {
                $all_permission[] = 'dummy text';
            }

            return view('warranty.index_export', compact('start_date', 'end_date', 'lims_warranty_list', 'all_permission'));
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function warrantyData(Request $request)
    {
      
        $start_date = $request->input('start_date', date('Y-m').'-01');
        $end_date = $request->input('end_date', date('Y-m-d'));
        $start_date = date('Y-m-d', strtotime(str_replace('/', '-', $start_date)));
        $end_date = date('Y-m-d', strtotime(str_replace('/', '-', $end_date)));

        $columns = array(
            1 => 'created_at',
            2 => 'quantity',         
        );

        $start = $request->input('start');
        $query = Warranty::with('customer')
            ->where('warranties.is_active', true)
            ->where('warranties.type', "import")
            ->whereDate('warranties.created_at', '>=' , $start_date)
            ->whereDate('warranties.created_at', '<=' , $end_date);
        $dir = $request->input('order.0.dir');
        switch ($columns[$request->input('order.0.column')]) {
            case 'customer' :
                $order = 'customers.name';
                break;
            case 'phone_number':
                $order = 'customers.phone_number';
                break;
            default:
                $order = 'warranties.' . $columns[$request->input('order.0.column')];
                break;
        }
        if (!empty($request->input('search.value'))) {
            $search = $request->input('search.value');
            $query->where('warranties.note', 'LIKE', "%{$search}%")
                ->orWhere('warranties.name', 'LIKE', "%{$search}%")
                ->orWhere('warranties.warranty_no', 'LIKE', "%{$search}%")
                ->orWhere('customers.name', 'LIKE', "%{$search}%")
                ->orWhere('customers.phone_number', 'LIKE', "%{$search}%");
        }
        $totalData = $totalFiltered = $query->count();
        if ($request->input('length') != -1) {
            $query->limit($request->input('length'));
        }
        $warranties = $query->offset($start)
            ->orderBy($order, $dir)
            ->get();

        $data = array();
        if (!empty($warranties)) {
            foreach ($warranties as $key => $warranty) {
                $nestedData['key'] = $key;
                $nestedData['date'] = date(config('date_format'), strtotime($warranty->created_at->toDateString()));
                $nestedData['id'] = $warranty->id;
                $nestedData['name'] = $warranty->name;
                $nestedData['code'] = $warranty->warranty_no;
                $nestedData['customer'] = "";
                $customer_name = "";
                if($warranty->customer){
                    $nestedData['customer'] = $warranty->customer->name;
                    $customer_name = $warranty->customer->name;
                }
                
                if($warranty->method == "warranty"){
                    $nestedData['method'] = trans("file.Warranty");
                } else {
                    $nestedData['method'] = trans("file.Repair");
                }

                $lims_product_warranty_data = ProductWarranty::where('warranty_id',  $warranty->id)->get();
                $nestedData['product_code'] = "";
                $nestedData['product_name'] = "";
                $nestedData['unit'] = "";
                $nestedData['qty'] = "";
                $nestedData['tr_number'] = "";
                $nestedData['invoice_number'] = "";
                $nestedData['old_batch_number'] = "";
                $nestedData['batch_number'] = "";
                $nestedData['old_serial_number'] = "";
                $nestedData['serial_number'] = "";
                $nestedData['RMA_number'] = "";
                $nestedData['TKHQ_number'] = "";
                $nestedData['invoice_date'] = "";
                $nestedData['fee_repair'] = "";
                $nestedData['fee_exchange'] = "";
                $nestedData['transport_cost'] = "";
                $tr_number = "";
                $invoice_number = "";
                $batch_number = "";

                foreach ($lims_product_warranty_data as $key => $product_warranty_data) {
                    $product = Product::find($product_warranty_data->product_id);
                    if (!empty($product)) {
                        if($product_warranty_data->variant_id){
                            $product_variant_code = ProductVariant::FindExactProduct($product_warranty_data->product_id, $product_warranty_data->variant_id)->first();
                            $product_variant_code = $product_variant_code ? $product_variant_code->item_code : "";
                            $variant_name = Variant::find($product_warranty_data->variant_id);
                            $variant_name = $variant_name ? $variant_name->name : "";
                            $nestedData['product_name'] .=  $variant_name . "<br>";
                            $nestedData['product_code'] .=  $product_variant_code . "<br>";
                        } else {
                            $nestedData['product_name'] .=  $product->name . "<br>";
                            $nestedData['product_code'] .=  $product->code . "<br>";
                        }

                        $unit_data = Unit::find($product->sale_unit_id);
                        if(!empty($unit_data)){
                            $nestedData['unit'] .= $unit_data->unit_name . "<br>";
                        }
                    }

                    $nestedData['qty'] .= number_format($product_warranty_data->qty, 0, '.', '.') . "<br>";
                    $nestedData['tr_number'] .= $product_warranty_data->tr_number . "<br>";
                    $nestedData['invoice_number'] .= $product_warranty_data->invoice_number . "<br>";
                    $nestedData['old_batch_number'] .= $product_warranty_data->old_batch_number . "<br>";
                    $nestedData['batch_number'] .= $product_warranty_data->batch_number . "<br>";
                    $nestedData['old_serial_number'] .= $product_warranty_data->old_serial_number . "<br>";
                    $nestedData['serial_number'] .= $product_warranty_data->serial_number . "<br>";
                    $nestedData['RMA_number'] .= $product_warranty_data->RMA_number . "<br>";
                    $nestedData['invoice_date'] .= date(config('date_format'), strtotime($product_warranty_data->invoice_date)) . "<br>";
                    $nestedData['TKHQ_number'] .= $product_warranty_data->TKHQ_number . "<br>";
                    $nestedData['fee_repair'] .= number_format($product_warranty_data->fee_repair, 2, ',', '.') . "<br>";
                    $nestedData['fee_exchange'] .= number_format($product_warranty_data->fee_exchange, 2, ',', '.') . "<br>";
                    $nestedData['transport_cost'] .= number_format((float)($product_warranty_data->transport_cost), 0, '.', '.') . "<br>";
          
                    if ($product_warranty_data->tr_number) {
                        $tr_number = $product_warranty_data->tr_number;
                    }
                    if ($product_warranty_data->invoice_number) {
                        $invoice_number = $product_warranty_data->invoice_number;
                    }
                    if ($product_warranty_data->batch_number) {
                        $batch_number = $product_warranty_data->batch_number;
                    }
                }

                $nestedData['options'] = '<div class="btn-group">
                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . trans("file.action") . '
                              <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu edit-options dropdown-menu-right dropdown-default" user="menu">
                                <li>
                                    <button type="button" class="btn btn-link view"><i class="fa fa-eye"></i> ' . trans('file.View') . '</button>
                                </li>';
                if (in_array("warranties-edit", $request['all_permission'])) {
                    $nestedData['options'] .= '<li>
                            <a href="' . route('warranties.edit',
                            $warranty->id) . '" class="btn btn-link"><i class="fa fa-edit"></i> ' . trans('file.edit') . '</a>
                        </li>';
                }
                if (in_array("warranties-delete", $request['all_permission'])) {
                    $nestedData['options'] .= \Form::open([
                            "route" => ["warranties.destroy", $warranty->id],
                            "method" => "POST"
                        ]) . '
                            <li>
                              <button type="submit" class="btn btn-link" onclick="return confirmDelete()"><i class="fa fa-trash"></i> ' . trans("file.delete") . '</button>
                            </li>' . \Form::close() . '
                        </ul>
                    </div>';
                }

                $nestedData['warranty'] = array(
                    '[ "' . date(config('date_format'), strtotime($warranty->created_at->toDateString())) . '"', ' "' . $warranty->inventory_receiving_voucher	 . '"', ' "' . $warranty->id . '"', ' "' . $warranty->warehouse_id . '"', ' "' . $warranty->method . '"', ' "' . $warranty->type . '"', ' "' . $warranty->total_qty . '"', ' "' . $warranty->total_allocation_cost . '"', ' "' . $warranty->total_repair_fee . '"', ' "' . $warranty->total_exchange_fee . '"', ' "' . $warranty->total_transport_cost . '"', ' "' . $customer_name . '"', ' "' . $warranty->note . '" ]' );

                $data[] = $nestedData;
            }
        }
        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        echo json_encode($json_data);
    }

    public function warrantyDataExport(Request $request)
    {
        $start_date = $request->input('start_date', date('Y-m').'-01');
        $end_date = $request->input('end_date', date('Y-m-d'));
        $start_date = date('Y-m-d', strtotime(str_replace('/', '-', $start_date)));
        $end_date = date('Y-m-d', strtotime(str_replace('/', '-', $end_date)));

        $columns = array(
            1 => 'created_at',
            2 => 'quantity',
           
        );

        $start = $request->input('start');
        $query = Warranty::with('customer')
            ->where('warranties.is_active', true)
            ->where('warranties.type', "export")
            ->whereDate('warranties.created_at', '>=' , $start_date)
            ->whereDate('warranties.created_at', '<=' , $end_date);
        $dir = $request->input('order.0.dir');
        switch ($columns[$request->input('order.0.column')]) {
            case 'customer' :
                $order = 'customers.name';
                break;
            case 'phone_number':
                $order = 'customers.phone_number';
                break;
            default:
                $order = 'warranties.' . $columns[$request->input('order.0.column')];
                break;
        }
        if (!empty($request->input('search.value'))) {
            $search = $request->input('search.value');
            $query->where('warranties.note', 'LIKE', "%{$search}%")
                ->orWhere('warranties.name', 'LIKE', "%{$search}%")
                ->orWhere('warranties.warranty_no', 'LIKE', "%{$search}%")
                ->orWhere('customers.name', 'LIKE', "%{$search}%")
                ->orWhere('customers.phone_number', 'LIKE', "%{$search}%");
        }
        $totalData = $totalFiltered = $query->count();
        if ($request->input('length') != -1) {
            $query->limit($request->input('length'));
        }
        $warranties = $query->offset($start)
            ->orderBy($order, $dir)
            ->get();

        $data = array();
        if (!empty($warranties)) {
            foreach ($warranties as $key => $warranty) {
                $nestedData['key'] = $key;
                $nestedData['date'] = date(config('date_format'), strtotime($warranty->created_at->toDateString()));
                $nestedData['id'] = $warranty->id;
                $nestedData['name'] = $warranty->name;
                $nestedData['code'] = $warranty->warranty_no;
                $nestedData['customer'] = "";
                $customer_name = "";
                if($warranty->customer){
                    $nestedData['customer'] = $warranty->customer->name;
                    $customer_name = $warranty->customer->name;
                }

                if($warranty->method == "warranty"){
                    $nestedData['method'] = trans("file.Warranty");
                } else {
                    $nestedData['method'] = trans("file.Repair");
                }

                $lims_product_warranty_data = ProductWarranty::where('warranty_id',  $warranty->id)->get();
                $nestedData['product_code'] = "";
                $nestedData['product_name'] = "";
                $nestedData['unit'] = "";
                $nestedData['qty'] = "";
                $nestedData['tr_number'] = "";
                $nestedData['batch_number'] = "";
                $nestedData['serial_number'] = "";
                $nestedData['RMA_number'] = "";
                $nestedData['TKHQ_number'] = "";
                $nestedData['invoice_number'] = "";
                $nestedData['transport_cost'] = "";
                $nestedData['invoice_date'] = "";
                $nestedData['temporary_date'] = "";
                $nestedData['import_date'] = "";
                $tr_number = "";
                $invoice_number = "";
                $batch_number = "";

                foreach ($lims_product_warranty_data as $key => $product_warranty_data) {
                    $product = Product::find($product_warranty_data->product_id);
                    if (!empty($product)) {
                        if($product_warranty_data->variant_id){
                            $product_variant_code = ProductVariant::FindExactProduct($product_warranty_data->product_id, $product_warranty_data->variant_id)->first();
                            $product_variant_code = $product_variant_code ? $product_variant_code->item_code : "";
                            $variant_name = Variant::find($product_warranty_data->variant_id);
                            $variant_name = $variant_name ? $variant_name->name : "";
                            $nestedData['product_name'] .=  $variant_name . "<br>";
                            $nestedData['product_code'] .=  $product_variant_code . "<br>";
                        } else {
                            $nestedData['product_name'] .=  $product->name . "<br>";
                            $nestedData['product_code'] .=  $product->code . "<br>";
                        }

                        $unit_data = Unit::find($product->sale_unit_id);
                        if(!empty($unit_data)){
                            $nestedData['unit'] .= $unit_data->unit_name . "<br>";
                        }
                    }

                    $nestedData['qty'] .= $product_warranty_data->qty . "<br>";
                    $nestedData['tr_number'] .= $product_warranty_data->tr_number . "<br>";
                    $nestedData['invoice_number'] .= $product_warranty_data->invoice_number . "<br>";
                    $nestedData['invoice_date'] .= date(config('date_format'), strtotime($product_warranty_data->invoice_date)) . "<br>";
                    $nestedData['batch_number'] .= $product_warranty_data->batch_number . "<br>";
                    $nestedData['serial_number'] .= $product_warranty_data->serial_number . "<br>";
                    $nestedData['RMA_number'] .= $product_warranty_data->RMA_number . "<br>";
                    $nestedData['TKHQ_number'] .= $product_warranty_data->TKHQ_number . "<br>";
                    $nestedData['temporary_date'] .= date(config('date_format'), strtotime($product_warranty_data->temporary_date)) . "<br>";
                    $nestedData['import_date'] .= date(config('date_format'), strtotime($product_warranty_data->import_date)) . "<br>";
                    $nestedData['transport_cost'] .= number_format((float)($product_warranty_data->transport_cost), 0, '.', '.') . "<br>"; 

                    if ($product_warranty_data->tr_number) {
                        $tr_number = $product_warranty_data->tr_number;
                    }
                    if ($product_warranty_data->invoice_number) {
                        $invoice_number = $product_warranty_data->invoice_number;
                    }
                    if ($product_warranty_data->batch_number) {
                        $batch_number = $product_warranty_data->batch_number;
                    }
                }

                $nestedData['options'] = '<div class="btn-group">
                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . trans("file.action") . '
                              <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu edit-options dropdown-menu-right dropdown-default" user="menu">
                                <li>
                                    <button type="button" class="btn btn-link view"><i class="fa fa-eye"></i> ' . trans('file.View') . '</button>
                                </li>';
                if (in_array("warranties-edit", $request['all_permission'])) {
                    $nestedData['options'] .= '<li>
                            <a href="' . route('warranties.editExport',
                            $warranty->id) . '" class="btn btn-link"><i class="fa fa-edit"></i> ' . trans('file.edit') . '</a>
                        </li>';
                }
                if (in_array("warranties-delete", $request['all_permission'])) {
                    $nestedData['options'] .= \Form::open([
                            "route" => ["warranties.destroy", $warranty->id],
                            "method" => "POST"
                        ]) . '
                            <li>
                              <button type="submit" class="btn btn-link" onclick="return confirmDelete()"><i class="fa fa-trash"></i> ' . trans("file.delete") . '</button>
                            </li>' . \Form::close() . '
                        </ul>
                    </div>';
                }
                $nestedData['warranty'] = array(
                    '[ "' . date(config('date_format'), strtotime($warranty->created_at->toDateString())) . '"', ' "' . $warranty->inventory_delivery_voucher . '"', ' "' . $warranty->id . '"', ' "' . $warranty->warehouse_id . '"', ' "' . $warranty->method . '"', ' "' . $warranty->type . '"', ' "' . $warranty->total_qty . '"', ' "' . $warranty->total_allocation_cost . '"', ' "' . $warranty->total_transport_cost . '"', ' "' . $customer_name . '"', ' "' . $warranty->note . '" ]' );
                
                $data[] = $nestedData;
            }
        }
        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        echo json_encode($json_data);
    }

    public function create(Request $request)
    {
        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('warranties-add')) {
            $lims_product_list_without_variant = $this->productWithoutVariant();
            $lims_product_list_with_variant = $this->productWithVariant();
            $lims_warranty_list = Warranty::where('is_active', true)->get();
            $lims_warehouse_list = Warehouse::where([['is_active', true], ['type', 'store']])->get();
            $date_format = GeneralSetting::select('date_format')->latest()->first();

            return view('warranty.create',
                compact(
                    'lims_product_list_without_variant',
                    'lims_product_list_with_variant',
                    'lims_warranty_list',
                    'lims_warehouse_list',
                    'date_format'
                )
            );
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function createExport(Request $request)
    {
        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('warranties-add')) {
            $lims_product_list_without_variant = $this->productWithoutVariant();
            $lims_product_list_with_variant = $this->productWithVariant();
            $lims_warranty_list = Warranty::where('is_active', true)->get();
            $lims_warehouse_list = Warehouse::where([['is_active', true], ['type', 'store']])->get();
            $date_format = GeneralSetting::select('date_format')->latest()->first();

            return view('warranty.create_export',
                compact(
                    'lims_product_list_without_variant',
                    'lims_product_list_with_variant',
                    'lims_warehouse_list',
                    'date_format'
                )
            );
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function store(Request $request)
    {
        $data = $request->except('document');
        $date_format = GeneralSetting::select('date_format')->latest()->first();
        $customer_id = $data['customer_id'];
        $customer_name = $request->input('customer_name');
        $customer_address = $request->input('customer_address');
        // Create customer if not exist
        if ($customer_id === null && $customer_name && $customer_address) {
            $customer_id = Customer::create([
                "customer_group_id" => 1,
                "user_id" => auth()->id(),
                "name" => $request->input('customer_name'),
                "email" => $request->input('customer_email'),
                "city" => "",
                "phone_number" => $request->input('customer_phone_number'),
                "address" => $request->input('customer_address'),
                "is_active" => true
            ])->id;
            $data['customer_id'] = $customer_id;
        } else if($customer_id !== null){
            $data['customer_id'] = $customer_id;
        } 
        $data['is_active'] = true;
        $data['warranty_no'] = Keygen::numeric(7)->generate();
        if($request->input('purchase_date') !== null){
            $data['purchase_date'] = Carbon::createFromFormat($date_format->date_format, $request->input('purchase_date'));
        } else {
            $data['purchase_date'] = null;
        }

        // Create Warranty
        Warranty::create($data);

        // Create Product Warranty
        $lims_warranty_data = Warranty::latest()->first();
        $fee_repair = $data['fee_repair'];
        $fee_exchange = $data['fee_exchange'];
        $transport_cost = $data['transport_cost'];
        $old_serial_number = $data['old_serial_number'];
        $serial_number = $data['serial_number'];
        $old_batch_number = $data['old_batch_number'];
        $batch_number = $data['batch_number'];
        $tr_number = $data['tr_number'];
        $RMA_number = $data['RMA_number'];
        $TKHQ_number = $data['TKHQ_number'];
        $unit_name = $data['unit_name'];
        $warranty_company = $data['warranty_company'];
        $repair_company = $data['repair_company'];
        $unit_name = $data['unit_name'];
        $invoice_number = $data['invoice_number'];
        $invoice_date = $data['invoice_date'];
        $temporary_date = $data['temporary_date'];
        $import_date = $data['import_date'];
        $product_id = $data['product_id'];
        $qty = $data['qty'];
        $unit_id = $data['unit_id'];
        $product_code = $data['product_code'];
        
        foreach ($product_id as $key => $pro_id) {
            $lims_product_data = Product::find($pro_id);
            if ($lims_product_data->is_variant) {
                $lims_product_variant_data = ProductVariant::select('id', 'variant_id', 'qty')->FindExactProductWithCode($lims_product_data->id, $product_code[$key])->first();
                $product_warranty['variant_id'] = $lims_product_variant_data->variant_id;
            } else {
                $product_warranty['variant_id'] = null;
            }

            $product_warranty['product_id'] = $pro_id;
            $product_warranty['warranty_id'] = $lims_warranty_data->id;
            $product_warranty['qty'] = $qty[$key];
            $product_warranty['unit_id'] = $unit_id[$key];
            $product_warranty['fee_repair'] = $fee_repair[$key];
            $product_warranty['fee_exchange'] = $fee_exchange[$key];
            $product_warranty['transport_cost'] = $transport_cost[$key];
            $product_warranty['old_serial_number'] = $old_serial_number[$key];
            $product_warranty['serial_number'] = $serial_number[$key];
            $product_warranty['old_batch_number'] = $old_batch_number[$key];
            $product_warranty['batch_number'] = $batch_number[$key];
            $product_warranty['tr_number'] = $tr_number[$key];
            $product_warranty['RMA_number'] = $RMA_number[$key];
            $product_warranty['TKHQ_number'] = $TKHQ_number[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['warranty_company'] = $warranty_company[$key];
            $product_warranty['repair_company'] = $repair_company[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['invoice_number'] = $invoice_number[$key];
            $product_warranty['invoice_date'] = isset($invoice_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $invoice_date[$key]) : null;
            $product_warranty['temporary_date'] = isset($temporary_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $temporary_date[$key]) : null;
            $product_warranty['import_date'] = isset($import_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $import_date[$key]) : null;
            $product_warranty['created_at'] = Carbon::now();
            $product_warranty['updated_at'] = Carbon::now();
           
            ProductWarranty::create($product_warranty);
        }
       
        if ($data['type'] == "import") {
            return Redirect::route('warranties.index')->with('success', 'Warranty created successfully');
        } 
        return Redirect::route('warranties.index_export')->with('success', 'Warranty created successfully');
        
    }

    public function productWithoutVariant()
    {
        return Product::ActiveStandard()->select('id', 'name', 'code', DB::raw("CONCAT(code, ' (', replace(name, '\"', ''), ')') as search_code"))
            ->whereNull('is_variant')->get();
    }

    public function productWithVariant()
    {
        return Product::join('product_variants', 'products.id', 'product_variants.product_id')
            ->join('variants', 'product_variants.variant_id', 'variants.id')
            ->ActiveStandard()
            ->whereNotNull('is_variant')
            ->select('products.id', 'variants.name', 'product_variants.item_code', DB::raw("CONCAT(product_variants.item_code, ' (', variants.name, ')') as search_code"))
            ->orderBy('position')
            ->get();
    }

    public function limsProductSearch(Request $request)
    {
        $product_code = explode("(", $request['data']);
        $product_code[0] = rtrim($product_code[0], " ");
        $lims_product_data = Product::where('code', $product_code[0])->first();
        if (!$lims_product_data) {
            $lims_product_data = Product::join('product_variants', 'products.id', 'product_variants.product_id')
                ->select('products.*', 'product_variants.item_code')
                ->where('product_variants.item_code', $product_code[0])
                ->first();
        }

        if ($lims_product_data->is_variant){
            $product_variant_data = ProductVariant::where('item_code', $lims_product_data->item_code)->first();
            $variant_data = Variant::find($product_variant_data->variant_id);
            $product[] = $variant_data->name;
            $product[] = $lims_product_data->item_code;
        }
        else {
            $product[] = $lims_product_data->name;
            $product[] = $lims_product_data->code;
        }

        $role = Role::find(Auth::user()->role_id);
        $permission_view_price = $role->hasPermissionTo('view_price');
        if (!$permission_view_price) {
            $lims_product_data->cost = 0;
        }
        $product[] = $lims_product_data->cost;

        if ($lims_product_data->tax_id) {
            $lims_tax_data = Tax::find($lims_product_data->tax_id);
            $product[] = $lims_tax_data->rate;
            $product[] = $lims_tax_data->name;
        } else {
            $product[] = 0;
            $product[] = 'No Tax';
        }
        $product[] = $lims_product_data->tax_method;

        $units = Unit::where("base_unit", $lims_product_data->unit_id)
            ->orWhere('id', $lims_product_data->unit_id)
            ->get();
        $unit_name = array();
        $unit_id = array();
        $unit_operator = array();
        $unit_operation_value = array();
        foreach ($units as $unit) {
            if ($lims_product_data->purchase_unit_id == $unit->id) {
                array_unshift($unit_name, $unit->unit_name);
                array_unshift($unit_id, $unit->id);
                array_unshift($unit_operator, $unit->operator);
                array_unshift($unit_operation_value, $unit->operation_value);
            } else {
                $unit_name[]  = $unit->unit_name;
                $unit_id[]  = $unit->id;
                $unit_operator[] = $unit->operator;
                $unit_operation_value[] = $unit->operation_value;
            }
        }

        $product[] = implode(",", $unit_name) . ',';
        $product[] = implode(",", $unit_operator) . ',';
        $product[] = implode(",", $unit_operation_value) . ',';
        $product[] = $lims_product_data->id;
        $product[] = implode(",", $unit_id) . ',';
        return $product;
    }
    
    public function createFromSales(Request $request, $sale_id = null)
    {
        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('warranties-add')) {
            $lims_warehouse_list = Warehouse::where([['is_active', true], ['type', 'store']])->get();
            $lims_sales_list = Sale::select('id', 'reference_no')->where('sale_status', 1)->get();
            $lims_product_sale_data = !empty($sale_id) ? Product_Sale::where('sale_id', $sale_id)->get() : [];
            $lims_sale_data = Sale::find($sale_id);
            $lims_unit_list = !empty($lims_sale_data) ? Unit::whereIn('id', $lims_sale_data->products->pluck('unit_id')->unique())->get()->keyBy('id') : [];
            $date_format = GeneralSetting::select('date_format')->latest()->first();
            return view('warranty.create-from-sales',
                compact(
                    'lims_product_sale_data',
                    'lims_sales_list',
                    'lims_warehouse_list',
                    'lims_sale_data',
                    'sale_id',
                    'lims_unit_list',
                    'date_format'
                )
            );
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function edit($id)
    {
        $role = Role::firstOrCreate(['id' => Auth::user()->role_id]);
        if ($role->hasPermissionTo('warranties-edit')) {
            $lims_warranty_data = Warranty::with('customer')->where([
                ['id', $id],
                ['is_active', true]
            ])->firstOrFail();
            $lims_product_list_without_variant = $this->productWithoutVariant();
            $lims_product_list_with_variant = $this->productWithVariant();
            $lims_warranty_list = ProductWarranty::where('warranty_id', $id)->get();
            $lims_warehouse_list = Warehouse::where([['is_active', true], ['type', 'store']])->get();
            $date_format = GeneralSetting::select('date_format')->latest()->first();
            return view('warranty.edit',
                compact(
                    'lims_warranty_list',
                    'lims_warranty_data',
                    'lims_warehouse_list',
                    'lims_product_list_without_variant',
                    'lims_product_list_with_variant',
                    'date_format'
                )
            );
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function update(Request $request, $id)
    {
        $data = $request->except('document');
        $date_format = GeneralSetting::select('date_format')->latest()->first();
        if($request->input('purchase_date') !== null){
            $data['purchase_date'] = Carbon::createFromFormat($date_format->date_format, $request->input('purchase_date'));
        } else {
            $data['purchase_date'] = null;
        }

        $customer_id = $data['customer_id'];
        $customer_name = $request->input('customer_name');
        $customer_address = $request->input('customer_address');
        // Create customer if not exist
        if ($customer_id === null && $customer_name && $customer_address) {
            $customer_id = Customer::create([
                "customer_group_id" => 1,
                "user_id" => auth()->id(),
                "name" => $request->input('customer_name'),
                "email" => $request->input('customer_email'),
                "city" => "",
                "phone_number" => $request->input('customer_phone_number'),
                "address" => $request->input('customer_address'),
                "is_active" => true
            ])->id;
            $data['customer_id'] = $customer_id;
        } else if($customer_id !== null){
            $data['customer_id'] = $customer_id;
        } 

        $lims_warranty_data = Warranty::find($id);
        $lims_product_warranty_data = ProductWarranty::where('warranty_id', $id)->get();

        $fee_repair = $data['fee_repair'];
        $fee_exchange = $data['fee_exchange'];
        $transport_cost = $data['transport_cost'];
        $old_serial_number = $data['old_serial_number'];
        $serial_number = $data['serial_number'];
        $old_batch_number = $data['old_batch_number'];
        $batch_number = $data['batch_number'];
        $tr_number = $data['tr_number'];
        $RMA_number = $data['RMA_number'];
        $TKHQ_number = $data['TKHQ_number'];
        $unit_name = $data['unit_name'];
        $warranty_company = $data['warranty_company'];
        $repair_company = $data['repair_company'];
        $unit_name = $data['unit_name'];
        $invoice_number = $data['invoice_number'];
        $invoice_date = $data['invoice_date'];
        $temporary_date = $data['temporary_date'];
        $import_date = $data['import_date'];
        $product_id = $data['product_id'];
        $unit_id = $data['unit_id'];
        $qty = $data['qty'];
        $product_code = $data['product_code'];

        foreach ($lims_product_warranty_data as $product_warranty_data) {
            $product_warranty_data->delete();
        }

        foreach ($product_id as $key => $pro_id) {
            $lims_product_data = Product::find($pro_id);
            if ($lims_product_data->is_variant) {
                $lims_product_variant_data = ProductVariant::select('id', 'variant_id', 'qty')->FindExactProductWithCode($lims_product_data->id, $product_code[$key])->first();
                $product_warranty['variant_id'] = $lims_product_variant_data->variant_id;
            } else {
                $product_warranty['variant_id'] = null;
            }

            $product_warranty['product_id'] = $pro_id;
            $product_warranty['warranty_id'] = $lims_warranty_data->id;
            $product_warranty['unit_id'] = $unit_id[$key];
            $product_warranty['qty'] = $qty[$key];
            $product_warranty['fee_repair'] = $fee_repair[$key];
            $product_warranty['fee_exchange'] = $fee_exchange[$key];
            $product_warranty['transport_cost'] = $transport_cost[$key];
            $product_warranty['old_serial_number'] = $old_serial_number[$key];
            $product_warranty['serial_number'] = $serial_number[$key];
            $product_warranty['old_batch_number'] = $old_batch_number[$key];
            $product_warranty['batch_number'] = $batch_number[$key];
            $product_warranty['tr_number'] = $tr_number[$key];
            $product_warranty['RMA_number'] = $RMA_number[$key];
            $product_warranty['TKHQ_number'] = $TKHQ_number[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['warranty_company'] = $warranty_company[$key];
            $product_warranty['repair_company'] = $repair_company[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['invoice_number'] = $invoice_number[$key];
            $product_warranty['invoice_date'] = isset($invoice_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $invoice_date[$key]) : null;
            $product_warranty['temporary_date'] = isset($temporary_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $temporary_date[$key]) : null;
            $product_warranty['import_date'] = isset($import_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $import_date[$key]) : null;
            $product_warranty['created_at'] = Carbon::now();
            $product_warranty['updated_at'] = Carbon::now();
           
            ProductWarranty::create($product_warranty);
        }

        $lims_warranty_data->update($data);
        return Redirect::route('warranties.index')->with('success', 'Warranty updated successfully');
    }

    public function editExport($id)
    {
        $role = Role::firstOrCreate(['id' => Auth::user()->role_id]);
        if ($role->hasPermissionTo('warranties-edit')) {
            $lims_warranty_data = Warranty::with('customer')->where([
                ['id', $id],
                ['is_active', true]
            ])->firstOrFail();
            $lims_product_list_without_variant = $this->productWithoutVariant();
            $lims_product_list_with_variant = $this->productWithVariant();
            $lims_warranty_list = ProductWarranty::where('warranty_id', $id)->get();
            $lims_warehouse_list = Warehouse::where([['is_active', true], ['type', 'store']])->get();
            $date_format = GeneralSetting::select('date_format')->latest()->first();
            return view('warranty.edit_export',
                compact(
                    'lims_warranty_list',
                    'lims_warranty_data',
                    'lims_warehouse_list',
                    'lims_product_list_without_variant',
                    'lims_product_list_with_variant',
                    'date_format'
                )
            );
        } else {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
    }

    public function updateExport(Request $request, $id)
    {
        $data = $request->except('document');
        $date_format = GeneralSetting::select('date_format')->latest()->first();
        if($request->input('purchase_date') !== null){
            $data['purchase_date'] = Carbon::createFromFormat($date_format->date_format, $request->input('purchase_date'));
        } else {
            $data['purchase_date'] = null;
        }

        $customer_id = $data['customer_id'];
        $customer_name = $request->input('customer_name');
        $customer_address = $request->input('customer_address');
        // Create customer if not exist
        if ($customer_id === null && $customer_name && $customer_address) {
            $customer_id = Customer::create([
                "customer_group_id" => 1,
                "user_id" => auth()->id(),
                "name" => $request->input('customer_name'),
                "email" => $request->input('customer_email'),
                "city" => "",
                "phone_number" => $request->input('customer_phone_number'),
                "address" => $request->input('customer_address'),
                "is_active" => true
            ])->id;
            $data['customer_id'] = $customer_id;
        } else if($customer_id !== null){
            $data['customer_id'] = $customer_id;
        } 

        $lims_warranty_data = Warranty::find($id);
        $lims_product_warranty_data = ProductWarranty::where('warranty_id', $id)->get();

        $fee_repair = $data['fee_repair'];
        $fee_exchange = $data['fee_exchange'];
        $transport_cost = $data['transport_cost'];
        $old_serial_number = $data['old_serial_number'];
        $serial_number = $data['serial_number'];
        $old_batch_number = $data['old_batch_number'];
        $batch_number = $data['batch_number'];
        $tr_number = $data['tr_number'];
        $RMA_number = $data['RMA_number'];
        $TKHQ_number = $data['TKHQ_number'];
        $unit_name = $data['unit_name'];
        $warranty_company = $data['warranty_company'];
        $repair_company = $data['repair_company'];
        $unit_name = $data['unit_name'];
        $invoice_number = $data['invoice_number'];
        $invoice_date = $data['invoice_date'];
        $temporary_date = $data['temporary_date'];
        $import_date = $data['import_date'];
        $product_id = $data['product_id'];
        $unit_id = $data['unit_id'];
        $qty = $data['qty'];
        $product_code = $data['product_code'];

        foreach ($lims_product_warranty_data as $product_warranty_data) {
            $product_warranty_data->delete();
        }

        foreach ($product_id as $key => $pro_id) {
            $lims_product_data = Product::find($pro_id);
            if ($lims_product_data->is_variant) {
                $lims_product_variant_data = ProductVariant::select('id', 'variant_id', 'qty')->FindExactProductWithCode($lims_product_data->id, $product_code[$key])->first();
                $product_warranty['variant_id'] = $lims_product_variant_data->variant_id;
            } else {
                $product_warranty['variant_id'] = null;
            }

            $product_warranty['product_id'] = $pro_id;
            $product_warranty['warranty_id'] = $lims_warranty_data->id;
            $product_warranty['unit_id'] = $unit_id[$key];
            $product_warranty['qty'] = $qty[$key];
            $product_warranty['fee_repair'] = $fee_repair[$key];
            $product_warranty['fee_exchange'] = $fee_exchange[$key];
            $product_warranty['transport_cost'] = $transport_cost[$key];
            $product_warranty['old_serial_number'] = $old_serial_number[$key];
            $product_warranty['serial_number'] = $serial_number[$key];
            $product_warranty['old_batch_number'] = $old_batch_number[$key];
            $product_warranty['batch_number'] = $batch_number[$key];
            $product_warranty['tr_number'] = $tr_number[$key];
            $product_warranty['RMA_number'] = $RMA_number[$key];
            $product_warranty['TKHQ_number'] = $TKHQ_number[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['warranty_company'] = $warranty_company[$key];
            $product_warranty['repair_company'] = $repair_company[$key];
            $product_warranty['unit_name'] = $unit_name[$key];
            $product_warranty['invoice_number'] = $invoice_number[$key];
            $product_warranty['invoice_date'] = isset($invoice_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $invoice_date[$key]) : null;
            $product_warranty['temporary_date'] = isset($temporary_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $temporary_date[$key]) : null;
            $product_warranty['import_date'] = isset($import_date[$key]) ? Carbon::createFromFormat($date_format->date_format, $import_date[$key]) : null;
            $product_warranty['created_at'] = Carbon::now();
            $product_warranty['updated_at'] = Carbon::now();
           
            ProductWarranty::create($product_warranty);
        }

        $lims_warranty_data->update($data);
        return Redirect::route('warranties.index_export')->with('success', 'Warranty updated successfully');
    }

    public function updateProductWarranties(array $values)
    {
        $table = ProductWarranty::getModel()->getTable();;
        $ids = [];
        $params = [];
        $columnsGroups = [];
        $queryStart = "UPDATE {$table} SET";
        $columnsNames = array_keys(array_values($values)[0]);
        foreach ($columnsNames as $columnName) {
            $cases = [];
            $columnGroup = " " . $columnName . " = CASE id ";
            foreach ($values as $id => $newData) {
                $cases[] = "WHEN {$id} then ?";
                $params[] = $newData[$columnName];
                $ids[$id] = "0";
            }
            $cases = implode(' ', $cases);
            $columnsGroups[] = $columnGroup . "{$cases} END";
        }
        $ids = implode(',', array_keys($ids));
        $columnsGroups = implode(',', $columnsGroups);
        $params[] = Carbon::now();
        $queryEnd = ", updated_at = ? WHERE id in ({$ids})";

        return DB::update($queryStart . $columnsGroups . $queryEnd, $params);
    }

    public function destroy($id)
    {
        $role = Role::firstOrCreate(['id' => Auth::user()->role_id]);
        if (!$role->hasPermissionTo('warranties-delete')) {
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
        }
        Warranty::findOrFail($id)->update(['is_active' => false]);
        return back()->with('success', 'Warranty deleted successfully');
    }

    public function destroyBySelection(Request $request)
    {
        $role = Role::firstOrCreate(['id' => Auth::user()->role_id]);
        if (!$role->hasPermissionTo('warranties-delete')) {
            Session::flash('not_permitted', 'Sorry! You are not allowed to access this module');
            return response()->json(['error' => 'Sorry! You are not allowed to access this module'], 500);
        }

        Warranty::whereIn('id', $request->input('ids'))->update(['is_active' => false]);
        Session::flash('success', 'Warranty deleted successfully');
        return response()->json(['success' => 'Warranty deleted successfully']);
    }

    
    public function productWarrantyData($id)
    {
        $lims_product_purchase_data = ProductWarranty::where('warranty_id', $id)->get();
        foreach ($lims_product_purchase_data as $key => $product_purchase_data) {
            $product = Product::find($product_purchase_data->product_id);
            $unit = Unit::find($product_purchase_data->unit_id);
            if ($product_purchase_data->variant_id) {
                $lims_product_variant_data = ProductVariant::FindExactProduct($product->id, $product_purchase_data->variant_id)->select('item_code')->first();
                $variant_name = Variant::find($product_purchase_data->variant_id)->name;
                $product->code = $lims_product_variant_data->item_code;
                $product->name = $variant_name;
            }
            if($product){
                $product_purchase[0][$key] = $product->name;
                $product_purchase[10][$key] = $product->code;
            }
            $product_purchase[1][$key] = $product_purchase_data->qty;
            $product_purchase[2][$key] = $unit->unit_name;
            $product_purchase[3][$key] = $product_purchase_data->fee_repair;
            $product_purchase[4][$key] = $product_purchase_data->fee_exchange;
            $product_purchase[5][$key] = $product_purchase_data->transport_cost;
            $product_purchase[6][$key] = $product_purchase_data->old_serial_number;
            $product_purchase[7][$key] = $product_purchase_data->serial_number;
            $product_purchase[8][$key] = $product_purchase_data->old_batch_number;
            $product_purchase[9][$key] = $product_purchase_data->batch_number;
            $product_purchase[11][$key] = $product_purchase_data->lot_number;
            $product_purchase[12][$key] = $product_purchase_data->tr_number;
            $product_purchase[13][$key] = $product_purchase_data->invoice_number;
            $product_purchase[14][$key] = $product_purchase_data->RMA_number;
            $product_purchase[15][$key] = $product_purchase_data->TKHQ_number;
            $product_purchase[16][$key] = $product_purchase_data->warranty_company;
            $product_purchase[17][$key] = $product_purchase_data->repair_company;
        }
        return $product_purchase;
    }

    public function productWarrantyExportData($id)
    {
        $lims_product_purchase_data = ProductWarranty::where('warranty_id', $id)->get();
        foreach ($lims_product_purchase_data as $key => $product_purchase_data) {
            $product = Product::find($product_purchase_data->product_id);
            $unit = Unit::find($product_purchase_data->unit_id);
            if ($product_purchase_data->variant_id) {
                $lims_product_variant_data = ProductVariant::FindExactProduct($product->id, $product_purchase_data->variant_id)->select('item_code')->first();
                $variant_name = Variant::find($product_purchase_data->variant_id)->name;
                $product->code = $lims_product_variant_data->item_code;
                $product->name = $variant_name;
            }
            if($product){
                $product_purchase[0][$key] = $product->name;
                $product_purchase[10][$key] = $product->code;
            }
            $product_purchase[1][$key] = $product_purchase_data->qty;
            $product_purchase[2][$key] = $unit->unit_name;
            $product_purchase[3][$key] = $product_purchase_data->fee_repair;
            $product_purchase[4][$key] = $product_purchase_data->fee_exchange;
            $product_purchase[5][$key] = $product_purchase_data->transport_cost;
            $product_purchase[6][$key] = $product_purchase_data->old_serial_number;
            $product_purchase[7][$key] = $product_purchase_data->serial_number;
            $product_purchase[8][$key] = $product_purchase_data->old_batch_number;
            $product_purchase[9][$key] = $product_purchase_data->batch_number;
            $product_purchase[11][$key] = $product_purchase_data->lot_number;
            $product_purchase[12][$key] = $product_purchase_data->tr_number;
            $product_purchase[13][$key] = $product_purchase_data->invoice_number;
            $product_purchase[14][$key] = $product_purchase_data->RMA_number;
            $product_purchase[15][$key] = $product_purchase_data->TKHQ_number;
            $product_purchase[16][$key] = $product_purchase_data->warranty_company;
            $product_purchase[17][$key] = $product_purchase_data->repair_company;
        }
        return $product_purchase;
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit