package invoice import ( "context" "fmt" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) type Invoice struct { ID string `json:"id"` WorkOrderID string `json:"work_order_id"` Type string `json:"type"` Number int `json:"number"` PDFPath string `json:"pdf_path"` IssuedAt time.Time `json:"issued_at"` CreatedAt time.Time `json:"created_at"` } func ListInvoices(ctx context.Context, conn *pgxpool.Conn) ([]*Invoice, error) { rows, err := conn.Query(ctx, `SELECT id, work_order_id, type, number, COALESCE(pdf_path,''), issued_at, issued_at AS created_at FROM invoices ORDER BY issued_at DESC`) if err != nil { return nil, fmt.Errorf("invoice: list: %w", err) } defer rows.Close() var list []*Invoice for rows.Next() { var inv Invoice if err := rows.Scan(&inv.ID, &inv.WorkOrderID, &inv.Type, &inv.Number, &inv.PDFPath, &inv.IssuedAt, &inv.CreatedAt); err != nil { return nil, fmt.Errorf("invoice: scan: %w", err) } list = append(list, &inv) } return list, rows.Err() } func GetInvoice(ctx context.Context, conn *pgxpool.Conn, id string) (*Invoice, error) { row := conn.QueryRow(ctx, `SELECT id, work_order_id, type, number, COALESCE(pdf_path,''), issued_at, issued_at AS created_at FROM invoices WHERE id = $1`, id) var inv Invoice err := row.Scan(&inv.ID, &inv.WorkOrderID, &inv.Type, &inv.Number, &inv.PDFPath, &inv.IssuedAt, &inv.CreatedAt) if err == pgx.ErrNoRows { return nil, nil } if err != nil { return nil, fmt.Errorf("invoice: get: %w", err) } return &inv, nil } func CreateInvoice(ctx context.Context, conn *pgxpool.Conn, woID, docType string) (*Invoice, error) { row := conn.QueryRow(ctx, `INSERT INTO invoices (work_order_id, type, issued_at) VALUES ($1, $2, NOW()) RETURNING id, work_order_id, type, number, COALESCE(pdf_path,''), issued_at, issued_at AS created_at`, woID, docType) var inv Invoice if err := row.Scan(&inv.ID, &inv.WorkOrderID, &inv.Type, &inv.Number, &inv.PDFPath, &inv.IssuedAt, &inv.CreatedAt); err != nil { return nil, fmt.Errorf("invoice: create: %w", err) } return &inv, nil } func SetPDFPath(ctx context.Context, conn *pgxpool.Conn, id, path string) error { _, err := conn.Exec(ctx, `UPDATE invoices SET pdf_path = $2 WHERE id = $1`, id, path) if err != nil { return fmt.Errorf("invoice: set pdf path: %w", err) } return nil }