| new file mode 100644 |
| index 000000000..af1bddd45 |
| --- /dev/null |
| +++ b/internal/console/legal_store.go |
| @@ -0,0 +1,344 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "errors" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The legal documents, the letterhead and the DPA acceptances (DPA and |
| +// retention spec §3.1, §3.3, §3.6), kept here so the feature is one file to |
| +// read. Rows are append-only; dpa_acceptances.ended_at is the only column |
| +// ever updated. |
| + |
| +var ( |
| + // ErrLegalVersionExists: a document of this kind and version is already |
| + // published. |
| + ErrLegalVersionExists = errors.New("console: that version of this legal document is already published") |
| + // ErrDPAAlreadyInForce: the account already has a live acceptance. |
| + ErrDPAAlreadyInForce = errors.New("console: this account already has a DPA in force") |
| +) |
| + |
| +// LegalDocument is one published version of a legal document. |
| +type LegalDocument struct { |
| + ID int64 |
| + Kind string // "dpa", "terms" or "privacy" |
| + Version string |
| + URL string |
| + BodyURL string // dpa only |
| + Body string // dpa only |
| + SHA256 string |
| + Summary string |
| + PublishedAt time.Time |
| + EffectiveAt *time.Time // nil until known |
| + NeedsNotice bool |
| + PublishedBy string |
| +} |
| + |
| +// Letterhead is the operator's headed paper; the newest row is current. |
| +type Letterhead struct { |
| + ID int64 |
| + Logo []byte |
| + LogoType string |
| + Entity string |
| + RegisteredOffice string |
| + CompanyNumber string |
| + VATNumber string |
| + Signatory string |
| + PrivacyAddress string |
| + Footer string |
| + CreatedBy string |
| + CreatedAt time.Time |
| +} |
| + |
| +// DPAAcceptance is an account owner's acceptance of a DPA version. |
| +type DPAAcceptance struct { |
| + ID, AccountID, DocumentID, LetterheadID int64 |
| + LegalName, Address, Country string |
| + SignerName, SignerRole string |
| + AcceptedBy, AcceptedIP string |
| + AcceptedAt time.Time |
| + EndedAt *time.Time |
| +} |
| + |
| +// DPAAcceptanceRow is a live acceptance with its account's identity, for the |
| +// operator list. |
| +type DPAAcceptanceRow struct { |
| + DPAAcceptance |
| + AccountSqid, AccountName string |
| +} |
| + |
| +func (s *Store) migrateLegal() error { |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS legal_documents ( |
| + id INTEGER PRIMARY KEY, |
| + kind TEXT NOT NULL, |
| + version TEXT NOT NULL, |
| + url TEXT NOT NULL, |
| + body_url TEXT, |
| + body TEXT, |
| + sha256 TEXT NOT NULL, |
| + summary TEXT NOT NULL, |
| + published_at INTEGER NOT NULL, |
| + effective_at INTEGER, |
| + needs_notice INTEGER NOT NULL, |
| + published_by TEXT NOT NULL, |
| + UNIQUE(kind, version) |
| +); |
| +CREATE TABLE IF NOT EXISTS letterhead ( |
| + id INTEGER PRIMARY KEY, |
| + logo BLOB, |
| + logo_type TEXT, |
| + entity TEXT NOT NULL, |
| + registered_office TEXT NOT NULL, |
| + company_number TEXT NOT NULL, |
| + vat_number TEXT, |
| + signatory TEXT NOT NULL, |
| + privacy_address TEXT NOT NULL, |
| + footer TEXT, |
| + created_at INTEGER NOT NULL, |
| + created_by TEXT NOT NULL |
| +); |
| +CREATE TABLE IF NOT EXISTS dpa_acceptances ( |
| + id INTEGER PRIMARY KEY, |
| + account_id INTEGER NOT NULL, |
| + document_id INTEGER NOT NULL REFERENCES legal_documents(id), |
| + letterhead_id INTEGER NOT NULL REFERENCES letterhead(id), |
| + legal_name TEXT NOT NULL, |
| + address TEXT NOT NULL, |
| + country TEXT NOT NULL, |
| + signer_name TEXT NOT NULL, |
| + signer_role TEXT NOT NULL, |
| + accepted_by TEXT NOT NULL, |
| + accepted_ip TEXT NOT NULL, |
| + accepted_at INTEGER NOT NULL, |
| + ended_at INTEGER |
| +); |
| +CREATE UNIQUE INDEX IF NOT EXISTS dpa_live ON dpa_acceptances(account_id) WHERE ended_at IS NULL;`) |
| + return err |
| +} |
| + |
| +func isUniqueViolation(err error) bool { |
| + return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") |
| +} |
| + |
| +func nullTime(t *time.Time) any { |
| + if t == nil { |
| + return nil |
| + } |
| + return t.Unix() |
| +} |
| + |
| +func timePtr(n sql.NullInt64) *time.Time { |
| + if !n.Valid { |
| + return nil |
| + } |
| + t := time.Unix(n.Int64, 0).UTC() |
| + return &t |
| +} |
| + |
| +// PublishLegalDocument appends a document and returns its id, or |
| +// ErrLegalVersionExists when the kind and version are already there. |
| +func (s *Store) PublishLegalDocument(d LegalDocument) (int64, error) { |
| + res, err := s.db.Exec(`INSERT INTO legal_documents (kind, version, url, body_url, body, sha256, summary, |
| + published_at, effective_at, needs_notice, published_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + d.Kind, d.Version, d.URL, d.BodyURL, d.Body, d.SHA256, d.Summary, |
| + d.PublishedAt.Unix(), nullTime(d.EffectiveAt), d.NeedsNotice, d.PublishedBy) |
| + if err != nil { |
| + if isUniqueViolation(err) { |
| + return 0, ErrLegalVersionExists |
| + } |
| + return 0, err |
| + } |
| + return res.LastInsertId() |
| +} |
| + |
| +const legalDocumentCols = `id, kind, version, url, COALESCE(body_url, ''), COALESCE(body, ''), sha256, summary, |
| + published_at, effective_at, needs_notice, published_by` |
| + |
| +type rowScanner interface{ Scan(dest ...any) error } |
| + |
| +func scanLegalDocument(r rowScanner) (LegalDocument, error) { |
| + var d LegalDocument |
| + var pub int64 |
| + var eff sql.NullInt64 |
| + if err := r.Scan(&d.ID, &d.Kind, &d.Version, &d.URL, &d.BodyURL, &d.Body, &d.SHA256, &d.Summary, |
| + &pub, &eff, &d.NeedsNotice, &d.PublishedBy); err != nil { |
| + return d, err |
| + } |
| + d.PublishedAt = time.Unix(pub, 0).UTC() |
| + d.EffectiveAt = timePtr(eff) |
| + return d, nil |
| +} |
| + |
| +// LegalDocuments is every document of the kind, newest first. |
| +func (s *Store) LegalDocuments(kind string) ([]LegalDocument, error) { |
| + rows, err := s.db.Query(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ? |
| + ORDER BY published_at DESC, id DESC`, kind) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []LegalDocument |
| + for rows.Next() { |
| + d, err := scanLegalDocument(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, d) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// NewestLegalDocument is the latest published document of the kind, or nil, |
| +// nil when there is none. |
| +func (s *Store) NewestLegalDocument(kind string) (*LegalDocument, error) { |
| + d, err := scanLegalDocument(s.db.QueryRow(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE kind = ? |
| + ORDER BY published_at DESC, id DESC LIMIT 1`, kind)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &d, nil |
| +} |
| + |
| +// LegalDocument is the document with this id, or nil, nil. |
| +func (s *Store) LegalDocument(id int64) (*LegalDocument, error) { |
| + d, err := scanLegalDocument(s.db.QueryRow(`SELECT `+legalDocumentCols+` FROM legal_documents WHERE id = ?`, id)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &d, nil |
| +} |
| + |
| +// SetLetterhead appends a letterhead, which becomes the current one. |
| +func (s *Store) SetLetterhead(l Letterhead) (int64, error) { |
| + var logo any |
| + if len(l.Logo) > 0 { |
| + logo = l.Logo |
| + } |
| + res, err := s.db.Exec(`INSERT INTO letterhead (logo, logo_type, entity, registered_office, company_number, |
| + vat_number, signatory, privacy_address, footer, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + logo, l.LogoType, l.Entity, l.RegisteredOffice, l.CompanyNumber, l.VATNumber, l.Signatory, |
| + l.PrivacyAddress, l.Footer, l.CreatedAt.Unix(), l.CreatedBy) |
| + if err != nil { |
| + return 0, err |
| + } |
| + return res.LastInsertId() |
| +} |
| + |
| +const letterheadCols = `id, logo, COALESCE(logo_type, ''), entity, registered_office, company_number, |
| + COALESCE(vat_number, ''), signatory, privacy_address, COALESCE(footer, ''), created_at, created_by` |
| + |
| +func scanLetterhead(r rowScanner) (*Letterhead, error) { |
| + var l Letterhead |
| + var created int64 |
| + if err := r.Scan(&l.ID, &l.Logo, &l.LogoType, &l.Entity, &l.RegisteredOffice, &l.CompanyNumber, |
| + &l.VATNumber, &l.Signatory, &l.PrivacyAddress, &l.Footer, &created, &l.CreatedBy); err != nil { |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + return nil, err |
| + } |
| + l.CreatedAt = time.Unix(created, 0).UTC() |
| + return &l, nil |
| +} |
| + |
| +// CurrentLetterhead is the newest letterhead, or nil, nil when none is set. |
| +func (s *Store) CurrentLetterhead() (*Letterhead, error) { |
| + return scanLetterhead(s.db.QueryRow(`SELECT ` + letterheadCols + ` FROM letterhead ORDER BY id DESC LIMIT 1`)) |
| +} |
| + |
| +// LetterheadByID is the letterhead with this id, or nil, nil. |
| +func (s *Store) LetterheadByID(id int64) (*Letterhead, error) { |
| + return scanLetterhead(s.db.QueryRow(`SELECT `+letterheadCols+` FROM letterhead WHERE id = ?`, id)) |
| +} |
| + |
| +// AcceptDPA records an acceptance, or returns ErrDPAAlreadyInForce when the |
| +// account already has a live one. |
| +func (s *Store) AcceptDPA(a DPAAcceptance) (int64, error) { |
| + res, err := s.db.Exec(`INSERT INTO dpa_acceptances (account_id, document_id, letterhead_id, legal_name, address, |
| + country, signer_name, signer_role, accepted_by, accepted_ip, accepted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + a.AccountID, a.DocumentID, a.LetterheadID, a.LegalName, a.Address, a.Country, a.SignerName, |
| + a.SignerRole, a.AcceptedBy, a.AcceptedIP, a.AcceptedAt.Unix()) |
| + if err != nil { |
| + if isUniqueViolation(err) { |
| + return 0, ErrDPAAlreadyInForce |
| + } |
| + return 0, err |
| + } |
| + return res.LastInsertId() |
| +} |
| + |
| +const dpaCols = `a.id, a.account_id, a.document_id, a.letterhead_id, a.legal_name, a.address, a.country, |
| + a.signer_name, a.signer_role, a.accepted_by, a.accepted_ip, a.accepted_at, a.ended_at` |
| + |
| +func scanDPA(r rowScanner, extra ...any) (DPAAcceptance, error) { |
| + var a DPAAcceptance |
| + var at int64 |
| + var ended sql.NullInt64 |
| + dest := append([]any{&a.ID, &a.AccountID, &a.DocumentID, &a.LetterheadID, &a.LegalName, &a.Address, |
| + &a.Country, &a.SignerName, &a.SignerRole, &a.AcceptedBy, &a.AcceptedIP, &at, &ended}, extra...) |
| + if err := r.Scan(dest...); err != nil { |
| + return a, err |
| + } |
| + a.AcceptedAt = time.Unix(at, 0).UTC() |
| + a.EndedAt = timePtr(ended) |
| + return a, nil |
| +} |
| + |
| +// LiveDPA is the account's acceptance still in force, or nil, nil. |
| +func (s *Store) LiveDPA(accountID int64) (*DPAAcceptance, error) { |
| + a, err := scanDPA(s.db.QueryRow(`SELECT `+dpaCols+` FROM dpa_acceptances a |
| + WHERE a.account_id = ? AND a.ended_at IS NULL`, accountID)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &a, nil |
| +} |
| + |
| +// LiveDPAs is every acceptance in force, newest first, with its account. |
| +func (s *Store) LiveDPAs() ([]DPAAcceptanceRow, error) { |
| + rows, err := s.db.Query(`SELECT ` + dpaCols + `, COALESCE(c.sqid, ''), COALESCE(c.name, '') |
| + FROM dpa_acceptances a LEFT JOIN accounts c ON c.id = a.account_id |
| + WHERE a.ended_at IS NULL ORDER BY a.accepted_at DESC, a.id DESC`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []DPAAcceptanceRow |
| + for rows.Next() { |
| + var r DPAAcceptanceRow |
| + a, err := scanDPA(rows, &r.AccountSqid, &r.AccountName) |
| + if err != nil { |
| + return nil, err |
| + } |
| + r.DPAAcceptance = a |
| + out = append(out, r) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// EndDPA ends the account's live acceptance at `at`; none live is not an |
| +// error. |
| +func (s *Store) EndDPA(accountID int64, at time.Time) error { |
| + return endDPA(s.db, accountID, at) |
| +} |
| + |
| +// endDPA is EndDPA on a db or a transaction, so DeleteAccount can end the |
| +// acceptance in the transaction that removes the account. |
| +func endDPA(x interface { |
| + Exec(string, ...any) (sql.Result, error) |
| +}, accountID int64, at time.Time) error { |
| + _, err := x.Exec(`UPDATE dpa_acceptances SET ended_at = ? WHERE account_id = ? AND ended_at IS NULL`, |
| + at.Unix(), accountID) |
| + return err |
| +} |