documents

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Document generation

fyt documents generate 2026-09 --types=detailed,summary -i work.fyt -i array.json -i list.yaml reads inputs in the supplied order. Each file produces a v1alpha1.TimeEntryList for subsequent processing, whether it contains FYT records, an API array, or an API list. After successful collection, GenerateCommand.Run validates the entries, applies processing.duplicatePolicy from the application configuration and checks the remaining entries for overlaps.

Use --strict to require exactly one document in each JSON or YAML input. Extra documents and invalid trailing content fail before report generation. The option defaults to off. It adds a validation pass over the already-read bytes. Schema validation applies in both modes. Plain-text FYT input uses the same parser in both modes.

Supply the reporting month in YYYY-MM format. When the positional argument is omitted, FYT_DOCUMENTS_GENERATE_MONTH can supply it. Cobra validates the month and prepares the reporting period before configuration and inputs are read.

Select document types with -t or --types. The default is all. Pass --types=detailed,summary to select multiple types in one flag or repeat the flag, for example -t detailed -t summary. Allowed values are all, detailed, summary and invoice. Including all selects all three models. The command validates shared configuration settings for every selection. Detailed and summary require valid report settings, and invoice requires valid invoice settings. The config file is decoded strictly for every selection.

When the selection includes invoice, supply --invoice-number and --invoice-date (YYYY-MM-DD), including for an empty period. Use -D or --invoice-due-date to set an optional due date in YYYY-MM-DD format. FYT_DOCS_GEN_INVOICE_DUE_DATE can supply the value when the flag is omitted. The remaining invoice settings come from the application configuration and any --invoice-config overrides. The reports' member name comes from the application configuration.

The command prepares GenerateCommand.CalendarParts after the entire timesheet passes the overlap check. It clips entries to the reporting period, splits them by local day and retains their original sources. The command builds the selected detailed, summary and invoice models from these same calendar parts.

The default --format=text writes the selected documents to stdout in detailed, summary, invoice order, with a blank line between documents. Logs and diagnostics go to stderr. Text output shows detailed intervals, weekly summary totals and invoice amounts. A month without matching records shows an explicit empty message in each document. Summary still lists every week intersecting the period. An invoice for that month includes any configured extra charges and omits the hourly service line.

Invoice configuration

In the base configuration, an omitted or null invoice.customer uses the default customer ACME Inc. A customer object in the base requires a nonblank name in the effective invoice settings.

Both parties accept optional address, city, phone, email and multiline details fields. Supply invoice.supplier.options as a mapping of string keys to string values. The built-in text and PDF outputs show the customer_id value as Customer ID when supplied. Custom PDF templates receive the complete mapping.

apiVersion: fyt.queueb.org/v1alpha1
kind: Config
invoice:
  supplier:
    name: Example Studio
    address: 1 Main Street
    city: Example City
    phone: "+1 202 555 0100"
    email: supplier@example.com
    options:
      customer_id: "13"
  customer:
    name: Example Company
    address: 2 Main Street
    city: Sample City
    phone: "+1 202 555 0101"
    email: customer@example.com
  additionalLines:
    - description: Software license
      quantity: "1"
      unitPrice: "110.00"

invoice.additionalLines is an optional list in display order, after the hourly service line when present. Each line requires a nonblank description, a positive decimal quantity, and a non-negative decimal unit price in the invoice currency. Quote quantities, prices, phone numbers and option values in YAML to preserve their exact text. Each amount is quantity times unit price, rounded half up to invoice.monetaryPrecision. Subtotal sums the rounded amounts and any percentage tax applies to that subtotal.

In the base configuration, an omitted or null invoice.currency defaults to USD and an omitted or null invoice.monetaryPrecision defaults to 2. Precision is independent of currency. An explicit 0 produces totals without decimal places. An empty or whitespace-only effective currency blocks generation.

Omitting invoice.tax.type selects None. For Percentage, supply invoice.tax.ratePercent in the base configuration or the per-invoice override. Use an explicit "0" for a zero percentage rate.

Per-invoice overrides

Use --invoice-config PATH to override invoice settings for the current invocation when the selection includes invoice. The file contains one JSON or YAML document with invoice as its sole top-level key. Use the same field names and types as the base invoice settings.

invoice:
  customer:
    email: billing@example.org
  tax:
    type: Percentage
    ratePercent: "0"
  additionalLines:
    - description: One-time software license
      quantity: "1"
      unitPrice: "110.00"

