public function store(Request $request): JsonResponse
{
$request->validate([
'id_venta' => 'required|exists:ventas,id_venta',
'motivo_id' => 'required|exists:motivo_nota,id',
'descripcion_motivo' => 'nullable|string|max:255',
]);
return DB::transaction(function () use ($request) {
$venta = Venta::with(['empresa', 'cliente', 'tipoDocumento', 'productosVentas'])
->findOrFail($request->id_venta);
$empresa = $venta->empresa;
$motivo = MotivoNota::findOrFail($request->motivo_id);
// Determinar serie según documento afectado
$tipDocAfectado = $venta->tipoDocumento->cod_sunat;
$serieNC = $tipDocAfectado === '01' ? 'FC01' : 'BC01';
$ultimoNumero = NotaCredito::where('serie', $serieNC)
->where('id_empresa', $empresa->id_empresa)
->max('numero') ?? 0;
// Consultar documentos_empresas como número base
$numeroBase = DB::table('documentos_empresas')
->where('id_empresa', $empresa->id_empresa)
->where('serie', $serieNC)
->value('numero') ?? 0;
$ultimoNumero = max($ultimoNumero, $numeroBase);
// Sincronizar documentos_empresas
DB::table('documentos_empresas')
->where('id_empresa', $empresa->id_empresa)
->where('serie', $serieNC)
->update(['numero' => $ultimoNumero + 1]);
$nota = NotaCredito::create([
'id_venta' => $venta->id_venta,
'motivo_id' => $motivo->id,
'serie' => $serieNC,
'numero' => $ultimoNumero + 1,
'tipo_doc_afectado' => $tipDocAfectado,
'serie_num_afectado' => $venta->serie . '-' . $venta->numero,
'descripcion_motivo' => $request->descripcion_motivo ?? $motivo->descripcion,
'monto_subtotal' => $venta->subtotal,
'monto_igv' => $venta->igv,
'monto_total' => $venta->total,
'moneda' => $venta->tipo_moneda ?? 'PEN',
'fecha_emision' => now()->toDateString(),
'estado' => 'pendiente',
'id_empresa' => $empresa->id_empresa,
'id_usuario' => $request->user()->id,
]);
$resultado = $this->sunatService->generarNotaCreditoXml($nota);
return response()->json([
'success' => true,
'data' => $nota,
'xml' => $resultado,
], 201);
});
}