Files
flux/lib/features/tickets/utils/ticket_pdf_service.dart
T

712 lines
24 KiB
Dart

import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:get_it/get_it.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/company/models/company_model.dart';
class TicketPdfService {
final CompanyModel company = GetIt.I.get<SessionCubit>().state.company!;
/// Funzione principale: Genera il PDF A4 con le due metà
Future<pw.Document> generateTicketReceipt(TicketModel ticket) async {
final pdf = pw.Document();
// Carichiamo il font per essere sicuri che i caratteri siano ok
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
pw.Widget customerHalf = await _buildTicketHalf(
ticket,
company,
font,
boldFont,
isForCustomer: true,
);
pw.Widget storeHalf = await _buildTicketHalf(
ticket,
company,
font,
boldFont,
isForCustomer: false,
);
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
margin: const pw.EdgeInsets.all(20),
build: (pw.Context context) {
return pw.Column(
children: [
// 1. METÀ SUPERIORE: CLIENTE
customerHalf,
pw.SizedBox(height: 10),
// Linea tratteggiata per il taglio
pw.Container(
margin: const pw.EdgeInsets.symmetric(vertical: 10),
child: pw.Text(
'-' * 100,
style: const pw.TextStyle(color: PdfColors.grey400),
),
),
pw.SizedBox(height: 10),
// 2. METÀ INFERIORE: NEGOZIO
storeHalf,
],
);
},
),
);
return pdf;
}
/// Helper per costruire una singola metà (Cliente o Negozio)
Future<pw.Widget> _buildTicketHalf(
TicketModel ticket,
CompanyModel company,
pw.Font font,
pw.Font boldFont, {
required bool isForCustomer,
}) async {
return pw.Expanded(
//height: 380, // Circa metà A4 meno i margini
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
// HEADER: Logo e Dati Azienda (Solo per cliente o ID per negozio)
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
company.name,
style: pw.TextStyle(font: boldFont, fontSize: 16),
),
if (isForCustomer) ...[
pw.Text(
"${company.address}, ${company.city} - ${company.email} - ${company.phone}",
style: const pw.TextStyle(fontSize: 10),
),
pw.Text(
"P.IVA: ${company.vatId}",
style: const pw.TextStyle(fontSize: 10),
),
],
],
),
pw.Row(
children: [
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.end,
children: [
pw.Text(
isForCustomer
? "RICEVUTA CLIENTE"
: "COPIA INTERNA NEGOZIO",
style: pw.TextStyle(
font: boldFont,
fontSize: 12,
color: PdfColors.grey700,
),
),
pw.Text(
"Rif: ${ticket.referenceId}",
style: pw.TextStyle(font: boldFont, fontSize: 14),
),
pw.Text(
"Data: ${ticket.createdAt?.toString().substring(0, 10) ?? ''}",
style: const pw.TextStyle(fontSize: 10),
),
],
),
pw.SizedBox(width: 10),
// IL NOSTRO QR CODE MAGICO
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(),
data: ticket.id!, // Salviamo l'ID univoco nel QR!
width: 45,
height: 45,
),
],
),
],
),
pw.Divider(thickness: 1),
pw.SizedBox(height: 10),
// DATI CLIENTE
pw.Row(
children: [
pw.Expanded(
child: _infoBlock(
"CLIENTE",
ticket.customer?.name ?? 'Cliente Sconosciuto',
font,
boldFont,
),
),
if (ticket.customer?.phoneNumber != null)
pw.Expanded(
child: _infoBlock(
"TELEFONO",
ticket.customer?.phoneNumber ?? 'N/D',
font,
boldFont,
),
),
if (ticket.alternativePhoneNumber != null)
pw.Expanded(
child: _infoBlock(
"CONTATTO ALTERNATIVO",
ticket.alternativePhoneNumber ?? 'N/D',
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 15),
// DETTAGLI LAVORAZIONE
_infoBlock(
"DESCRIZIONE PROBLEMA / LAVORAZIONE RICHIESTA",
ticket.request,
font,
boldFont,
),
pw.SizedBox(height: 8),
pw.Row(
children: [
pw.Expanded(
child: _infoBlock(
"ACCESSORI CONSEGNATI",
ticket.includedAccessories ?? 'Nessuno',
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
"GARANZIA",
ticket.warrantyType?.displayValue ?? 'Standard',
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 15),
// NOTE (Pubbliche o Private a seconda della copia)
if (isForCustomer)
_infoBlock("NOTE", ticket.publicNotes ?? '-', font, boldFont)
else
_infoBlock(
"NOTE INTERNE (PRIVATE)",
ticket.internalNotes ?? '-',
font,
boldFont,
),
pw.Spacer(),
// FOOTER: Disclaimer e Firma
if (!isForCustomer) ...[
pw.Text(
"CONDIZIONI E LIBERATORIA:",
style: pw.TextStyle(font: boldFont, fontSize: 8),
),
pw.Text(
company.ticketDisclaimer ??
'Firma per accettazione delle condizioni di riparazione.',
style: const pw.TextStyle(fontSize: 7),
textAlign: pw.TextAlign.justify,
),
pw.SizedBox(height: 20),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Container(
width: 150,
decoration: pw.BoxDecoration(
border: const pw.Border(top: pw.BorderSide(width: 0.5)),
),
),
pw.Text(
"Firma del Cliente per accettazione",
style: const pw.TextStyle(fontSize: 8),
),
],
),
] else
pw.Align(
alignment: pw.Alignment.centerRight,
child: pw.Text(
"Grazie per averci scelto!",
style: pw.TextStyle(
font: font,
fontSize: 10,
fontStyle: pw.FontStyle.italic,
),
),
),
],
),
);
}
pw.Widget _infoBlock(
String label,
String value,
pw.Font font,
pw.Font boldFont,
) {
return pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
label,
style: pw.TextStyle(
font: boldFont,
fontSize: 8,
color: PdfColors.grey600,
),
),
pw.Text(value, style: pw.TextStyle(font: font, fontSize: 11)),
],
);
}
/// Genera una ricevuta digitale A4 (1 sola copia cliente, senza note interne né password)
/// con QR Code collegato alla pagina pubblica di tracciamento.
Future<pw.Document> generateCustomerReceiptPdf(TicketModel ticket) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
final ref = ticket.referenceId?.trim().isNotEmpty == true
? ticket.referenceId!
: (ticket.id?.substring(0, 8) ?? '');
final createdDate = ticket.createdAt != null
? '${ticket.createdAt!.day.toString().padLeft(2, '0')}/${ticket.createdAt!.month.toString().padLeft(2, '0')}/${ticket.createdAt!.year}'
: '';
final estimatedDate = ticket.estimatedDeliveryAt != null
? '${ticket.estimatedDeliveryAt!.day.toString().padLeft(2, '0')}/${ticket.estimatedDeliveryAt!.month.toString().padLeft(2, '0')}/${ticket.estimatedDeliveryAt!.year}'
: '';
final trackingUrl = ticket.publicTrackingUrl;
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
margin: const pw.EdgeInsets.all(28),
build: (pw.Context context) {
return pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
// HEADER AZIENDA + RIF TICKET
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
company.name,
style: pw.TextStyle(font: boldFont, fontSize: 18),
),
pw.SizedBox(height: 3),
pw.Text(
[
company.address,
company.city,
].where((e) => e.trim().isNotEmpty).join(', '),
style: pw.TextStyle(font: font, fontSize: 9.5),
),
pw.Text(
[
if ((company.phone ?? '').trim().isNotEmpty)
'Tel: ${company.phone}',
if ((company.email ?? '').trim().isNotEmpty)
company.email!,
].join(' • '),
style: pw.TextStyle(font: font, fontSize: 9.5),
),
if (company.vatId.trim().isNotEmpty)
pw.Text(
'P.IVA: ${company.vatId}',
style: pw.TextStyle(font: font, fontSize: 9),
),
],
),
),
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.end,
children: [
pw.Text(
'RICEVUTA DI ASSISTENZA',
style: pw.TextStyle(
font: boldFont,
fontSize: 11,
color: PdfColors.blueGrey700,
),
),
pw.SizedBox(height: 2),
pw.Text(
'Pratica #$ref',
style: pw.TextStyle(font: boldFont, fontSize: 15),
),
if (createdDate.isNotEmpty)
pw.Text(
'Data apertura: $createdDate',
style: pw.TextStyle(font: font, fontSize: 9.5),
),
],
),
],
),
pw.SizedBox(height: 12),
pw.Divider(thickness: 1, color: PdfColors.grey400),
pw.SizedBox(height: 14),
// DATI CLIENTE & DISPOSITIVO
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'CLIENTE',
ticket.customer?.name ?? 'Cliente',
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'RECAPITO',
ticket.effectiveContactDestination.isNotEmpty
? ticket.effectiveContactDestination
: (ticket.customer?.phoneNumber ?? '-'),
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'DISPOSITIVO',
ticket.targetModelName?.isNotEmpty == true
? ticket.targetModelName!
: ticket.ticketType.displayValue,
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'SERIALE / IMEI',
ticket.targetSn?.trim().isNotEmpty == true
? ticket.targetSn!.trim()
: '-',
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'TIPO INTERVENTO',
ticket.ticketType.displayValue,
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'GARANZIA',
ticket.warrantyType?.displayValue ?? 'Fuori garanzia',
font,
boldFont,
),
),
],
),
if (ticket.includedAccessories?.trim().isNotEmpty == true ||
ticket.hasCourtesyDevice ||
estimatedDate.isNotEmpty ||
ticket.customerPrice > 0) ...[
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
if (ticket.includedAccessories?.trim().isNotEmpty == true)
pw.Expanded(
child: _infoBlock(
'ACCESSORI LASCIATI',
ticket.includedAccessories!.trim(),
font,
boldFont,
),
),
if (ticket.hasCourtesyDevice)
pw.Expanded(
child: _infoBlock(
'MULETTO DI CORTESIA',
'Consegnato al cliente',
font,
boldFont,
),
),
if (estimatedDate.isNotEmpty)
pw.Expanded(
child: _infoBlock(
'CONSEGNA STIMATA',
estimatedDate,
font,
boldFont,
),
),
if (ticket.customerPrice > 0)
pw.Expanded(
child: _infoBlock(
'PREVENTIVO INIZIALE',
'EUR ${ticket.customerPrice.toStringAsFixed(2)}',
font,
boldFont,
),
),
],
),
],
pw.SizedBox(height: 16),
// PROBLEMA SEGNALATO
pw.Container(
width: double.infinity,
padding: const pw.EdgeInsets.all(12),
decoration: pw.BoxDecoration(
color: PdfColors.grey100,
borderRadius: pw.BorderRadius.circular(6),
),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'DIFETTO / RICHIESTA SEGNALATA',
style: pw.TextStyle(
font: boldFont,
fontSize: 8.5,
color: PdfColors.grey700,
),
),
pw.SizedBox(height: 4),
pw.Text(
ticket.request.trim().isNotEmpty
? ticket.request.trim()
: '-',
style: pw.TextStyle(font: font, fontSize: 11),
),
],
),
),
// NOTE PUBBLICHE (MAI internalNotes!)
if (ticket.publicNotes?.trim().isNotEmpty == true) ...[
pw.SizedBox(height: 12),
pw.Container(
width: double.infinity,
padding: const pw.EdgeInsets.all(12),
decoration: pw.BoxDecoration(
border: pw.Border.all(color: PdfColors.grey300),
borderRadius: pw.BorderRadius.circular(6),
),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'NOTE',
style: pw.TextStyle(
font: boldFont,
fontSize: 8.5,
color: PdfColors.grey700,
),
),
pw.SizedBox(height: 4),
pw.Text(
ticket.publicNotes!.trim(),
style: pw.TextStyle(font: font, fontSize: 10.5),
),
],
),
),
],
pw.Spacer(),
// BOX TRACCIAMENTO ONLINE CON QR CODE
if (trackingUrl.isNotEmpty)
pw.Container(
padding: const pw.EdgeInsets.all(14),
decoration: pw.BoxDecoration(
color: PdfColors.blue50,
border: pw.Border.all(color: PdfColors.blue200),
borderRadius: pw.BorderRadius.circular(8),
),
child: pw.Row(
children: [
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(
errorCorrectLevel: pw.BarcodeQRCorrectionLevel.low,
),
data: trackingUrl,
width: 68,
height: 68,
),
pw.SizedBox(width: 14),
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'SEGUI LO STATO DELLA TUA PRATICA ONLINE',
style: pw.TextStyle(
font: boldFont,
fontSize: 10.5,
color: PdfColors.blue900,
),
),
pw.SizedBox(height: 4),
pw.Text(
'Inquadra il QR Code con il telefono per verificare in tempo reale gli aggiornamenti, eventuali preventivi e quando il dispositivo sarà pronto per il ritiro.',
style: pw.TextStyle(font: font, fontSize: 9),
),
pw.SizedBox(height: 4),
pw.Text(
trackingUrl,
style: pw.TextStyle(
font: font,
fontSize: 8,
color: PdfColors.blue700,
),
),
],
),
),
],
),
),
pw.SizedBox(height: 14),
pw.Align(
alignment: pw.Alignment.centerRight,
child: pw.Text(
'Grazie per aver scelto ${company.name}!',
style: pw.TextStyle(
font: font,
fontSize: 9.5,
color: PdfColors.grey700,
),
),
),
],
);
},
),
);
return pdf;
}
Future<pw.Document> generateLabelPdf(TicketModel ticket) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
// Prendiamo le misure salvate (se custom) o usiamo default
final widthMm = company.labelWidth ?? 62.0;
final heightMm = company.labelHeight ?? 29.0;
// Creiamo il formato fisico esatto!
final format = company.isLabelVertical
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
: PdfPageFormat(
widthMm * PdfPageFormat.mm,
heightMm * PdfPageFormat.mm,
);
pdf.addPage(
pw.Page(
pageFormat: format,
margin: const pw.EdgeInsets.all(2), // Margini minimi per le etichette
build: (context) {
return pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
mainAxisAlignment: pw.MainAxisAlignment.center,
children: [
pw.Text(
ticket.referenceId ?? '',
style: pw.TextStyle(font: boldFont, fontSize: 10),
),
pw.Text(
ticket.customer?.name ?? 'Cliente sconosciuto',
style: pw.TextStyle(font: font, fontSize: 9),
),
pw.Text(
ticket.createdAt?.toString().substring(0, 10) ?? '',
style: const pw.TextStyle(fontSize: 7),
),
],
),
),
// QR Code compatto
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(),
data: ticket.id!,
width: 20,
height: 20,
),
],
);
},
),
);
return pdf;
}
}