The command loads the base --config with its usual defaults, then applies the supplied fields and validates the result. supplier, customer and tax merge by field. Omitted fields inherit their base values. Each supplied options map and the additionalLines array replaces the corresponding collection in full. Use options: {} or additionalLines: [] to clear one. A supplied empty string or zero reaches validation as given.

Unreadable override files, null, unknown or duplicate keys, and incorrect field types fail generation. Invalid effective invoice settings block the whole selected set, including for an empty month. Set the invoice number, date and optional due date using the existing flags. All documents use the common reporting month.

fyt --config config.yaml docs generate 2026-10 -i work.fyt \
  --invoice-config invoice-2026-10.yaml --invoice-number OPS/2026-10 \
  --invoice-date 2026-11-01 --format=pdf

Environment defaults

Flag Environment variable
--strict FYT_DOCS_GEN_STRICT
--types FYT_DOCS_GEN_TYPES
--format FYT_DOCS_GEN_FORMAT
--output-dir FYT_DOCS_GEN_OUTPUT_DIR
--templates-dir FYT_DOCS_GEN_TEMPLATES_DIR
--overwrite FYT_DOCS_GEN_OVERWRITE
--invoice-config FYT_DOCS_GEN_INVOICE_CONFIG

These names are shown in fyt docs generate --help. Set FYT_DOCS_GEN_TYPES to a comma-separated list, such as detailed,summary. An explicit flag overrides its environment value, including --strict=false when FYT_DOCS_GEN_STRICT=true and --overwrite=false when FYT_DOCS_GEN_OVERWRITE=true. Use --invoice-config= to disable an override supplied by the environment. An unset or empty variable leaves the next source in effect. Invalid strict and overwrite environment values fall back to false.

PDF output

The bundled invoice shows the hourly rate as 35.00 USD/h and additional unit prices as 110.00 USD. For a period without work entries, the hourly rate appears above the charges table or totals.

Install Typst CLI on PATH and make DejaVu Sans available to Typst. The PDF integration was verified with Typst 0.15.1 on Linux. The bundled templates use local resources and can render offline.

fyt docs generate 2026-09 -i work.fyt --format=pdf \
  --invoice-number INV-2026-09 --invoice-date 2026-10-01
fyt docs generate 2026-09 -i work.fyt --format=pdf --types=summary \
  --templates-dir ./my-templates --output-dir ./output

PDFs are saved to ./documents/<MONTH> from the working directory by default. Set documents.outputDirectory in Config to a Go text template for the final directory. It can use .Year (YYYY), .Month (MM), and .YearMonth (YYYY-MM) from the selected reporting month.

documents:
  outputDirectory: './reports/{{ .Year }}/{{ .Month }}'

For 2026-09, this selects ./reports/2026/09. Use './reports/{{ .YearMonth }}' for ./reports/2026-09, or './reports' to write directly to that directory. The default is './documents/{{ .YearMonth }}'.

The template can also read the process environment through .Env. For example, '{{ .Env.FYT_REPORT_ROOT }}/{{ .YearMonth }}' uses the value of FYT_REPORT_ROOT as the report base directory.

FYT_DOCS_GEN_OUTPUT_DIR and --output-dir DIR override Config with literal directories, with the flag taking precedence. Use --output-dir= to select the built-in default explicitly. An unset or empty environment value leaves Config in effect. The command resolves relative paths from the working directory and creates the selected directory if needed.

The filenames are YYYY-MM-detailed.pdf, YYYY-MM-summary.pdf and YYYY-MM-invoice.pdf. The prefix is always the report month.

Only the selected types are rendered and checked for collisions. By default all three types are selected. Before publishing any PDF, the command reports all occupied selected paths. --overwrite permits replacement of the selected PDFs. The base config, invoice override in use, timesheet inputs, and inputs used by any selected template are protected from replacement. Each file is published after its render completes. On failure, the command returns a nonzero status and reports the paths written and still pending for that run on stderr. A previously written PDF remains available if its replacement fails. Publishing without overwrite requires hard-link support in the output filesystem. PDF mode leaves stdout empty.

User templates and JSON

Copy the bundled Typst templates to start a custom bundle. In Config, list bundle directories in preference order. Relative directory paths are resolved from the working directory.

documents:
  templatesDirectories:
    - path: ./templates/team
    - path: ./templates/shared

