public function create(Request $request)
 {
     // var_dump($request->all());die();
     \DB::beginTransaction();
     $saldoTemp = 0;
     $codigoHeadIS = 0;
     $purchase = $this->purchaseRepo->getModel();
     $payment = $this->paymentRepo->getModel();
     $pendientAccount = $this->pendientAccountRepo->getModel();
     $var = $request->detailOrderPurchases;
     $almacen_id = $request->input("warehouses_id");
     if (!empty($request->input("compraDirecta"))) {
         foreach ($var as $object) {
             $stockmodel = new StockRepo();
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             if (!empty($stockac)) {
                 $object["stockActual"] = floatval($stockac->stockActual) + floatval($object["cantidad"]);
                 //var_dump($object["stockActual"]);die();
                 $manager = new StockManager($stockac, $object);
                 $manager->save();
                 $stock = null;
             } else {
                 $object["stockActual"] = $object["cantidad"];
                 //var_dump($object["stockActual"]);die();
                 $manager = new StockManager($stockRepo->getModel, $object);
             }
             $stockac = null;
         }
     }
     //==================================Cancelar Factura
     if ($request->input('estado') == 2) {
         //var_dump("hola");die();
         foreach ($var as $object) {
             $stockmodel = new StockRepo();
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             //var_dump($stockac);die();
             if (!empty($stockac)) {
                 $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($object["cantidad"]);
                 $manager = new StockManager($stockac, $object);
                 $manager->save();
                 $stock = null;
             }
             //}
             $stockac = null;
         }
         $orderPurchase = $this->orderPurchaseRepo->find($request->id);
         $ordercompra = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista', 'montoBruto', 'montoTotal', 'descuento'));
         $ordercompra->save();
         if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
             $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
             $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
         } else {
             $orderPurchase->fechaPedido = null;
             $orderPurchase->fechaPrevista = null;
         }
         $orderPurchase->save();
         $payment1 = $this->paymentRepo->paymentById($request->input('id'));
         $pendientAccount = $this->pendientAccountRepo->getModel();
         //$pendientAcc=$this->pendientAccountRepo->verSaldos($payment1->id);
         if (!empty($payment1)) {
             $detPayment = $this->detPaymentRepo->verPagosAdelantados($payment1->id);
             if (!empty($detPayment)) {
                 foreach ($detPayment as $detPayment) {
                     $request->merge(["estado" => 0]);
                     $SaldosTemporales = $this->pendientAccountRepo->find2($detPayment['Saldo_F']);
                     if ($SaldosTemporales != null) {
                         $request->merge(['Saldo' => $SaldosTemporales->Saldo + $detPayment['montoPagado']]);
                         $request->merge(['orderPurchase_id' => $SaldosTemporales->orderPurchase_id]);
                         $request->merge(['supplier_id' => $SaldosTemporales->supplier_id]);
                         $insercount = new PendientAccountManager($SaldosTemporales, $request->all());
                         $insercount->save();
                     } else {
                         $request->merge(['orderPurchase_id' => $request->input('id')]);
                         $request->merge(['Saldo' => $payment1->Acuenta]);
                         $insercount = new PendientAccountManager($pendientAccount, $request->all());
                         $insercount->save();
                     }
                 }
                 ///================solucion Errores==================================
             } else {
                 $request->merge(['orderPurchase_id' => $request->input('id')]);
                 $request->merge(['Saldo' => $payment1->Acuenta]);
                 $insercount = new PendientAccountManager($pendientAccount, $request->all());
                 $insercount->save();
                 $provicional = $request->idpayment;
             }
             //==========================fin
         }
     } else {
         //===================================UpdateOrderPurchase===========================================
         if ($request->input('estado') == 1) {
             $request->merge(["Estado" => 1]);
             // var_dump($request->input("Estado"));die();
             $orderPurchase = $this->orderPurchaseRepo->find($request->id);
             //var_dump($orderPurchase->Estado);die();
             $ordercompra = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista', 'montoBruto', 'montoTotal', 'descuento'));
             $ordercompra->save();
             if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
                 $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
                 $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
             } else {
                 $orderPurchase->fechaPedido = null;
                 $orderPurchase->fechaPrevista = null;
             }
             $orderPurchase->save();
             $verSiExiste = $this->detailOrderPurchaseRepo->Comprobar($request->id);
             //***************************************************************
             if (!empty($verSiExiste[0])) {
                 //var_dump("no deve entrar");die();
                 $orderPurchase->detPres()->detach();
                 foreach ($var as $object1) {
                     //$hola=$var[$n];
                     //$object[]
                     $object1["Cantidad_Ll"] = $object1["cantidad1"];
                     $object1["pendiente"] = floatval($object1["cantidad"]) - floatval($object1["cantidad1"]);
                     /*if(!empty($object1["cantidad1"])){
                           //var_dump("holay".$object1["cantidad1"]);die();
                           //$object1["cantidad"]=$object1["Cantidad_Ll"];
                           //$object1["pendiente"]=$object1["pendiente"];
                           $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                           $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                       }else{
                           //var_dump("dos".$object1["cantidad1"]);die();
                         
                           if($object1["Cantidad_Ll"]=='0' && $object1["montoBruto"]=='0'){
                             $object1["Cantidad_Ll"]=0;
                             $object1["pendiente"]=$object1["cantidad"];
                             $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                             $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                           }else{
                               if($object1["Cantidad_Ll"]>0){
                                    $object1["Cantidad_Ll"]=$object1["cantidad"];
                                    $object1["pendiente"]=0;
                                    $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                                    $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                               }else{  
                                    $object1["Cantidad_Ll"]=$object1["cantidad"];
                                    $object1["pendiente"]=0;
                                    $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                                    $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                           }
                         }
                       
                       }*/
                     ////if($hola->cantidad1!=null){
                     ////    $object1["Cantidad_Ll"]=$hola->Cantidad_Ll;
                     ////    $object1["pendiente"]=$hola->pendiente;
                     ////
                     ////}else{
                     ////    $object1["Cantidad_Ll"]=$object1["cantidad"];
                     ////    $object1["pendiente"]=0;
                     ////}
                     //var_dump($hola['Cantidad_Ll']);die();
                     if (floatval($object1["preCompra"]) > 0) {
                         $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
                         $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object1);
                         $insertar->save();
                         $detailOrderPurchaseRepox = null;
                         //$n++;
                     }
                 }
                 //   var_dump($var);die();
             }
         }
         //==============================================================================
         $codOrder = $request->input("orderPurchase_id");
         $fechaActual = $request->input("fecha");
         //var_dump($fechaActual);die();
         //=============================Creando compra =============================
         //var_dump($var); die();
         $manager = new PurchaseManager($purchase, $request->except('fechaEntrega'));
         $manager->save();
         if ($this->purchaseRepo->validateDate(substr($request->input('fechaEntrega'), 0, 10))) {
             $purchase->fechaEntrega = substr($request->input('fechaEntrega'), 0, 10);
         } else {
             $purchase->fechaEntrega = null;
         }
         $purchase->save();
         $temporal = $purchase->id;
         // return $temporal;
         $request->merge(["purchase_id" => $temporal]);
         $detailPurchaseRepox;
         $consulPayment = null;
         //$almacen_id=$request->input("warehouses_id");
         //========================================================================
         $total = 0;
         foreach ($var as $object) {
             //========================insertDEtalles=========================
             $object['orderPurchase_id'] = $codOrder;
             $object['purchases_id'] = $temporal;
             $object['purchase_id'] = $temporal;
             $object['Fecha'] = $fechaActual;
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockmodel = new StockRepo();
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             if ($request->input('estado') == 1) {
                 // var_dump($object1["cantidad1"]);
                 $cantidadReal = $object["cantidad"];
                 $object["cantidad"] = $object["cantidad1"];
                 if ($request->input("tCambio") == "sol") {
                     //var_dump("hola este es soles");die();
                     $object["montoBruto"] = floatval($object["cantidad1"]) * floatval($object["preProducto"]);
                     $object["montoBrutoDolar"] = floatval($object["montoBruto"]) / floatval($request->input("tasaDolar"));
                     $object["montoTotal"] = floatval($object["cantidad1"]) * floatval($object["preCompra"]);
                     $object["montoTotalDolar"] = floatval($object["montoTotal"]) / floatval($request->input("tasaDolar"));
                     $total = $total + $object["montoTotal"];
                 } else {
                     $object["montoBrutoDolar"] = floatval($object["cantidad1"]) * floatval($object["preProductoDolar"]);
                     $object["montoBruto"] = floatval($object["montoBrutoDolar"]) * floatval($request->input("tasaDolar"));
                     $object["montoTotalDolar"] = floatval($object["cantidad1"]) * floatval($object["preCompraDolar"]);
                     $object["montoTotal"] = floatval($object["montoTotalDolar"]) * floatval($request->input("tasaDolar"));
                     $total = $total + $object["montoTotalDolar"];
                 }
                 //  var_dump($object["cantidad"]);
                 /*if(!empty($object["cantidad1"])){
                           $object["cantidad"]=$object["Cantidad_Ll"];
                        }else{
                          if($object["preCompra"]==0){
                                  $object["cantidad"]=$object["cantidad"];
                            }else{
                                  if($object["Cantidad_Ll"]==0 && $object["montoBruto"]==0)
                                  {
                                     $object["cantidad"]=$object["Cantidad_Ll"];
                                  }else{
                                   //if(floatval($object["Cantidad_Ll"])>0){
                                   //   $object["cantidad"]=$object["Cantidad_Ll"]; 
                                   //}else{
                                     $object["cantidad"]=$object["cantidad"];
                                   //}
                              }
                        }
                   }**/
                 //***************************************************
                 // $stockmodel = new StockRepo;
                 //$object['warehouse_id']=$almacen_id;
                 //$object["variant_id"]=$object["Codigovar"];
                 //$stockac=$stockmodel->encontrar($object["variant_id"],$almacen_id);
                 $cantidaCalculada = floatval($object["cantidad1"]) - floatval($object["Cantidad_Ll"]);
                 if ($cantidaCalculada < 0) {
                     $cantidaCalculada = floatval($cantidaCalculada * -1);
                 }
                 /*
                                   if(!empty($object["cantidad1"])){
                                       $cantidaCalculada=floatval($object["cantidad1"])-floatval($object["Cantidad_Ll"]);
                                   }else{ 
                                     if($object["preCompra"]==0){
                                           $cantidaCalculada=floatval($object["cantidad"]);
                                     }else{
                                          if($object["Cantidad_Ll"]==0 && $object["montoBruto"]==0){
                                                $cantidaCalculada=0;
                                           }else{
                                          $cantidaCalculada=floatval($object["cantidad"])-floatval($object["Cantidad_Ll"]);
                                           }
                                     }
                                   }*/
                 //*****************ssss*************************
             } else {
                 $stockmodel = new StockRepo();
                 $object['warehouse_id'] = $almacen_id;
                 $object["variant_id"] = $object["Codigovar"];
                 $cantidaCalculada = $object["cantidad"];
             }
             //$object["cantidad"]=$cantidaCalculada;
             if (intval($object["cantidad"] > 0)) {
                 //var_dump($object);die();
                 $detailPurchaseRepox = new DetailPurchaseRepo();
                 $insertar = new DetailPurchaseManager($detailPurchaseRepox->getModel(), $object);
                 $insertar->save();
                 $detailPurchaseRepox = null;
             }
             if ($request->input('estado') == 1) {
                 $purchase1 = $this->purchaseRepo->find($temporal);
                 if ($request->input("tCambio") == "sol") {
                     $request->merge(['montoBruto' => floatval($total)]);
                     $request->merge(['montoBrutoDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                 } else {
                     $request->merge(['montoBrutoDolar' => floatval($total)]);
                     $request->merge(['montoBruto' => floatval($total) * floatval($request->input("tasaDolar"))]);
                 }
                 if (!empty($purchase1->descuento)) {
                     if ($request->input("tCambio") == "sol") {
                         $request->merge(['montoTotal' => floatval($total) - floatval($total) * floatval($purchase1->descuento) / 100]);
                         $request->merge(['montoTotalDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                     } else {
                         $request->merge(['montoTotalDolar' => floatval($total) - floatval($total) * floatval($purchase1->descuento) / 100]);
                         $request->merge(['montoTotal' => floatval($total) * floatval($request->input("tasaDolar"))]);
                     }
                 } else {
                     if ($request->input("tCambio") == "sol") {
                         $request->merge(['montoTotal' => floatval($total)]);
                         $request->merge(['montoTotalDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                     } else {
                         $request->merge(['montoTotalDolar' => floatval($total)]);
                         $request->merge(['montoTotal' => floatval($total) * floatval($request->input("tasaDolar"))]);
                     }
                 }
                 $manager = new PurchaseManager($purchase1, $request->except('fechaEntrega'));
                 $manager->save();
             }
             //======================Si Existe Stock Pendiente Por Agregar===============================
             $inputStock = $this->inputStockRepo->getModel();
             $object["warehouses_id"] = $request->input("warehouses_id");
             $object["cantidad_llegado"] = $cantidaCalculada;
             $object['descripcion'] = 'Entrada por compra';
             $object['tipo'] = 'Compra';
             if (!empty($cantidadReal)) {
                 if (floatval($cantidadReal) > 0) {
                     if (!empty($stockac)) {
                         $object["stockActual"] = $stockac->stockActual + $cantidaCalculada;
                         if ($object["Cantidad_Ll"] > 0) {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($cantidaCalculada);
                         } else {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($cantidadReal);
                         }
                         //======================Actualizando stock si es que variante existe===============================
                         $manager = new StockManager($stockac, $object);
                         $manager->save();
                         $stock = null;
                     } else {
                         if (!empty($stockac->porLlegar)) {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($object["cantidad"]);
                         } else {
                             $object["porLlegar"] = 0;
                         }
                         //======================Registrando estock si es que variante no existe===============================
                         $manager = new StockManager($stockmodel->getModel(), $object);
                         $manager->save();
                         $stockmodel = null;
                     }
                     $stockac = null;
                 }
             }
             if ($cantidaCalculada > 0) {
                 ////======================Registrando en notas de cabecera===============================
                 if ($codigoHeadIS === 0 && $cantidaCalculada > 0) {
                     $headInputStock = $this->headInputStockRepo->getModel();
                     //var_dump($object);die();
                     $object["user_id"] = auth()->user()->id;
                     $inserHeadInputStock = new HeadInputStockManager($headInputStock, $object);
                     $inserHeadInputStock->save();
                     $codigoHeadIS = $headInputStock->id;
                 }
                 ////======================Registrando en notas de detalles===============================cantidad_llegado
                 //if(!empty($object["equivalencia"])){
                 //  if($object["equivalencia"]>0){
                 //    $object["cantidad_llegado"]=$object["cantidad_llegado"]*$object["equivalencia"];
                 //  }
                 //}
                 $object['headInputStock_id'] = $codigoHeadIS;
                 $inserInputStock = new inputStockManager($inputStock, $object);
                 $inserInputStock->save();
             }
         }
         //======================Creando reporte por cada linea de detalle de compra===============================
         //====================Creando y actualizando pagos si que existe adelantos====================================
         if ($request->input('compraDirecta') == 1) {
             $request->merge(["Acuenta" => 0]);
             $inserPay = new PaymentManager($payment, $request->all());
             $inserPay->save();
         } else {
             // var_dump($request->orderPurchase_id);die();
             $consulPayment = $this->paymentRepo->paymentById($request->orderPurchase_id);
             if (!empty($consulPayment)) {
                 // var_dump("entrando XD");die();
                 $request->merge(["Acuenta" => $consulPayment->Acuenta]);
                 $request->merge(["Saldo" => floatval($request->input("montoTotal")) - floatval($request->input("Acuenta"))]);
                 //$request->merge(["Acuenta"=>0]);
                 $inserPay = new PaymentManager($consulPayment, $request->all());
                 $inserPay->save();
                 //------------------------------------
                 if (floatval($request->Saldo) < 0) {
                     $request->merge(['Saldo' => floatval($request->Saldo * -1)]);
                     //$request->merge(["estado"=>0]);
                     $insercount = new PendientAccountManager($pendientAccount, $request->except("estado"));
                     $insercount->save();
                 }
             } else {
                 $request->merge(["Acuenta" => 0]);
                 $request->merge(["Saldo" => floatval($request->input("montoTotal")) - floatval($request->input("Acuenta"))]);
                 $inserPay = new PaymentManager($payment, $request->all());
                 $inserPay->save();
                 //$saldoTemp=$inserPay->Saldo;
             }
         }
         //var_dump("recolectando verdadero salfdo".$consulPayment->Saldo);die();
         // if(!empty($consulPayment)){
         // }
         if (!empty($consulPayment)) {
             $detPayment = $this->detPaymentRepo->verPagosAdelantados($consulPayment->id);
             if ($detPayment != null) {
                 foreach ($detPayment as $detPayment) {
                     if ($detPayment->Saldo_F != null) {
                         $saldos = $this->pendientAccountRepo->find2($detPayment['Saldo_F']);
                         if ($saldos != null) {
                             if ($saldos->Saldo == 0) {
                                 $request->merge(['Saldo' => 0]);
                                 $request->merge(['estado' => 1]);
                                 $request->merge(['orderPurchase_id' => $saldos->orderPurchase_id]);
                                 $request->merge(['supplier_id' => $saldos->supplier_id]);
                                 $insercount = new PendientAccountManager($saldos, $request->all());
                                 $insercount->save();
                             }
                         }
                     }
                 }
             }
         }
         ///==========================Registrando saldo Afavor ========================================
     }
     \DB::commit();
     return response()->json(['estado' => true, 'nombres' => $purchase->nombres]);
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit(Request $request)
 {
     \DB::beginTransaction();
     $varDetOrders = $request->detOrder;
     $varPayment = $request->payment;
     $movimiento = $request->movimiento;
     if ($movimiento['montoMovimientoEfectivo'] > 0) {
         //---create movimiento---
         //var_dump($request->movimiento);die();
         $detCashrepo;
         $movimiento['observacion'] = "temporal";
         $movimiento['fecha'] = date('Y-m-d');
         $movimiento['hora'] = date('H:i:s');
         $detCashrepo = new DetCashRepo();
         $movimientoSave = $detCashrepo->getModel();
         $insertarMovimiento = new DetCashManager($movimientoSave, $movimiento);
         $insertarMovimiento->save();
         //---Autualizar Caja---
         $cajaAct = $request->caja;
         $cashrepo;
         $cashrepo = new CashRepo();
         $cajaSave = $cashrepo->getModel();
         $cash1 = $cashrepo->find($cajaAct["id"]);
         $manager1 = new CashManager($cash1, $cajaAct);
         $manager1->save();
         //----------------
         $salePaymentRepo;
         $salePaymentRepo = new SalePaymentRepo();
         //$payment = $salePaymentRepo->find($varPayment['id']);
         $payment = $salePaymentRepo->find($varPayment['idPAY']);
         $manager = new SalePaymentManager($payment, $varPayment);
         $manager->save();
     }
     $HeadStockRepo;
     $codigoHeadIS = 0;
     //$detOrderSaleRepo;
     foreach ($varDetOrders as $object) {
         //$detOrderSaleRepo = new DetSaleRepo;
         //$detorderSale = $detOrderSaleRepo->find($object['id']);
         //$manager = new DetSaleManager($detorderSale,$object);
         //$manager->save();
         if (!empty($object['idStock'])) {
             $stokRepo;
             $stokRepo = new StockRepo();
             $cajaSave = $stokRepo->getModel();
             $stockOri = $stokRepo->find($object['id']);
             $stock = $stokRepo->find($object['idStock']);
             //+++if ($object['estad']==true) {
             $stock->stockActual = $stock->stockActual + $object['cantidad'];
             //+++}else{
             //+++$stock->stockPedidos= $stock->stockPedidos+$object['canPendiente'];
             //+++}
             $stock->save();
             //--------------reporte stock------------
             $object["variant_id"] = $object['vari'];
             if ($codigoHeadIS === 0) {
                 $object["warehouses_id"] = $object['idAlmacen'];
                 //$object["cantidad_llegado"]=$cantidaCalculada;
                 //$object['descripcion']='Entrada por compra';
                 //$object['tipo']='Entrada Venta';
                 $object['tipo'] = 'Entrada-Anulado';
                 $object["user_id"] = auth()->user()->id;
                 //$object["Fecha"]=$request->input("fechaPedido");
                 $object["Fecha"] = date('Y-m-d H:i:s');
                 $HeadStockRepo = new HeadInputStockRepo();
                 $HeadStock = $HeadStockRepo->getModel();
                 $HeadStockinsert = new HeadInputStockManager($HeadStock, $object);
                 $HeadStockinsert->save();
                 $codigoHeadIS = $HeadStock->id;
             }
             $object['headInputStock_id'] = $codigoHeadIS;
             $object["producto"] = $object['nameProducto'] . "(" . $object['NombreAtributos'] . ")";
             $object["cantidad_llegado"] = $object['cantidad'];
             $object['descripcion'] = 'Entrada-Venta-Anulada';
             $inputRepo;
             $inputRepo = new InputStockRepo();
             $inputstock = $inputRepo->getModel();
             $inputInsert = new InputStockManager($inputstock, $object);
             $inputInsert->save();
         }
         //---------------------------------------
     }
     $orderSale = $this->saleRepo->find($request->id);
     if ($request->input('estado') == '3') {
         $request->merge(array('fechaAnulado' => date('Y-m-d H:i:s')));
     }
     $manager = new SaleManager($orderSale, $request->all());
     $manager->save();
     $serviceID = $orderSale->service_id;
     if (!empty($serviceID)) {
         $servicio = $this->serviceRepo->find($serviceID);
         $request->merge(["estado" => 4]);
         $request->merge(["numeroServicio" => $servicio->numeroServicio]);
         $request->merge(["fechaServicio" => $servicio->fechaServicio]);
         $request->merge(["tipo" => $servicio->tipo]);
         $request->merge(["cliente" => $servicio->cliente]);
         $request->merge(["ruc" => $servicio->ruc]);
         $request->merge(["direcion" => $servicio->direcion]);
         $request->merge(["telefono" => $servicio->telefono]);
         $request->merge(["empresa" => $servicio->empresa]);
         $request->merge(["descripcion" => $servicio->descripcion]);
         $request->merge(["modelo" => $servicio->modelo]);
         $request->merge(["serie" => $servicio->serie]);
         $request->merge(["accesorios" => $servicio->accesorios]);
         $request->merge(["diagnostico" => $servicio->diagnostico]);
         $request->merge(["accionCorrectiva" => $servicio->accionCorrectiva]);
         $request->merge(["ordenTrabajo" => $servicio->ordenTrabajo]);
         $request->merge(["customer_id" => $servicio->customer_id]);
         $request->merge(["employee_id" => $servicio->employee_id]);
         $request->merge(["user_id" => $servicio->user_id]);
         $manager = new ServiceManager($servicio, $request->all());
         $manager->save();
     }
     \DB::commit();
     return response()->json(['estado' => true, 'nombre' => $orderSale->nombre]);
 }
 public function create(Request $request)
 {
     \DB::beginTransaction();
     if ($request->warehouDestino_id == "") {
         $request->merge(["warehouDestino_id" => null]);
     }
     $var = $request->detailOrderPurchases;
     $request->merge(["Fecha" => $request->fecha]);
     // var_dump($request->input("generareport"));die();
     $codigoHeadIS;
     $almacen_id = $request->input("warehouses_id");
     $almacen_Destino = $request->input("warehouDestino_id");
     //if($almacen_Destino==null){
     //       $almacen_Destino=null;
     //}
     $queHacer = $request->input("eliminar");
     $tipo = $request->input("tipo");
     $tipo2 = "Salida";
     $request->merge(['user_id' => auth()->user()->id]);
     //var_dump();die();
     if ($queHacer === 0) {
         $request->merge(["orderPurchase_id" => $request->input('id')]);
         $headInputStock = $this->headInputStockRepo->getModel();
         if (!empty($request->input('warehouDestino_id'))) {
             $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->all());
         } else {
             $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->except('warehouDestino_id'));
         }
         $inserHeadInputStock->save();
         $codigoHeadIS = $headInputStock->id;
         $orderPurchase = $this->orderPurchaseRepo->find($request->input('id'));
         $orderPurchase->detPres()->detach();
         foreach ($var as $object) {
             //  if($queHacer===0){
             //var_dump("hola");die();
             $detPres = $this->detPresRepo->listarVariantes($object['detPres_id']);
             $object["variant_id"] = $detPres->variant_id;
             $object["warehouses_id"] = $request->input("warehouses_id");
             $object["descripcion"] = "Ingreso por pedido";
             $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
             $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object);
             $insertar->save();
             $detailOrderPurchaseRepox = null;
             // }
             $inputStock = $this->inputStockRepo->getModel();
             // var_dump($object);die();
             if (!empty($object["cantidad_llegado"])) {
                 //if($object["cantidad_llegado"]>0){
                 //  if(!empty($object["equivalencia"])){
                 //      if($object["equivalencia"]>0){
                 //        $object["cantidad_llegado"]=$object["cantidad_llegado"]*$object["equivalencia"];
                 //      }
                 //   }
                 $object['headInputStock_id'] = $codigoHeadIS;
                 $inserInputStock = new inputStockManager($inputStock, $object);
                 $inserInputStock->save();
                 $stockmodel = new StockRepo();
                 $object['warehouse_id'] = $almacen_id;
                 $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
                 //var_dump($object["tipo"]);die();
                 if (!empty($stockac)) {
                     /* if($object["esbase"]==0){
                            if($object["tipo"]=="Salida"){
                                $object["stockActual"]=$stockac->stockActual-($object["cantidad_llegado"]*$object["equivalencia"]);
                                var_dump("entre");
                            }else{
                                $object["stockActual"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
                             }
                        }else{
                            if($object["tipo"]=="Salida"){
                              $object["stockActual"]=$stockac->stockActual-$object["cantidad_llegado"];
                              var_dump("entre");
                            }else{
                               $object["stockActual"]=$stockac->stockActual+$object["cantidad_llegado"]; 
                            }
                        }*/
                     //if($object["esbase"]==0){
                     //  $object["stockActual"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
                     // }else{
                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"];
                     $object["porLlegar"] = $stockac->porLlegar - $object["cantidad_llegado"];
                     //}
                     $manager = new StockManager($stockac, $object);
                     $manager->save();
                     $stock = null;
                 } else {
                     if ($tipo != $tipo2) {
                         if ($object["esbase"] == 0) {
                             $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                         } else {
                             $object["stockActual"] = $object["cantidad_llegado"];
                         }
                         $manager = new StockManager($stockmodel->getModel(), $object);
                         $manager->save();
                         $stockmodel = null;
                     }
                 }
                 $stockac = null;
             }
         }
         // }
     } else {
         //==========================================================0
         //$inputStock = $this->inputStockRepo->getModel();
         $headInputStock = $this->headInputStockRepo->getModel();
         //var_dump($var);die();
         //if(!empty($var["cantidad_llegado"])){
         //var_dump($request->all());die();
         $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->all());
         $inserHeadInputStock->save();
         $codigoHeadIS = $headInputStock->id;
         foreach ($var as $object) {
             $inputStock = $this->inputStockRepo->getModel();
             //$inputStock = $this->inputStockRepo->getModel();
             if (!empty($object["cantidad_llegado"])) {
                 if ($object["cantidad_llegado"] > 0) {
                     $object['warehouse_id'] = $almacen_id;
                     $object['headInputStock_id'] = $codigoHeadIS;
                     $inserInputStock = new InputStockManager($inputStock, $object);
                     $inserInputStock->save();
                     //var_dump($object);die();
                     $stockmodel = new StockRepo();
                     //$var['warehouse_id']=$almacen_id;
                     $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
                     if ($tipo == "Transferencia") {
                         $tockacDestino = $stockmodel->encontrar($object["variant_id"], $almacen_Destino);
                         if (!empty($tockacDestino)) {
                             if ($object["esbase"] == 0) {
                                 $object["stockActual"] = $tockacDestino->stockActual + $object["cantidad_llegado"] * $object["equivalencia"];
                             } else {
                                 $object["stockActual"] = $tockacDestino->stockActual + $object["cantidad_llegado"];
                             }
                             $object['warehouse_id'] = $almacen_Destino;
                             $manager = new StockManager($tockacDestino, $object);
                             $manager->save();
                             $stock = null;
                         } else {
                             if ($object["esbase"] == 0) {
                                 $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                             } else {
                                 $object["stockActual"] = $object["cantidad_llegado"];
                             }
                             $object['warehouse_id'] = $almacen_Destino;
                             $manager = new StockManager($stockmodel->getModel(), $object);
                             $manager->save();
                             $stockmodel = null;
                         }
                         $tockacDestino = null;
                         if (!empty($stockac)) {
                             $object['warehouse_id'] = $almacen_id;
                             $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"];
                             $manager = new StockManager($stockac, $object);
                             $manager->save();
                             $stock = null;
                         }
                     } else {
                         //Actualiza Stock---------------------------------------------
                         if (!empty($stockac)) {
                             if ($object["esbase"] == 0) {
                                 if ($tipo == $tipo2) {
                                     $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"] * $object["equivalencia"];
                                     //var_dump("entre");
                                 } else {
                                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"] * $object["equivalencia"];
                                 }
                             } else {
                                 if ($tipo == $tipo2) {
                                     $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"];
                                     //var_dump("entre");
                                 } else {
                                     // var_dump("hola ");die();
                                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"];
                                 }
                             }
                             $manager = new StockManager($stockac, $object);
                             $manager->save();
                             $stock = null;
                         } else {
                             if ($tipo != $tipo2) {
                                 if ($object["esbase"] == 0) {
                                     $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                                 } else {
                                     $object["stockActual"] = $object["cantidad_llegado"];
                                 }
                                 $manager = new StockManager($stockmodel->getModel(), $object);
                                 $manager->save();
                                 $stockmodel = null;
                             }
                         }
                     }
                     //fin actualiza Stock---------------------------------------------------
                     $stockac = null;
                 }
             }
         }
     }
     // var_dump($request->generareport);die();
     //$idOrder=intval($request->input("id"));
     //var_dump($idOrder);die();
     \DB::commit();
     ////======================================================00
     return response()->json(['estado' => true]);
 }