feat(contracts): fill the AVV from the company profile
A workspace whose company profile is submitted and whose Geschäftsleitung is named (Verantwortliche) now sees its AVV filled in: name with legal form, address, "Vertreten durch" and, as the owner decided, "Geschäftsleitung" on the Weisung line. The new package internal/legal/avvfill writes the details onto the released master as one incremental PDF update: the two content streams holding the blank lines are replaced, the underscores dropped and the value set in their place in Geist Regular at body size, inside the line's marked content. The master's bytes stay an untouched prefix, so its pin still holds; the result is deterministic and cached by master and details digest. Layouts are pinned per master SHA-256; a test makes every released AVV master have one.
Until then the master is listed with "missing" (profile, company_name, address, management) for the portal's hint; details that do not fit the form or the Windows-1252 character set give "manual" and a log line without the values. A staff upload still wins (filled_from: staff). The admin avv-values answer uses the same derivation; its Weisung is now "Geschäftsleitung" only. The legal form is no longer appended twice when the name writes it without spaces ("UG(haftungsbeschränkt)").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
16b4b9528f
commit
05673defd4
9 files changed
+927
-40
No files matched your search
@@ -17,6 +17,8 @@ require (
|
||||
go.opentelemetry.io/otel/sdk v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.48.0
|
||||
golang.org/x/text v0.44.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -89,9 +91,8 @@ require (
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/grpc v1.83.2 // indirect
|
||||
|
||||
@@ -204,21 +204,23 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
|
||||
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2023 Vercel, in collaboration with basement.studio
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,411 @@
|
||||
// Package avvfill writes a customer's details onto the blank lines of a
|
||||
// released AVV master PDF.
|
||||
//
|
||||
// The master is never changed: the filled PDF is the master's bytes followed
|
||||
// by one incremental update (ISO 32000-1, 7.5.6). The update replaces the
|
||||
// two content streams that hold the blank lines: in each line's text run the
|
||||
// underscores are dropped and the value is set in their place, in Geist
|
||||
// Regular (the master's body font, embedded whole because the master's copy
|
||||
// is a subset), at body size. The value stays inside the line's marked
|
||||
// content, so it is part of the tagged structure like the label before it.
|
||||
// Everything else stays as released, so the master's digest holds for the
|
||||
// first len(master) bytes of every filled AVV.
|
||||
//
|
||||
// Where the lines are is pinned per master (by its SHA-256), like the master
|
||||
// itself: a new master version needs its layout added here, and a master
|
||||
// without one is not filled.
|
||||
package avvfill
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"crypto/sha256"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/sfnt"
|
||||
"golang.org/x/image/math/fixed"
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
)
|
||||
|
||||
// Values are the Verantwortlicher's details, one per blank line.
|
||||
type Values struct {
|
||||
Name string // Name des Verantwortlichen
|
||||
Anschrift string // Anschrift
|
||||
Vertreten string // Vertreten durch
|
||||
Weisung string // Weisungsberechtigte Person oder Stelle
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrNoLayout: there is no pinned layout for this master.
|
||||
ErrNoLayout = errors.New("avvfill: no layout for this master")
|
||||
// ErrEmpty: a value is empty; a blank line is never "filled" with nothing.
|
||||
ErrEmpty = errors.New("avvfill: empty value")
|
||||
// ErrTooLong: a value does not fit its line even at the smallest size.
|
||||
ErrTooLong = errors.New("avvfill: value too long for its line")
|
||||
// ErrNotEncodable: a value has a character the font encoding lacks.
|
||||
ErrNotEncodable = errors.New("avvfill: value has a character outside Windows-1252")
|
||||
)
|
||||
|
||||
// Body size as in the master; a value too long for its line is set smaller,
|
||||
// down to minSize.
|
||||
const (
|
||||
bodySize = 10.0
|
||||
minSize = 8.0
|
||||
)
|
||||
|
||||
// line is one blank line: the text run that holds it (its stream and the
|
||||
// operators that start it), where its underscores start and how far a value
|
||||
// may run (the text column's right edge), in PDF points.
|
||||
type line struct {
|
||||
stream int
|
||||
run string // e.g. "68.15 709.139 Td /F3 10 Tf["
|
||||
x, right float64
|
||||
}
|
||||
|
||||
type layout struct {
|
||||
fontDict int // the shared /Font resource dictionary
|
||||
blank string // the space-and-underscore glyph pair that starts each blank, e.g. "<0120>"
|
||||
under string // one more underscore glyph, e.g. "<20>"
|
||||
lines [4]line
|
||||
}
|
||||
|
||||
// layouts, by the master's SHA-256. Read from the master (content stream
|
||||
// text runs; x from pdftotext -bbox); the test checks them against it.
|
||||
var layouts = map[string]layout{
|
||||
// AVV 1.0.0 (AS06, Stand 17.11.2026): page 2 Vertragsparteien, page 4 § 5 (2).
|
||||
"623aa518fdaaa3c8a7e5aa2f15a97ac3b853c8d49d83e41f371b8cf2370a4040": {
|
||||
fontDict: 404, blank: "<0120>", under: "<20>",
|
||||
lines: [4]line{
|
||||
{stream: 65, run: "68.15 709.139 Td /F3 10 Tf[", x: 203.32, right: 527.15},
|
||||
{stream: 65, run: "68.15 694.189 Td /F3 10 Tf[", x: 116.62, right: 527.15},
|
||||
{stream: 65, run: "68.15 679.239 Td /F3 10 Tf[", x: 147.55, right: 527.15},
|
||||
{stream: 239, run: "68.15 599.439 Td /F3 10 Tf[", x: 261.04, right: 527.15},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// HasLayout reports whether the master with that digest can be filled.
|
||||
func HasLayout(masterSHA256 string) bool { _, ok := layouts[masterSHA256]; return ok }
|
||||
|
||||
// Fill returns the master with v on its blank lines. The result depends only
|
||||
// on master and v: the same input always gives the same bytes.
|
||||
func Fill(master []byte, v Values) ([]byte, error) {
|
||||
sum := sha256.Sum256(master)
|
||||
lay, ok := layouts[hex.EncodeToString(sum[:])]
|
||||
if !ok {
|
||||
return nil, ErrNoLayout
|
||||
}
|
||||
f, err := geist()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tr, err := readTrailer(master)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fontObj, descObj, fileObj := tr.size, tr.size+1, tr.size+2
|
||||
|
||||
// The content streams, decoded once each.
|
||||
content := map[int][]byte{}
|
||||
for _, l := range lay.lines {
|
||||
if content[l.stream] == nil {
|
||||
if content[l.stream], err = streamData(master, l.stream); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, val := range []string{v.Name, v.Anschrift, v.Vertreten, v.Weisung} {
|
||||
val = strings.Join(strings.Fields(val), " ")
|
||||
if val == "" {
|
||||
return nil, ErrEmpty
|
||||
}
|
||||
enc, err := charmap.Windows1252.NewEncoder().Bytes([]byte(val))
|
||||
if err != nil || bytes.IndexByte(enc, 0x7f) >= 0 || bytes.IndexFunc(enc, func(r rune) bool { return r < 32 }) >= 0 {
|
||||
return nil, ErrNotEncodable
|
||||
}
|
||||
l := lay.lines[i]
|
||||
size := bodySize
|
||||
if w := f.width(enc) / 1000; l.x+w*size > l.right {
|
||||
size = float64(int((l.right-l.x)/w*100)) / 100 // round down: the text stays inside
|
||||
if size < minSize {
|
||||
return nil, ErrTooLong
|
||||
}
|
||||
}
|
||||
if content[l.stream], err = replaceBlank(content[l.stream], lay, l, fmt.Sprintf("/FAVV %s Tf<%s>Tj", num(size), hex.EncodeToString(enc))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
objs := map[int][]byte{}
|
||||
for n, data := range content {
|
||||
objs[n] = flateStream(data, "")
|
||||
}
|
||||
fontDict, err := objectBody(master, lay.fontDict)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
end := bytes.LastIndex(fontDict, []byte(">>"))
|
||||
if !bytes.HasPrefix(fontDict, []byte("<<")) || end < 0 || bytes.Contains(fontDict, []byte("/FAVV")) {
|
||||
return nil, fmt.Errorf("avvfill: unexpected font dictionary %d", lay.fontDict)
|
||||
}
|
||||
objs[lay.fontDict] = append(append(append([]byte{}, fontDict[:end]...), fmt.Sprintf("/FAVV %d 0 R", fontObj)...), fontDict[end:]...)
|
||||
objs[fontObj] = []byte(fmt.Sprintf("<</Type/Font/Subtype/TrueType/BaseFont/Geist-Regular/FirstChar 32/LastChar 255/Widths[%s]/Encoding/WinAnsiEncoding/FontDescriptor %d 0 R>>",
|
||||
f.widthsArray(), descObj))
|
||||
objs[descObj] = []byte(fmt.Sprintf("<</Type/FontDescriptor/FontName/Geist-Regular/Flags 32/FontBBox[%s]/ItalicAngle 0/Ascent %d/Descent %d/CapHeight %d/StemV 80/FontFile2 %d 0 R>>",
|
||||
f.bbox, f.ascent, f.descent, f.capHeight, fileObj))
|
||||
objs[fileObj] = flateStream(geistTTF, fmt.Sprintf("/Length1 %d", len(geistTTF)))
|
||||
|
||||
// The update: objects, a cross-reference section for them, the trailer.
|
||||
out := bytes.NewBuffer(make([]byte, 0, len(master)+len(geistTTF)))
|
||||
out.Write(master)
|
||||
if !bytes.HasSuffix(master, []byte("\n")) {
|
||||
out.WriteByte('\n')
|
||||
}
|
||||
nums := make([]int, 0, len(objs))
|
||||
for k := range objs {
|
||||
nums = append(nums, k)
|
||||
}
|
||||
sort.Ints(nums)
|
||||
offsets := map[int]int{}
|
||||
for _, k := range nums {
|
||||
offsets[k] = out.Len()
|
||||
fmt.Fprintf(out, "%d 0 obj\n", k)
|
||||
out.Write(objs[k])
|
||||
out.WriteString("\nendobj\n")
|
||||
}
|
||||
xref := out.Len()
|
||||
out.WriteString("xref\n")
|
||||
for i := 0; i < len(nums); {
|
||||
j := i
|
||||
for j+1 < len(nums) && nums[j+1] == nums[j]+1 {
|
||||
j++
|
||||
}
|
||||
fmt.Fprintf(out, "%d %d\n", nums[i], j-i+1)
|
||||
for _, k := range nums[i : j+1] {
|
||||
fmt.Fprintf(out, "%010d 00000 n \n", offsets[k])
|
||||
}
|
||||
i = j + 1
|
||||
}
|
||||
fmt.Fprintf(out, "trailer\n<</Size %d/Root %s/Info %s/ID %s/Prev %d>>\nstartxref\n%d\n%%%%EOF\n",
|
||||
fileObj+1, tr.root, tr.info, tr.id, tr.startxref, xref)
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// replaceBlank finds the line's text run (exactly once), checks that it ends
|
||||
// with the blank (a space-underscore pair, then only kerned underscores up to
|
||||
// "]TJ"), and puts the value in place of the underscores, in the same text
|
||||
// object and marked content.
|
||||
func replaceBlank(stream []byte, lay layout, l line, value string) ([]byte, error) {
|
||||
if bytes.Count(stream, []byte(l.run)) != 1 {
|
||||
return nil, fmt.Errorf("avvfill: text run %q not found once in stream %d", l.run, l.stream)
|
||||
}
|
||||
i := bytes.Index(stream, []byte(l.run))
|
||||
e := bytes.Index(stream[i:], []byte("]TJ"))
|
||||
if e < 0 {
|
||||
return nil, fmt.Errorf("avvfill: text run %q has no end", l.run)
|
||||
}
|
||||
tj := stream[i : i+e]
|
||||
b := bytes.Index(tj, []byte(lay.blank))
|
||||
if b < 0 || bytes.Count(tj, []byte(lay.blank)) != 1 {
|
||||
return nil, fmt.Errorf("avvfill: text run %q has no single blank", l.run)
|
||||
}
|
||||
rest := strings.TrimLeft(string(tj[b+len(lay.blank):]), "")
|
||||
if !regexp.MustCompile(`^(-?\d+` + regexp.QuoteMeta(lay.under) + `)+$`).MatchString(rest) {
|
||||
return nil, fmt.Errorf("avvfill: text run %q does not end in underscores", l.run)
|
||||
}
|
||||
space := strings.Replace(lay.blank, lay.under[1:len(lay.under)-1]+">", ">", 1) // "<0120>" -> "<01>"
|
||||
var out bytes.Buffer
|
||||
out.Write(stream[:i+b])
|
||||
out.WriteString(space)
|
||||
out.WriteString("]TJ")
|
||||
out.WriteString(value)
|
||||
out.Write(stream[i+e+len("]TJ"):])
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// num writes a coordinate without trailing zeros.
|
||||
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
|
||||
|
||||
func flateStream(data []byte, extra string) []byte {
|
||||
var z bytes.Buffer
|
||||
w, _ := zlib.NewWriterLevel(&z, zlib.BestCompression)
|
||||
_, _ = w.Write(data)
|
||||
_ = w.Close()
|
||||
return []byte(fmt.Sprintf("<</Length %d/Filter/FlateDecode%s>>\nstream\n%s\nendstream", z.Len(), extra, z.Bytes()))
|
||||
}
|
||||
|
||||
// ─── reading the master ────────────────────────────────────────────────────
|
||||
|
||||
type trailer struct {
|
||||
size, startxref int
|
||||
root, info, id string
|
||||
}
|
||||
|
||||
var (
|
||||
reStartxref = regexp.MustCompile(`startxref\s+(\d+)\s+%%EOF\s*$`)
|
||||
reSize = regexp.MustCompile(`/Size (\d+)`)
|
||||
reRoot = regexp.MustCompile(`/Root (\d+ \d+ R)`)
|
||||
reInfo = regexp.MustCompile(`/Info (\d+ \d+ R)`)
|
||||
reID = regexp.MustCompile(`/ID\s*\[\s*(<[0-9A-Fa-f]+>)\s*(<[0-9A-Fa-f]+>)\s*\]`)
|
||||
)
|
||||
|
||||
// readTrailer reads the master's single classic trailer (one revision, a
|
||||
// cross-reference table, no streams: as LibreOffice writes it).
|
||||
func readTrailer(pdf []byte) (trailer, error) {
|
||||
var t trailer
|
||||
m := reStartxref.FindSubmatch(pdf)
|
||||
i := bytes.LastIndex(pdf, []byte("trailer"))
|
||||
if m == nil || i < 0 || bytes.Count(pdf, []byte("startxref")) != 1 {
|
||||
return t, errors.New("avvfill: master is not a single-revision PDF")
|
||||
}
|
||||
t.startxref, _ = strconv.Atoi(string(m[1]))
|
||||
tail := pdf[i:]
|
||||
s, r, in, id := reSize.FindSubmatch(tail), reRoot.FindSubmatch(tail), reInfo.FindSubmatch(tail), reID.FindSubmatch(tail)
|
||||
if s == nil || r == nil || in == nil || id == nil {
|
||||
return t, errors.New("avvfill: master trailer lacks Size, Root, Info or ID")
|
||||
}
|
||||
t.size, _ = strconv.Atoi(string(s[1]))
|
||||
t.root, t.info = string(r[1]), string(in[1])
|
||||
t.id = "[" + string(id[1]) + string(id[2]) + "]"
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// objectBody is what stands between "n 0 obj" and "endobj" (dictionaries
|
||||
// only; the objects rewritten here have no stream).
|
||||
func objectBody(pdf []byte, n int) ([]byte, error) {
|
||||
head := []byte(fmt.Sprintf("\n%d 0 obj", n))
|
||||
i := bytes.Index(pdf, head)
|
||||
if i < 0 || bytes.Count(pdf, head) != 1 {
|
||||
return nil, fmt.Errorf("avvfill: object %d not found once", n)
|
||||
}
|
||||
rest := pdf[i+len(head):]
|
||||
j := bytes.Index(rest, []byte("endobj"))
|
||||
if j < 0 {
|
||||
return nil, fmt.Errorf("avvfill: object %d has no end", n)
|
||||
}
|
||||
body := bytes.TrimSpace(rest[:j])
|
||||
if bytes.Contains(body, []byte("stream")) {
|
||||
return nil, fmt.Errorf("avvfill: object %d is a stream", n)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// streamData is the decoded data of stream object n (FlateDecode, its
|
||||
// /Length direct or indirect).
|
||||
func streamData(pdf []byte, n int) ([]byte, error) {
|
||||
head := []byte(fmt.Sprintf("\n%d 0 obj", n))
|
||||
i := bytes.Index(pdf, head)
|
||||
if i < 0 || bytes.Count(pdf, head) != 1 {
|
||||
return nil, fmt.Errorf("avvfill: object %d not found once", n)
|
||||
}
|
||||
rest := pdf[i+len(head):]
|
||||
k := bytes.Index(rest, []byte("stream"))
|
||||
if k < 0 {
|
||||
return nil, fmt.Errorf("avvfill: object %d is no stream", n)
|
||||
}
|
||||
dict := rest[:k]
|
||||
if !bytes.Contains(dict, []byte("/FlateDecode")) {
|
||||
return nil, fmt.Errorf("avvfill: stream %d is not Flate", n)
|
||||
}
|
||||
var length int
|
||||
if m := regexp.MustCompile(`/Length (\d+) 0 R`).FindSubmatch(dict); m != nil {
|
||||
ln, _ := strconv.Atoi(string(m[1]))
|
||||
b, err := objectBody(pdf, ln)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
length, _ = strconv.Atoi(string(b))
|
||||
} else if m := regexp.MustCompile(`/Length (\d+)`).FindSubmatch(dict); m != nil {
|
||||
length, _ = strconv.Atoi(string(m[1]))
|
||||
}
|
||||
data := rest[k+len("stream"):]
|
||||
data = bytes.TrimPrefix(bytes.TrimPrefix(data, []byte("\r")), []byte("\n"))
|
||||
if length <= 0 || length > len(data) {
|
||||
return nil, fmt.Errorf("avvfill: stream %d has no usable length", n)
|
||||
}
|
||||
r, err := zlib.NewReader(bytes.NewReader(data[:length]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("avvfill: stream %d: %w", n, err)
|
||||
}
|
||||
return io.ReadAll(r)
|
||||
}
|
||||
|
||||
// ─── the font ──────────────────────────────────────────────────────────────
|
||||
|
||||
// geistTTF is Geist Regular (OFL 1.1, see OFL.txt), the master's body font,
|
||||
// embedded whole: the master's own copy is a subset without the glyphs a
|
||||
// customer's details may need.
|
||||
//
|
||||
//go:embed Geist-Regular.ttf
|
||||
var geistTTF []byte
|
||||
|
||||
type fontInfo struct {
|
||||
widths [224]int // codes 32..255, in 1/1000 em
|
||||
bbox string
|
||||
ascent, descent, capHeight int
|
||||
}
|
||||
|
||||
func (f *fontInfo) width(enc []byte) float64 {
|
||||
w := 0
|
||||
for _, c := range enc {
|
||||
if c >= 32 {
|
||||
w += f.widths[c-32]
|
||||
}
|
||||
}
|
||||
return float64(w)
|
||||
}
|
||||
|
||||
func (f *fontInfo) widthsArray() string {
|
||||
s := make([]string, len(f.widths))
|
||||
for i, w := range f.widths {
|
||||
s[i] = strconv.Itoa(w)
|
||||
}
|
||||
return strings.Join(s, " ")
|
||||
}
|
||||
|
||||
var geist = sync.OnceValues(func() (*fontInfo, error) {
|
||||
ft, err := sfnt.Parse(geistTTF)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("avvfill: font: %w", err)
|
||||
}
|
||||
var buf sfnt.Buffer
|
||||
upem := fixed.Int26_6(ft.UnitsPerEm())
|
||||
ppem := upem // advances in font units
|
||||
scale := func(v fixed.Int26_6) int { return int((int64(v)*1000 + int64(upem)/2) / int64(upem)) }
|
||||
f := &fontInfo{}
|
||||
dec := charmap.Windows1252
|
||||
for c := 32; c <= 255; c++ {
|
||||
r := dec.DecodeByte(byte(c))
|
||||
gi, err := ft.GlyphIndex(&buf, r)
|
||||
if err != nil || gi == 0 {
|
||||
gi, _ = ft.GlyphIndex(&buf, ' ') // a code the font lacks takes a space's width
|
||||
}
|
||||
adv, err := ft.GlyphAdvance(&buf, gi, ppem, font.HintingNone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("avvfill: font: %w", err)
|
||||
}
|
||||
f.widths[c-32] = scale(adv)
|
||||
}
|
||||
b, err := ft.Bounds(&buf, ppem, font.HintingNone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("avvfill: font: %w", err)
|
||||
}
|
||||
// sfnt's y axis points down; PDF's up.
|
||||
f.bbox = fmt.Sprintf("%d %d %d %d", scale(b.Min.X), -scale(b.Max.Y), scale(b.Max.X), -scale(b.Min.Y))
|
||||
m, err := ft.Metrics(&buf, ppem, font.HintingNone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("avvfill: font: %w", err)
|
||||
}
|
||||
f.ascent, f.descent, f.capHeight = scale(m.Ascent), -scale(m.Descent), scale(m.CapHeight)
|
||||
return f, nil
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
package avvfill
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
|
||||
)
|
||||
|
||||
// Synthetic details only: never a customer's.
|
||||
var sample = Values{
|
||||
Name: "Muster Präzisionsmaschinenbau GmbH & Co. KG",
|
||||
Anschrift: "Industriestraße 123, 78351 Bodman-Ludwigshafen",
|
||||
Vertreten: "Maximilian Mustermann und Erika Musterfrau-Beispiel",
|
||||
Weisung: "Geschäftsleitung",
|
||||
}
|
||||
|
||||
func master(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
d := contractdocs.Default().Get("avv")
|
||||
if d == nil {
|
||||
t.Fatal("no released AVV master")
|
||||
}
|
||||
return d.PDF
|
||||
}
|
||||
|
||||
// Every released AVV master can be filled: a new master needs its layout.
|
||||
func TestEveryReleasedMasterHasALayout(t *testing.T) {
|
||||
for _, d := range contractdocs.Default().All() {
|
||||
if d.Kind == contractdocs.KindAVV && !HasLayout(d.SHA256) {
|
||||
t.Errorf("AVV %s (%s) has no layout", d.Version, d.SHA256)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFill_appendsOneUpdateAndKeepsTheMaster(t *testing.T) {
|
||||
m := master(t)
|
||||
out, err := Fill(m, sample)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.HasPrefix(out, m) {
|
||||
t.Fatal("the master is not a prefix of the filled AVV")
|
||||
}
|
||||
if again, _ := Fill(m, sample); !bytes.Equal(out, again) {
|
||||
t.Fatal("not deterministic")
|
||||
}
|
||||
upd := out[len(m)-1:] // from the master's last newline
|
||||
tr, err := readTrailer(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Contains(upd, []byte(fmt.Sprintf("/Prev %d>>", tr.startxref))) || !bytes.HasSuffix(out, []byte("%%EOF\n")) {
|
||||
t.Fatalf("trailer: %s", upd[bytes.LastIndex(upd, []byte("trailer")):])
|
||||
}
|
||||
|
||||
// Every cross-reference entry of the update points at its object.
|
||||
xr := bytes.LastIndex(out, []byte("\nxref\n")) + 1
|
||||
sec := regexp.MustCompile(`(?m)^(\d+) (\d+)\n((?:\d{10} 00000 n \n)+)`).FindAllSubmatch(out[xr:], -1)
|
||||
seen := 0
|
||||
for _, s := range sec {
|
||||
first, _ := strconv.Atoi(string(s[1]))
|
||||
for i, e := range strings.Split(strings.TrimSpace(string(s[3])), "\n") {
|
||||
off, _ := strconv.Atoi(e[:10])
|
||||
if !bytes.HasPrefix(out[off:], []byte(fmt.Sprintf("%d 0 obj\n", first+i))) {
|
||||
t.Errorf("xref %d -> %d", first+i, off)
|
||||
}
|
||||
seen++
|
||||
}
|
||||
}
|
||||
if seen != 6 { // two content streams, the font dictionary, font, descriptor, file
|
||||
t.Errorf("%d updated objects", seen)
|
||||
}
|
||||
|
||||
// The lines: label, a space, the value in the new font; no underscore left.
|
||||
lay := layouts[hex.EncodeToString(sha(m))]
|
||||
for i, val := range []string{sample.Name, sample.Anschrift, sample.Vertreten, sample.Weisung} {
|
||||
l := lay.lines[i]
|
||||
data, err := streamData(upd, l.stream)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
enc, _ := charmap.Windows1252.NewEncoder().Bytes([]byte(val))
|
||||
run := data[bytes.Index(data, []byte(l.run)):]
|
||||
run = run[:bytes.Index(run, []byte("ET"))]
|
||||
want := "<01>]TJ/FAVV 10 Tf<" + hex.EncodeToString(enc) + ">Tj"
|
||||
if !bytes.HasSuffix(bytes.TrimSpace(run), []byte(want)) || bytes.Contains(run, []byte(lay.under)) {
|
||||
t.Errorf("line %d: %s", i, run)
|
||||
}
|
||||
}
|
||||
if !bytes.Contains(upd, []byte("/FAVV 430 0 R")) || !bytes.Contains(upd, []byte("/FontFile2 432 0 R")) {
|
||||
t.Error("font not wired in")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFill_shrinksALongValueAndRefusesWhatDoesNotFit(t *testing.T) {
|
||||
m := master(t)
|
||||
long := sample
|
||||
long.Weisung = "Geschäftsleitung (datenschutz@mustermann-maschinenbau.de)" // 299 pt at 10 pt, room 266
|
||||
out, err := Fill(m, long)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := streamData(out[len(m)-1:], 239)
|
||||
sz := regexp.MustCompile(`/FAVV ([\d.]+) Tf`).FindSubmatch(data)
|
||||
if f, _ := strconv.ParseFloat(string(sz[1]), 64); f >= bodySize || f < minSize {
|
||||
t.Errorf("size %s", sz[1])
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
v Values
|
||||
want error
|
||||
}{
|
||||
"too long": {Values{sample.Name, sample.Anschrift, sample.Vertreten, strings.Repeat("Geschäftsleitung ", 6)}, ErrTooLong},
|
||||
"empty": {Values{sample.Name, " ", sample.Vertreten, sample.Weisung}, ErrEmpty},
|
||||
"not 1252": {Values{"Łódź Sp. z o.o.", sample.Anschrift, sample.Vertreten, sample.Weisung}, ErrNotEncodable},
|
||||
"control": {Values{"Muster\x01GmbH", sample.Anschrift, sample.Vertreten, sample.Weisung}, ErrNotEncodable},
|
||||
} {
|
||||
if _, err := Fill(m, c.v); !errors.Is(err, c.want) {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := Fill([]byte("%PDF-1.7 other"), sample); !errors.Is(err, ErrNoLayout) {
|
||||
t.Errorf("other master: %v", err)
|
||||
}
|
||||
// Whitespace inside a value is collapsed; Windows-1252 extras pass.
|
||||
if _, err := Fill(m, Values{"Muster „Café“ GmbH", sample.Anschrift, sample.Vertreten, sample.Weisung}); err != nil {
|
||||
t.Errorf("1252 extras: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func sha(b []byte) []byte { s := sha256.Sum256(b); return s[:] }
|
||||
@@ -13,10 +13,13 @@ import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/legal/avvfill"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/roles"
|
||||
@@ -32,6 +35,10 @@ import (
|
||||
// GET /v1/tenants/{id}/contracts overview, "documents" (tenants.read)
|
||||
// GET /v1/tenants/{id}/contracts/documents/{doc}.pdf the PDF (tenants.read)
|
||||
// GET /v1/admin/tenants/{id}/avv-values the details for the AVV (admin, staff only)
|
||||
//
|
||||
// The AVV a workspace sees: the one staff uploaded for it, else the master
|
||||
// filled with its details (avvfill) once the company profile is submitted
|
||||
// and its Geschäftsleitung is named, else the master, with what is missing.
|
||||
// PUT /v1/admin/tenants/{id}/contract-documents/avv the filled AVV (admin, staff only)
|
||||
|
||||
// maxContractPDFBytes caps a filled AVV upload.
|
||||
@@ -47,9 +54,15 @@ type contractDocument struct {
|
||||
Product string `json:"product,omitempty"`
|
||||
ManagedService string `json:"managed_service,omitempty"`
|
||||
TenantSpecific bool `json:"tenant_specific"`
|
||||
// The AVV only. FilledFrom: "profile" (filled from the workspace's
|
||||
// details) or "staff" (uploaded). Missing: why the master is still blank,
|
||||
// as avvMissing* codes, so the portal can say what to complete.
|
||||
FilledFrom string `json:"filled_from,omitempty"`
|
||||
Missing []string `json:"missing,omitempty"`
|
||||
|
||||
master *contractdocs.Doc
|
||||
own *store.ContractDocument
|
||||
filled []byte // the master filled from the profile
|
||||
}
|
||||
|
||||
var contractKindOrder = map[string]int{contractdocs.KindAGB: 0, contractdocs.KindAVV: 1, contractdocs.KindTOM: 2, contractdocs.KindLB: 3}
|
||||
@@ -108,10 +121,14 @@ func (s *Server) tenantContractDocuments(ctx context.Context, t *store.Tenant) (
|
||||
if d.Kind == contractdocs.KindAVV && own != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, contractDocument{
|
||||
doc := contractDocument{
|
||||
ID: d.ID, Kind: d.Kind, Title: d.Title, Version: d.Version, Date: d.Date, SHA256: d.SHA256,
|
||||
Product: d.Product, ManagedService: d.ManagedService, master: d,
|
||||
})
|
||||
}
|
||||
if d.Kind == contractdocs.KindAVV {
|
||||
s.fillAVV(ctx, t, &doc)
|
||||
}
|
||||
out = append(out, doc)
|
||||
}
|
||||
if own != nil {
|
||||
// The Stand of the master it was filled from; without that master in
|
||||
@@ -122,7 +139,7 @@ func (s *Server) tenantContractDocuments(ctx context.Context, t *store.Tenant) (
|
||||
}
|
||||
out = append(out, contractDocument{
|
||||
ID: contractdocs.KindAVV, Kind: contractdocs.KindAVV, Title: contractdocs.Title(contractdocs.KindAVV),
|
||||
Version: own.Version, Date: date, SHA256: own.SHA256, TenantSpecific: true, own: own,
|
||||
Version: own.Version, Date: date, SHA256: own.SHA256, TenantSpecific: true, FilledFrom: "staff", own: own,
|
||||
})
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b contractDocument) int { return contractKindOrder[a.Kind] - contractKindOrder[b.Kind] })
|
||||
@@ -169,6 +186,25 @@ func (s *Server) tenantContractDocumentPDF(w http.ResponseWriter, r *http.Reques
|
||||
s.serveVerified(ctx, w, d.own.ObjectKey, d.own.SHA256, "application/pdf", "Breakpilot_Auftragsverarbeitungsvertrag_"+d.own.Version+".pdf")
|
||||
return
|
||||
}
|
||||
if d.filled != nil {
|
||||
// The filled AVV is the master plus an update: the master's pin
|
||||
// holds for its first bytes.
|
||||
if contractdocs.Sum(d.master.PDF) != d.master.SHA256 || !bytes.HasPrefix(d.filled, d.master.PDF) {
|
||||
s.Log.Error("filled AVV does not start with its pinned master", "tenant_id", t.ID, "version", d.Version)
|
||||
writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served")
|
||||
return
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "application/pdf")
|
||||
h.Set("Content-Disposition", inlineDisposition("Breakpilot_Auftragsverarbeitungsvertrag_"+d.Version+".pdf"))
|
||||
h.Set("Content-Length", strconv.Itoa(len(d.filled)))
|
||||
h.Set("ETag", `"`+d.SHA256+`"`)
|
||||
h.Set("X-Content-SHA256", d.SHA256)
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "private, no-cache")
|
||||
_, _ = w.Write(d.filled)
|
||||
return
|
||||
}
|
||||
if contractdocs.Sum(d.master.PDF) != d.master.SHA256 {
|
||||
s.Log.Error("contract document does not match its pin", "document", d.ID, "version", d.Version)
|
||||
writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served")
|
||||
@@ -219,35 +255,126 @@ func (s *Server) adminAVVValues(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var v avvValues
|
||||
profile, err := s.companyProfileAnswers(ctx, t.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "the company profile could not be read")
|
||||
return
|
||||
}
|
||||
v.Name = companyWithLegalForm(profile["companyName"], profile["legalForm"])
|
||||
v.Anschrift = joinNonEmpty(", ",
|
||||
profile["headquartersStreet"],
|
||||
joinNonEmpty(" ", profile["headquartersZip"], profile["headquartersCity"]),
|
||||
profileCountry(profile["headquartersCountry"], profile["headquartersCountryOther"]))
|
||||
v.Weisung = "Geschäftsleitung"
|
||||
if mail := profile["legalContactEmail"]; mail != "" {
|
||||
v.Weisung += " (" + mail + ")"
|
||||
}
|
||||
names, err := s.managementNames(ctx, t)
|
||||
v, _, err := s.avvDetails(ctx, t)
|
||||
if errors.Is(err, errRoleDatasetUnreadable) {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "the role dataset could not be read")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errProfileUnreadable) {
|
||||
writeError(w, http.StatusInternalServerError, "internal", "the company profile could not be read")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeKeycloakError(w, t.ID, "list members for the AVV", err)
|
||||
return
|
||||
}
|
||||
v.Vertreten = germanList(names)
|
||||
v.ValuesSHA256 = avvValuesDigest(v)
|
||||
writeJSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
var errProfileUnreadable = errors.New("company profile unreadable")
|
||||
|
||||
// Why a workspace's AVV is still the blank master.
|
||||
const (
|
||||
avvMissingProfile = "profile" // the company profile is not submitted
|
||||
avvMissingName = "company_name" // no company name in it
|
||||
avvMissingAddress = "address" // street, postcode or city missing
|
||||
avvMissingManagement = "management" // nobody named as Geschäftsleitung (Verantwortliche)
|
||||
avvMissingManual = "manual" // the details do not fit the form; staff fill it in
|
||||
)
|
||||
|
||||
// avvDetails are the customer's details for the AVV, from the company
|
||||
// profile and the role dataset, and what is missing for an automatic fill.
|
||||
// The Weisung line names the function, Geschäftsleitung (owner 19.11.2026).
|
||||
func (s *Server) avvDetails(ctx context.Context, t *store.Tenant) (avvValues, []string, error) {
|
||||
var v avvValues
|
||||
var missing []string
|
||||
profile, submitted, err := s.companyProfile(ctx, t.ID)
|
||||
if err != nil {
|
||||
return v, nil, errProfileUnreadable
|
||||
}
|
||||
if !submitted {
|
||||
missing = append(missing, avvMissingProfile)
|
||||
}
|
||||
v.Name = companyWithLegalForm(profile["companyName"], profile["legalForm"])
|
||||
if v.Name == "" {
|
||||
missing = append(missing, avvMissingName)
|
||||
}
|
||||
v.Anschrift = joinNonEmpty(", ",
|
||||
profile["headquartersStreet"],
|
||||
joinNonEmpty(" ", profile["headquartersZip"], profile["headquartersCity"]),
|
||||
profileCountry(profile["headquartersCountry"], profile["headquartersCountryOther"]))
|
||||
if profile["headquartersStreet"] == "" || profile["headquartersZip"] == "" || profile["headquartersCity"] == "" {
|
||||
missing = append(missing, avvMissingAddress)
|
||||
}
|
||||
v.Weisung = "Geschäftsleitung"
|
||||
names, err := s.managementNames(ctx, t)
|
||||
if err != nil {
|
||||
return v, nil, err
|
||||
}
|
||||
v.Vertreten = germanList(names)
|
||||
if v.Vertreten == "" {
|
||||
missing = append(missing, avvMissingManagement)
|
||||
}
|
||||
v.ValuesSHA256 = avvValuesDigest(v)
|
||||
return v, missing, nil
|
||||
}
|
||||
|
||||
// fillAVV makes doc, the AVV master's entry, the master filled with the
|
||||
// workspace's details when they are complete, or names what is missing. A
|
||||
// failure to read the details leaves the plain master: the overview still
|
||||
// lists everything else. The details are the customer's data: never logged.
|
||||
func (s *Server) fillAVV(ctx context.Context, t *store.Tenant, doc *contractDocument) {
|
||||
v, missing, err := s.avvDetails(ctx, t)
|
||||
if err != nil {
|
||||
s.Log.Warn("AVV details unreadable; listing the blank master", "tenant_id", t.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
doc.Missing = missing
|
||||
return
|
||||
}
|
||||
pdf, err := filledAVV(doc.master, v)
|
||||
if err != nil {
|
||||
// Not a value: only which rule refused it (too long, character set).
|
||||
s.Log.Warn("AVV not filled automatically; staff must fill it", "tenant_id", t.ID, "version", doc.Version, "reason", err)
|
||||
doc.Missing = []string{avvMissingManual}
|
||||
return
|
||||
}
|
||||
doc.filled = pdf
|
||||
doc.SHA256 = contractdocs.Sum(pdf)
|
||||
doc.TenantSpecific = true
|
||||
doc.FilledFrom = "profile"
|
||||
}
|
||||
|
||||
// filledAVVs caches filled AVVs by master and details digest: the fill is
|
||||
// deterministic, so a hit is the same bytes.
|
||||
var filledAVVs = struct {
|
||||
sync.Mutex
|
||||
m map[string][]byte
|
||||
}{m: map[string][]byte{}}
|
||||
|
||||
func filledAVV(master *contractdocs.Doc, v avvValues) ([]byte, error) {
|
||||
key := master.SHA256 + "/" + v.ValuesSHA256
|
||||
filledAVVs.Lock()
|
||||
pdf, ok := filledAVVs.m[key]
|
||||
filledAVVs.Unlock()
|
||||
if ok {
|
||||
return pdf, nil
|
||||
}
|
||||
pdf, err := avvfill.Fill(master.PDF, avvfill.Values{Name: v.Name, Anschrift: v.Anschrift, Vertreten: v.Vertreten, Weisung: v.Weisung})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filledAVVs.Lock()
|
||||
if len(filledAVVs.m) >= 256 {
|
||||
clear(filledAVVs.m)
|
||||
}
|
||||
filledAVVs.m[key] = pdf
|
||||
filledAVVs.Unlock()
|
||||
return pdf, nil
|
||||
}
|
||||
|
||||
func avvValuesDigest(v avvValues) string {
|
||||
b, _ := json.Marshal(struct {
|
||||
Name string `json:"ag_name"`
|
||||
@@ -259,24 +386,26 @@ func avvValuesDigest(v avvValues) string {
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// companyProfileAnswers returns the text answers of the profile's
|
||||
// company_profile section, trimmed; empty when there is no profile.
|
||||
func (s *Server) companyProfileAnswers(ctx context.Context, tenantID string) (map[string]string, error) {
|
||||
// companyProfile returns the text answers of the profile's company_profile
|
||||
// section, trimmed (empty when there is no profile), and whether the profile
|
||||
// is submitted.
|
||||
func (s *Server) companyProfile(ctx context.Context, tenantID string) (map[string]string, bool, error) {
|
||||
out := map[string]string{}
|
||||
p, err := s.Store.GetCompanyProfile(ctx, tenantID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return out, nil
|
||||
return out, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
submitted := p.Status == store.ProfileSubmitted
|
||||
var doc struct {
|
||||
Sections struct {
|
||||
CompanyProfile map[string]json.RawMessage `json:"company_profile"`
|
||||
} `json:"sections"`
|
||||
}
|
||||
if json.Unmarshal(p.Data, &doc) != nil {
|
||||
return out, nil
|
||||
return out, submitted, nil
|
||||
}
|
||||
for k, raw := range doc.Sections.CompanyProfile {
|
||||
var str string
|
||||
@@ -284,7 +413,7 @@ func (s *Server) companyProfileAnswers(ctx context.Context, tenantID string) (ma
|
||||
out[k] = strings.TrimSpace(str)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
return out, submitted, nil
|
||||
}
|
||||
|
||||
// legalFormNames are the company profile's legal forms (portal schema
|
||||
@@ -306,9 +435,10 @@ func companyWithLegalForm(name, form string) string {
|
||||
if name == "" || len(names) == 0 {
|
||||
return name
|
||||
}
|
||||
lower := strings.ToLower(name)
|
||||
// Spaces do not count: "UG(haftungsbeschränkt)" is the UG already.
|
||||
squash := func(x string) string { return strings.ToLower(strings.ReplaceAll(x, " ", "")) }
|
||||
for _, n := range names {
|
||||
if strings.HasSuffix(lower, strings.ToLower(n)) {
|
||||
if strings.HasSuffix(squash(name), squash(n)) {
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,7 +490,8 @@ func TestAdminAVVValues(t *testing.T) {
|
||||
Name: "Muster Maschinenbau GmbH", Anschrift: "Musterstraße 1, 12345 Musterstadt",
|
||||
// u-admin has no name: the e-mail, as the portal shows it; u-gone is no member any more.
|
||||
Vertreten: "Erika Mustermann, Max Muster und admin@acme.test",
|
||||
Weisung: "Geschäftsleitung (recht@muster.test)",
|
||||
// The function only (owner 19.11.2026): an e-mail would not fit the line.
|
||||
Weisung: "Geschäftsleitung",
|
||||
}
|
||||
want.ValuesSHA256 = avvValuesDigest(want)
|
||||
if code != 200 || v != want {
|
||||
@@ -588,6 +589,8 @@ func TestCompanyWithLegalForm(t *testing.T) {
|
||||
{"Muster Maschinenbau gmbh", "gmbh", "Muster Maschinenbau gmbh"},
|
||||
{"Muster", "ug", "Muster UG (haftungsbeschränkt)"},
|
||||
{"Muster UG (haftungsbeschränkt)", "ug", "Muster UG (haftungsbeschränkt)"},
|
||||
{"Muster UG(haftungsbeschränkt)", "ug", "Muster UG(haftungsbeschränkt)"}, // spaces do not count
|
||||
{"Muster GmbH & Co.KG", "gmbh_co_kg", "Muster GmbH & Co.KG"},
|
||||
{"Muster UG", "ug", "Muster UG"},
|
||||
{"Muster", "ag", "Muster AG"},
|
||||
{"Muster", "gmbh_co_kg", "Muster GmbH & Co. KG"},
|
||||
@@ -651,3 +654,93 @@ func TestPurgeRemovesContractDocuments(t *testing.T) {
|
||||
t.Errorf("rows left: %d", len(rows))
|
||||
}
|
||||
}
|
||||
|
||||
func submitProfile(t *testing.T, f *storeFixture) {
|
||||
t.Helper()
|
||||
cur, err := f.s.Store.GetCompanyProfile(context.Background(), f.tenant.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.s.Store.SubmitCompanyProfile(context.Background(), f.tenant.ID, cur.Revision, "it@muster.test", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func avvEntry(t *testing.T, f *storeFixture) contractDocument {
|
||||
t.Helper()
|
||||
v, _ := f.contracts(t)
|
||||
for _, d := range v.Documents {
|
||||
if d.Kind == contractdocs.KindAVV {
|
||||
return d
|
||||
}
|
||||
}
|
||||
t.Fatal("no AVV listed")
|
||||
return contractDocument{}
|
||||
}
|
||||
|
||||
// The AVV fills itself from the submitted profile and the named
|
||||
// Geschäftsleitung; until then the master is listed with what is missing.
|
||||
func TestContractDocuments_avvFilledFromProfile(t *testing.T) {
|
||||
f := newContractFixture(t, true)
|
||||
var logs bytes.Buffer
|
||||
f.s.Log = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
master := contractdocs.Default().Get("avv")
|
||||
|
||||
// Nothing yet: the master, and everything is missing.
|
||||
a := avvEntry(t, f)
|
||||
if a.TenantSpecific || a.FilledFrom != "" || a.SHA256 != master.SHA256 || strings.Join(a.Missing, ",") != "profile,company_name,address,management" {
|
||||
t.Fatalf("empty: %+v", a)
|
||||
}
|
||||
if code, _, body := f.contractPDF(t, "avv.pdf"); code != 200 || !bytes.Equal(body, master.PDF) {
|
||||
t.Fatalf("blank pdf: %d", code)
|
||||
}
|
||||
|
||||
// A draft profile with all details and a Geschäftsleitung: only the submit is missing.
|
||||
saveProfile(t, f, `{"companyName":"Muster Maschinenbau","legalForm":"gmbh","headquartersStreet":"Musterstraße 1",
|
||||
"headquartersZip":"12345","headquartersCity":"Musterstadt","headquartersCountry":"DE"}`)
|
||||
f.kc.Members["acme"] = append(f.kc.Members["acme"],
|
||||
keycloak.OrgMember{UserID: "u-ceo", Email: "ceo@muster.test", FirstName: "Erika", LastName: "Mustermann", Enabled: true})
|
||||
saveRoles(t, f, `{"assignments":[{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`)
|
||||
if a := avvEntry(t, f); a.TenantSpecific || strings.Join(a.Missing, ",") != "profile" {
|
||||
t.Fatalf("draft: %+v", a)
|
||||
}
|
||||
|
||||
// Submitted: the filled AVV, the master plus its update.
|
||||
submitProfile(t, f)
|
||||
a = avvEntry(t, f)
|
||||
if !a.TenantSpecific || a.FilledFrom != "profile" || len(a.Missing) != 0 || a.Version != master.Version || a.Date != master.Date || a.SHA256 == master.SHA256 {
|
||||
t.Fatalf("filled: %+v", a)
|
||||
}
|
||||
code, hdr, body := f.contractPDF(t, "avv.pdf")
|
||||
if code != 200 || !bytes.HasPrefix(body, master.PDF) || len(body) <= len(master.PDF) || contractdocs.Sum(body) != a.SHA256 ||
|
||||
hdr.Get("ETag") != `"`+a.SHA256+`"` || !strings.Contains(hdr.Get("Content-Disposition"), "Breakpilot_Auftragsverarbeitungsvertrag_1.0.0.pdf") {
|
||||
t.Fatalf("filled pdf: %d %v", code, hdr)
|
||||
}
|
||||
// The same details give the same document.
|
||||
if _, _, again := f.contractPDF(t, "avv.pdf"); !bytes.Equal(again, body) {
|
||||
t.Error("not stable")
|
||||
}
|
||||
|
||||
// Details that do not fit the form: the master, staff fill it in.
|
||||
saveProfile(t, f, `{"companyName":"`+strings.Repeat("Muster Maschinenbau ", 4)+`","legalForm":"gmbh","headquartersStreet":"Musterstraße 1",
|
||||
"headquartersZip":"12345","headquartersCity":"Musterstadt"}`)
|
||||
submitProfile(t, f)
|
||||
if a := avvEntry(t, f); a.TenantSpecific || strings.Join(a.Missing, ",") != "manual" {
|
||||
t.Fatalf("too long: %+v", a)
|
||||
}
|
||||
|
||||
// An uploaded AVV wins over the automatic one.
|
||||
if rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", []byte("%PDF-1.7 synthetic"), avvHeaders("1.0.0", strings.Repeat("d", 64))); rr.Code != 201 {
|
||||
t.Fatalf("upload: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if a := avvEntry(t, f); !a.TenantSpecific || a.FilledFrom != "staff" || len(a.Missing) != 0 {
|
||||
t.Fatalf("staff: %+v", a)
|
||||
}
|
||||
|
||||
// The customer's details never reach the log.
|
||||
for _, v := range []string{"Muster Maschinenbau", "Musterstraße", "Erika"} {
|
||||
if strings.Contains(logs.String(), v) {
|
||||
t.Errorf("log carries %q", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -788,7 +788,8 @@ paths:
|
||||
Leistungsbeschreibungen that apply (the platform's always; a product's
|
||||
while the tenant holds it booked, on trial or as a preview grant; a
|
||||
managed service's while the tenant has one). A filled AVV of the
|
||||
tenant replaces the master (tenant_specific). Empty while the release
|
||||
tenant replaces the master (tenant_specific): the one staff uploaded,
|
||||
else the master filled from the submitted company profile. Empty while the release
|
||||
gate CONTRACT_DOCUMENTS is off.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
@@ -2702,6 +2703,23 @@ components:
|
||||
product: { type: string, description: The product a Leistungsbeschreibung belongs to. }
|
||||
managed_service: { type: string, description: The managed service kind a Leistungsbeschreibung belongs to. }
|
||||
tenant_specific: { type: boolean, description: The tenant's own filled copy (AVV). }
|
||||
filled_from:
|
||||
type: string
|
||||
enum: [profile, staff]
|
||||
description: >-
|
||||
AVV only, when tenant_specific: profile = the master filled with
|
||||
the submitted company profile and the named Geschäftsleitung
|
||||
(the master's bytes plus one incremental update); staff = the copy
|
||||
staff uploaded, which takes precedence.
|
||||
missing:
|
||||
type: array
|
||||
items: { type: string, enum: [profile, company_name, address, management, manual] }
|
||||
description: >-
|
||||
AVV only, when it is still the blank master: what keeps it from
|
||||
being filled. profile = company profile not submitted;
|
||||
company_name / address = not in the profile; management = nobody
|
||||
named as Geschäftsleitung; manual = the details do not fit the
|
||||
form, staff fill it in.
|
||||
|
||||
Error:
|
||||
type: object
|
||||
|
||||
Reference in new issue
Block a user