The command selects the first directory containing a readable regular detailed.typ, summary.typ, or invoice.typ at its root for every selected type. If none qualifies, the command lists the reason for rejecting each directory and exits before writing PDFs. An omitted or empty list selects the bundled templates.

FYT_DOCS_GEN_TEMPLATES_DIR overrides the list with a single directory. --templates-dir DIR takes precedence over the environment. Use --templates-dir= to select the bundled templates explicitly. A whitespace-only override or an unusable override directory fails with a diagnostic for that source.

The selected bundle supplies its own imports and assets. Relative Typst paths and paths beginning with / resolve as they would with that bundle as the Typst project root. Import and compilation failures are reported for the selected bundle. For offline use, install any custom fonts and other dependencies locally before rendering.

Each template reads one JSON object with json(sys.inputs.at("data")). All objects contain schemaVersion (currently 1), kind and period. The period contains month, firstDate, lastDate (inclusive) and timeZone. Optional text fields use an empty string. Durations for display, money and rates are strings. The complete field definitions are in data.go.

Kind Document fields
detailed memberName, totalDuration, and chronological rows. Each row has a document-local id, start, end, ticket, description, duration, and a nullable original interval. Each timestamp has date and time.
summary memberName, totalDuration, and weeks with monday, firstDate, lastDate, duration, and integer seconds for the chart.
invoice number, date, dueDate, supplier, customer, paymentInstructions, hourlyRate, currency, lines, nullable line, subtotal, tax and total. Both parties have name, details, address, city, phone, email and an options dictionary. Each line has description, quantity, unitPrice and amount. Tax contains type (none or percentage), ratePercent and amount.

Use report.lines to render every charge, with the hourly service first when present. It is an empty array when the invoice contains no charges. The legacy report.line field is the hourly service alone and is null when there is no hourly service. A template can look up the customer ID with report.supplier.options.at("customer_id", default: "").

Go calculates the displayed durations, amounts and tax. The templates use these values for display and control layout, including page breaks.

Processing and diagnostics

Inputs are collected through timesheet.FromFiles and stored in GenerateCommand.Timesheet as a *timesheet.Timesheet. See the timesheet input documentation for format selection, API root structures, decoding, and conversion rules.

Timesheet.Lists preserves file and record order and stores the source path once per list in .Meta. Timesheet.Entries() provides all entries sorted by start time, preserving source order for equal start times. Input errors are collected across files, and a failed collection clears the result. Source files are never modified.

Validation checks every entry's required values, interval ordering and whole-second precision, and rebuilds its Ready and Failed conditions from scratch. Run returns field and conversion errors with the source file path and one-based record number. A validation error retains the complete collected timesheet, including green and red entries, for diagnostics and stops the command.

The default policy Merge counts proven duplicates once and retains their source paths and entry numbers in GenerateCommand.ProcessedEntries. With Error, proven duplicates stop processing. Conflicts stop processing in both modes. The command reports the read, merged and accounted counts at info level after successful processing.

Touching bounds are allowed. Positive overlaps and mixed/ambiguous overlaps block both duplicate modes. The latter occur when both the ticket and description match exactly. The diagnostics show both intervals and their source occurrences.

After those checks, the command logs a warning to stderr for each source occurrence whose full duration is strictly less than processing.shortEntryThreshold (default 5m). The warning identifies the source file, one-based entry number, duration and threshold. Set the threshold to 0s to disable these warnings. Short entries retain their exact duration and generation continues. The threshold only applies before calendar selection and splitting, so a shorter calendar part alone does not produce a warning.

Input and validation errors are expanded with timesheet.Diagnostics and logged through alog in stderr, one record per problem. Every record contains the canonical command path, processing stage, source and reason. Available physical line numbers, entry numbers, fields and values are separate log attributes. Empty field values are retained, and alog.Sensitive values keep the logger's masking. For example, two malformed FYT lines produce two records, each with its source path and original physical line number. Unknown coordinates are omitted. Multiple strict decoding violations in one API array entry also produce separate records, each retaining the same source file, decode stage and entry number. Strict TimeEntryList violations are reported once each, without additional errors from attempting to read the root object as an array.

Run still returns the original error chain. After it logs the problems, the generate command suppresses Cobra's duplicate error printing. Argument and bootstrap errors that occur before Run retain their existing handling. Stdout remains available for command results.

