cmc-sales/go/internal/cmc/handlers/pdf_api_test.go

84 lines
2.2 KiB
Go

//go:build never
// +build never
package handlers
package handlers
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/jung-kurt/gofpdf"
)
func createPDF(path, title string) error {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Helvetica", "", 12)
pdf.CellFormat(0, 10, title, "", 1, "L", false, 0, "")
return pdf.OutputFileAndClose(path)
}
func TestGenerateInvoicePDF_Handler_CreatesFile(t *testing.T) {
dir := t.TempDir()
// Also create a terms file so merge path is exercised
if err := createPDF(filepath.Join(dir, "CMC_terms_and_conditions2006_A4.pdf"), "terms"); err != nil {
t.Fatalf("failed to create terms: %v", err)
}
reqBody := InvoicePDFRequest{
DocumentID: 1,
InvoiceTitle: "INV-1001",
CustomerName: "Acme Corp",
ShipVia: "Courier",
FOB: "Sydney",
IssueDate: "2025-01-01",
CurrencySymbol: "$",
ShowGST: true,
LineItems: []InvoiceLineItemRequest{{
ItemNumber: "1",
Quantity: "2",
Title: "Widget",
UnitPrice: 10.00,
TotalPrice: 20.00,
}},
OutputDir: dir,
}
// Add an extra file to append
extraPath := filepath.Join(dir, "extra.pdf")
if err := createPDF(extraPath, "extra"); err != nil {
t.Fatalf("failed to create extra: %v", err)
}
reqBody.AppendFiles = []string{extraPath}
b, _ := json.Marshal(reqBody)
r := httptest.NewRequest(http.MethodPost, "/go/pdf/generate-invoice", bytes.NewReader(b))
w := httptest.NewRecorder()
GenerateInvoicePDF(w, r)
resp := w.Result()
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
data, _ := io.ReadAll(resp.Body)
t.Fatalf("unexpected status: %d body=%s", resp.StatusCode, string(data))
}
// Verify file created
final := filepath.Join(dir, "INV-1001.pdf")
st, err := os.Stat(final)
if err != nil {
t.Fatalf("expected output file not found: %v", err)
}
if st.Size() <= 0 {
t.Fatalf("output pdf has zero size")
}
}