| 1 | package contract |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/carlosframework/docs/internal/export" |
| 12 | "golang.org/x/text/currency" |
| 13 | ) |
| 14 | |
| 15 | // Value represents a supplied value, including zero money. Absence is a |
| 16 | // missing map entry. Text is used for text/date, MinorUnits for money. |
| 17 | type Value struct { |
| 18 | Kind Kind |
| 19 | Text string |
| 20 | MinorUnits int64 |
| 21 | Currency string |
| 22 | } |
| 23 | |
| 24 | const ISOFormat = "iso" |
| 25 | |
| 26 | func currencyScale(code string) (int, bool) { |
| 27 | if len(code) != 3 || code != strings.ToUpper(code) || code == "XXX" || code == "XTS" { |
| 28 | return 0, false |
| 29 | } |
| 30 | u, err := currency.ParseISO(code) |
| 31 | if err != nil { |
| 32 | return 0, false |
| 33 | } |
| 34 | scale, _ := currency.Standard.Rounding(u) |
| 35 | return scale, true |
| 36 | } |
| 37 | |
| 38 | func formatValue(f Field, v Value, path string) (string, error) { |
| 39 | if v.Kind != f.Kind { |
| 40 | return "", problem("value_type", path) |
| 41 | } |
| 42 | if !validText(v.Text, MaxValueBytes) { |
| 43 | return "", problem("invalid_value", path) |
| 44 | } |
| 45 | if wordTooLong(v.Text) { |
| 46 | return "", problem("word_limit", path) |
| 47 | } |
| 48 | if v.Kind != Money && (v.MinorUnits != 0 || v.Currency != "") { |
| 49 | return "", problem("unexpected_money", path) |
| 50 | } |
| 51 | switch v.Kind { |
| 52 | case Text: |
| 53 | if strings.TrimSpace(v.Text) == "" && !f.Optional { |
| 54 | return "", problem("required_value", path) |
| 55 | } |
| 56 | return v.Text, nil |
| 57 | case Date: |
| 58 | date, err := time.Parse("2006-01-02", v.Text) |
| 59 | if err != nil || date.Year() < 1 || date.Format("2006-01-02") != v.Text { |
| 60 | return "", problem("invalid_date", path) |
| 61 | } |
| 62 | return v.Text, nil |
| 63 | case Money: |
| 64 | if v.Text != "" || v.Currency != f.Currency { |
| 65 | return "", problem("currency_mismatch", path) |
| 66 | } |
| 67 | scale, _ := currencyScale(f.Currency) // definition already validated |
| 68 | digits := strconv.FormatInt(v.MinorUnits, 10) |
| 69 | sign := "" |
| 70 | if strings.HasPrefix(digits, "-") { |
| 71 | sign, digits = "-", digits[1:] |
| 72 | } |
| 73 | if scale > 0 { |
| 74 | if len(digits) <= scale { |
| 75 | digits = strings.Repeat("0", scale+1-len(digits)) + digits |
| 76 | } |
| 77 | digits = digits[:len(digits)-scale] + "." + digits[len(digits)-scale:] |
| 78 | } |
| 79 | return f.Currency + " " + sign + digits, nil |
| 80 | } |
| 81 | return "", problem("unsupported_kind", path) |
| 82 | } |
| 83 | |
| 84 | // Resolve validates all input before producing a fresh tree. It never mutates |
| 85 | // the template or reinterprets a value as field syntax, markup or an expression. |
| 86 | func Resolve(t Template, values map[string]Value, format string) (export.Document, error) { |
| 87 | if format != ISOFormat { |
| 88 | return export.Document{}, problem("unsupported_format", "format") |
| 89 | } |
| 90 | if err := t.Validate(); err != nil { |
| 91 | return export.Document{}, err |
| 92 | } |
| 93 | if len(values) > len(t.Fields) { |
| 94 | return export.Document{}, problem("unexpected_values", "values") |
| 95 | } |
| 96 | resolved := make(map[string]string, len(t.Fields)) |
| 97 | for i, f := range t.Fields { |
| 98 | path := fmt.Sprintf("fields[%d]", i) |
| 99 | v, present := values[f.Key] |
| 100 | if !present { |
| 101 | if !f.Optional { |
| 102 | return export.Document{}, problem("required_value", path) |
| 103 | } |
| 104 | resolved[f.Key] = "" |
| 105 | continue |
| 106 | } |
| 107 | text, err := formatValue(f, v, path) |
| 108 | if err != nil { |
| 109 | return export.Document{}, err |
| 110 | } |
| 111 | resolved[f.Key] = text |
| 112 | } |
| 113 | for key := range values { |
| 114 | if _, ok := resolved[key]; !ok { |
| 115 | return export.Document{}, problem("unexpected_values", "values") |
| 116 | } |
| 117 | } |
| 118 | remaining := expansionBudget{text: MaxTextBytes - len(t.Title), nodes: MaxNodes} |
| 119 | root, err := resolveNode(t.Root, resolved, &remaining) |
| 120 | if err != nil { |
| 121 | return export.Document{}, err |
| 122 | } |
| 123 | return export.Document{Title: t.Title, Root: root}, nil |
| 124 | } |
| 125 | |
| 126 | type expansionBudget struct{ text, nodes int } |
| 127 | |
| 128 | func resolveNode(n Node, values map[string]string, remaining *expansionBudget) (export.Node, error) { |
| 129 | remaining.nodes-- |
| 130 | if remaining.nodes < 0 { |
| 131 | return export.Node{}, problem("expanded_node_limit", "root") |
| 132 | } |
| 133 | out := export.Node{Type: n.Type, Text: n.Text, |
| 134 | Attrs: export.Attrs{Level: n.Attrs.Level, Align: n.Attrs.Align, Indent: n.Attrs.Indent}, |
| 135 | Marks: append([]export.Mark(nil), n.Marks...)} |
| 136 | if n.Type == "merge_field" { |
| 137 | out.Type, out.Text = "text", values[n.Attrs.Key] |
| 138 | } |
| 139 | remaining.text -= len(out.Text) |
| 140 | if remaining.text < 0 { |
| 141 | return export.Node{}, problem("expanded_text_limit", "root") |
| 142 | } |
| 143 | for _, child := range n.Content { |
| 144 | c, err := resolveNode(child, values, remaining) |
| 145 | if err != nil { |
| 146 | return export.Node{}, err |
| 147 | } |
| 148 | // An optional absent field becomes no node, not an invalid empty text. |
| 149 | if c.Type == "text" && c.Text == "" { |
| 150 | continue |
| 151 | } |
| 152 | if c.Type == "text" && strings.Contains(c.Text, "\n") { |
| 153 | // The exporter treats newlines inside a text run as whitespace. |
| 154 | // Explicit breaks preserve multiline values and code-block lines. |
| 155 | parts := strings.Split(c.Text, "\n") |
| 156 | remaining.nodes -= 2 * (len(parts) - 1) |
| 157 | if remaining.nodes < 0 { |
| 158 | return export.Node{}, problem("expanded_node_limit", "root") |
| 159 | } |
| 160 | for i, part := range parts { |
| 161 | if i > 0 { |
| 162 | out.Content = append(out.Content, export.Node{Type: "hard_break", Marks: append([]export.Mark(nil), c.Marks...)}) |
| 163 | } |
| 164 | if part != "" { |
| 165 | run := c |
| 166 | run.Text = part |
| 167 | run.Marks = append([]export.Mark(nil), c.Marks...) |
| 168 | out.Content = append(out.Content, run) |
| 169 | } |
| 170 | } |
| 171 | continue |
| 172 | } |
| 173 | out.Content = append(out.Content, c) |
| 174 | } |
| 175 | return out, nil |
| 176 | } |
| 177 | |
| 178 | // Preview is an in-memory rendering, not a persisted or authorised agreement. |
| 179 | // Persist PDF exactly if it later becomes the subject of a signing operation. |
| 180 | type Preview struct { |
| 181 | Document export.Document |
| 182 | PDF []byte |
| 183 | SHA256 [32]byte |
| 184 | TemplateVersion int |
| 185 | Renderer string |
| 186 | } |
| 187 | |
| 188 | // Render refuses output that would substitute glyphs or overflow the page. |
| 189 | // Errors return the zero Preview, never a partially usable document or PDF. |
| 190 | func Render(t Template, values map[string]Value, format string) (Preview, error) { |
| 191 | doc, err := Resolve(t, values, format) |
| 192 | if err != nil { |
| 193 | return Preview{}, err |
| 194 | } |
| 195 | if renderedBytes(doc.Root)+len(doc.Title) > MaxRenderTextBytes { |
| 196 | return Preview{}, problem("render_text_limit", "document") |
| 197 | } |
| 198 | data, report, err := export.PDFBounded(doc, MaxPreviewPages) |
| 199 | if errors.Is(err, export.ErrPageLimit) { |
| 200 | return Preview{}, problem("page_limit", "document") |
| 201 | } |
| 202 | if err != nil { |
| 203 | return Preview{}, problem("render_failed", "document") |
| 204 | } |
| 205 | if !report.Empty() { |
| 206 | return Preview{}, problem("missing_glyphs", "document") |
| 207 | } |
| 208 | if report.LayoutOverflow { |
| 209 | return Preview{}, problem("layout_overflow", "document") |
| 210 | } |
| 211 | return Preview{Document: doc, PDF: data, SHA256: sha256.Sum256(data), TemplateVersion: Version, Renderer: "docs-contract-pdf-v1"}, nil |
| 212 | } |
| 213 | |
| 214 | func renderedBytes(n export.Node) int { |
| 215 | total := len(n.Text) |
| 216 | for _, c := range n.Content { |
| 217 | total += renderedBytes(c) |
| 218 | } |
| 219 | return total |
| 220 | } |
| 221 | |