The application and integration tests execute command trees through cli.Execute. It restores the original SilenceErrors settings of all commands present before execution after Cobra finishes handling the result, including on panic. Reusing a tree therefore keeps later flag and bootstrap errors visible. Before parsing flags, the wrapper refreshes the environment defaults for --strict, --types, --format, the PDF options, and the invoice override, number, date and due date. Repeated -t flags build one selection for that run. Parsed input paths remain available on subsequent executions of the same tree.

Documentation

Index

Constants

View Source
const (
	InputFlag      = "input"
	InputShortFlag = "i"

	StrictFlag         = "strict"
	StrictShortFlag    = ""
	StrictDefaultValue = false

	TypesFlag      = "types"
	TypesShortFlag = "t"

	FormatFlag         = "format"
	FormatShortFlag    = ""
	FormatText         = "text"
	FormatPDF          = "pdf"
	FormatDefaultValue = FormatText

	OutputDirFlag         = "output-dir"
	OutputDirShortFlag    = ""
	OutputDirDefaultValue = ""

	TemplatesDirFlag         = "templates-dir"
	TemplatesDirShortFlag    = ""
	TemplatesDirDefaultValue = ""

	OverwriteFlag         = "overwrite"
	OverwriteShortFlag    = ""
	OverwriteDefaultValue = false

	InvoiceConfigFlag         = "invoice-config"
	InvoiceConfigShortFlag    = ""
	InvoiceConfigDefaultValue = ""

	InvoiceNumberFlag         = "invoice-number"
	InvoiceNumberShortFlag    = "N"
	InvoiceNumberDefaultValue = ""

	InvoiceDateFlag         = "invoice-date"
	InvoiceDateShortFlag    = "d"
	InvoiceDateDefaultValue = ""

	InvoiceDueDateFlag         = "invoice-due-date"
	InvoiceDueDateShortFlag    = "D"
	InvoiceDueDateDefaultValue = ""

	TypeAll      = "all"
	TypeDetailed = "detailed"
	TypeSummary  = "summary"
	TypeInvoice  = "invoice"
)

Variables

View Source
var (
	// InputDefaultValue is the default list of explicit input files.
	InputDefaultValue = []string{}

	// TypesDefaultValue is the default selection for the types flag.
	TypesDefaultValue = []string{TypeAll}
)

Functions

func New

func New() *cobra.Command

New configures documents sub-group command

func SelectsType

func SelectsType(types []string, documentType string) bool

SelectsType reports whether the selection includes the given document type.

Types

type GenerateCommand

type GenerateCommand struct {
	// Inputs contains paths to input timesheet files.
	Inputs []string

	// Strict requires each exchange input to contain exactly one document.
	Strict bool

	// Types contains the requested document types. The default selection is all.
	Types []string

	// Format selects how to render the chosen documents.
	Format string

	// PDF output and template settings.
	OutputDir    string
	TemplatesDir string
	Overwrite    bool

	// InvoiceConfigPath points to the optional override for this invoice.
	InvoiceConfigPath string

	// InvoiceNumber, InvoiceDate and optional InvoiceDueDate apply to this invoice.
	InvoiceNumber  string
	InvoiceDate    string
	InvoiceDueDate string

	// Timesheet contains one v1alpha1.TimeEntryList per input file from the last
	// successful collection. A collection error clears it; a validation error
	// leaves the complete timesheet with updated entry conditions for diagnostics.
	Timesheet *timesheet.Timesheet

	// ProcessedEntries holds the entries to account for after duplicate and overlap checks.
	ProcessedEntries []timesheet.ProcessedEntry

	// CalendarParts holds the selected parts after the full timesheet passes validation.
	CalendarParts []reporting.CalendarPart

	// The selected models are published after successful preparation.
	DetailedReport *reporting.DetailedReport
	SummaryReport  *reporting.SummaryReport
	Invoice        *reporting.Invoice
	// contains filtered or unexported fields
}

GenerateCommand represents `documents generate` command.

func NewGenerateCommand

func NewGenerateCommand() *GenerateCommand

NewGenerateCommand configures GenerateCommand.

func (*GenerateCommand) AddFlags

func (c *GenerateCommand) AddFlags(flags *pflag.FlagSet, envParentPrefixes ...string)

AddFlags configures cli

func (*GenerateCommand) Register

func (c *GenerateCommand) Register() *cobra.Command

Register configures cobra.Command for the command.

func (*GenerateCommand) Run

func (c *GenerateCommand) Run(_ *cobra.Command, _ []string) (err error)

Run prepares and renders the selected documents for the month validated by Args.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL