feat/google-import
Squashed from feat/google-import into main. Co-Authored-By: Codex <noreply@openai.com>
54 files changed,
+3,196
−178
cmd/sheets/main.go+16 −5go.mod+1 −1go.sum+2 −2internal/sheets/app.go+9 −13internal/sheets/calc/inspect.go+49 −0internal/sheets/calc/inspect_test.go+53 −0internal/sheets/format/currency.go+73 −0internal/sheets/format/currency_test.go+52 −0internal/sheets/format/dates.go+11 −12internal/sheets/format/format.go+4 −0internal/sheets/format/section.go+13 −3internal/sheets/google_import_browser_test.go+94 −0internal/sheets/googleimport.go+71 −0internal/sheets/googleimport_test.go+133 −0internal/sheets/handlers_grid.go+3 −2internal/sheets/handlers_import.go+12 −8internal/sheets/handlers_import_page.go+41 −3internal/sheets/handlers_import_report.go+121 −0internal/sheets/handlers_import_test.go+9 −3internal/sheets/handlers_sheets.go+3 −1internal/sheets/importlifecycle.go+10 −3internal/sheets/importreport.go+95 −0internal/sheets/importreport_test.go+209 −0internal/sheets/migrations.go+1 −0internal/sheets/migrations/0011_create_import_reports.sql+2 −0internal/sheets/migrations/schema.sql+2 −0internal/sheets/native.go+9 −1internal/sheets/render.go+2 −0internal/sheets/store/models.go+15 −0internal/sheets/store/textinput.go+38 −0internal/sheets/store/textinput_test.go+68 −0internal/sheets/templates/import.html+21 −3internal/sheets/templates/import_report.html+42 −0internal/sheets/templates/sheet.html+1 −0internal/sheets/xlsx/agree_test.go+34 −0internal/sheets/xlsx/blob.go+4 −3internal/sheets/xlsx/blob_test.go+1 −1internal/sheets/xlsx/cell.go+247 −0internal/sheets/xlsx/classify.go+70 −0internal/sheets/xlsx/currency_test.go+54 −0internal/sheets/xlsx/helpers_test.go+1 −1internal/sheets/xlsx/import.go+85 −111internal/sheets/xlsx/import_omissions_test.go+105 −0internal/sheets/xlsx/import_refusals_test.go+114 −0internal/sheets/xlsx/import_values_test.go+161 −0internal/sheets/xlsx/omissions.go+96 −0internal/sheets/xlsx/plaintext_test.go+1 −1internal/sheets/xlsx/rawbook_test.go+140 −0internal/sheets/xlsx/report.go+119 −0internal/sheets/xlsx/roundtrip_test.go+1 −1internal/sheets/xlsx/saved.go+128 −0internal/sheets/xlsx/scan_parts.go+229 −0internal/sheets/xlsx/scan_sheet.go+236 −0tools/drive/google-import.mjs+85 −0
CI passed — run details
landed from feat/google-import
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go| index 3b04f1f..faaa571 100644 |
| --- a/cmd/sheets/main.go |
| +++ b/cmd/sheets/main.go |
| @@ -113,12 +113,23 @@ func main() { |
| // are mutually dependent: auth's admission gate has to read this |
| // app's grants table so a guest somebody shared a sheet with can |
| // sign in at all. See App.Admits. |
| + // Google Drive import: all three public SHEETS_GOOGLE_* settings or |
| + // none. Some but not all, or a malformed one, refuses boot rather |
| + // than serve a chooser that cannot work. The error carries no |
| + // setting's value. |
| + google, err := sheets.LoadGoogleImport() |
| + if err != nil { |
| + logger.Error("google import", "err", err) |
| + os.Exit(1) |
| + } |
| + |
| app := sheets.New(sheets.Config{ |
| - DB: d.G, |
| - Sealer: sealer, |
| - Origin: authEnv.Origin, |
| - Admit: sheets.Admits(authEnv.Owners), |
| - Team: team, |
| + DB: d.G, |
| + Sealer: sealer, |
| + Origin: authEnv.Origin, |
| + Admit: sheets.Admits(authEnv.Owners), |
| + Team: team, |
| + GoogleImport: google, |
| }) |
| signin, err := sheets.NewAuth(d.Writer(), authEnv, logger, app) |
diff --git a/go.mod b/go.mod| index f605222..a32d954 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -4,7 +4,7 @@ go 1.25.0 |
| require ( |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 |
| - amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| + amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f |
| amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
diff --git a/go.sum b/go.sum| index 953c2b5..578371a 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,7 +1,7 @@ |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw= |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| -amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw= |
| -amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| +amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f h1:SxWyFCGQwmxhSQPUT2SN04p9dyzUhElb7yuHDMH7HuQ= |
| +amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM= |
| amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I= |
diff --git a/internal/sheets/app.go b/internal/sheets/app.go| index bbbe54c..30ca139 100644 |
| --- a/internal/sheets/app.go |
| +++ b/internal/sheets/app.go |
| @@ -7,6 +7,7 @@ import ( |
| "net/http" |
| "amadan.net/oficina/estilo.git/chrome" |
| + "amadan.net/oficina/estilo.git/googleimport" |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -54,6 +55,9 @@ type Config struct { |
| // Team is team mode's verified configuration (TeamSettings), nil |
| // unless SHEETS_TEAM_* is set (team_config.go). |
| Team *teammode.Settings |
| + // GoogleImport is the Google Drive chooser's public configuration |
| + // (googleimport.go); the zero value is off. |
| + GoogleImport googleimport.Config |
| } |
| // App holds the wiring. One per process. |
| @@ -69,6 +73,7 @@ type App struct { |
| // team mode (team_config.go). Every team-mode branch keys on it. |
| team *teamRuntime |
| teamSettings *teammode.Settings |
| + google googleimport.Config |
| teamTest |
| db *gorm.DB |
| auth *auth.Auth |
| @@ -115,6 +120,7 @@ func New(cfg Config) *App { |
| admit: cfg.Admit, |
| hub: live.NewHub(), |
| teamSettings: cfg.Team, |
| + google: cfg.GoogleImport, |
| // nil logger means slog.Default(), which is exactly what main |
| // passes rastrillo everywhere else. |
| jobs: jobs.New(nil), |
| @@ -203,6 +209,7 @@ func (a *App) Router() http.Handler { |
| // http.FileServerFS semantics, where the URL path is "/" plus the |
| // FS path. |
| r.Handle("/static/*", staticHandler()) |
| + r.Get(googleScriptPath, serveGoogleScript) |
| // estilo serves the suite's app icons (the bar's brand). |
| mountEstilo(r) |
| // Light/dark is a per-person preference set by a form, so it works |
| @@ -228,19 +235,8 @@ func (a *App) Router() http.Handler { |
| r.Get("/api/native/jobs/{id}", a.handleNativeJob) |
| r.Get("/sheets", a.handleSheetList) |
| r.Post("/sheets", a.handleSheetCreate) |
| - // Static before the {sheetID} pattern below. chi prefers an |
| - // exact segment over a wildcard whatever the order, so this is |
| - // belt and braces rather than load-bearing — but a route that |
| - // only works because of resolution order is a route one |
| - // refactor away from parsing "import" as a sheet id. |
| - // TestImportPathIsNotASheetID pins it. |
| - r.Get("/sheets/import", a.handleImportPage) |
| - // Import. A whole workbook is too much work for a request, so |
| - // it 303s to a job (spec §11) rather than holding the |
| - // connection open — and the drop zone on the list posts to |
| - // exactly this route, because drag and drop is an enhancement |
| - // over the form, not a second way in. |
| - r.Post("/sheets/import", a.handleSheetImport) |
| + // Before the {sheetID} pattern below (handlers_import_page.go). |
| + a.importRoutes(r) |
| r.Get("/sheets/{sheetID}", a.handleSheetPage) |
| // Rename. The other half of a Create button that no longer |
| // asks for a name — see handlers_rename.go. |
diff --git a/internal/sheets/calc/inspect.go b/internal/sheets/calc/inspect.go| new file mode 100644 |
| index 0000000..5e73725 |
| --- /dev/null |
| +++ b/internal/sheets/calc/inspect.go |
| @@ -0,0 +1,49 @@ |
| +package calc |
| + |
| +// Inspection is what a parsed formula asks of this engine: whether |
| +// every function it calls is one evalCall can dispatch, and whether |
| +// any of them reads the clock. |
| +// |
| +// Import needs both. A formula that parses but names a function this |
| +// engine does not have evaluates to #NAME?, so keeping it would replace |
| +// a workbook's value with an error nobody typed; it has to be told |
| +// apart before it is written, not discovered afterwards. And a formula |
| +// that reads the clock cannot be compared with the value a workbook |
| +// saved for it, because the two were computed at different moments. |
| +type Inspection struct { |
| + // Unknown is true when some call names a function no table has. |
| + Unknown bool |
| + // Volatile is true when some call reads the recalculation clock |
| + // (NOW, TODAY). |
| + Volatile bool |
| +} |
| + |
| +// Inspect walks n and every node beneath it. |
| +func Inspect(n Node) Inspection { |
| + var in Inspection |
| + inspect(n, &in) |
| + return in |
| +} |
| + |
| +func inspect(n Node, in *Inspection) { |
| + switch t := n.(type) { |
| + case *Call: |
| + _, ordinary := funcTable[t.Name] |
| + _, clock := clockFuncTable[t.Name] |
| + _, node := nodeFuncTable[t.Name] |
| + if !ordinary && !clock && !node { |
| + in.Unknown = true |
| + } |
| + if clock { |
| + in.Volatile = true |
| + } |
| + for _, a := range t.Args { |
| + inspect(a, in) |
| + } |
| + case *Binary: |
| + inspect(t.Left, in) |
| + inspect(t.Right, in) |
| + case *Unary: |
| + inspect(t.X, in) |
| + } |
| +} |
diff --git a/internal/sheets/calc/inspect_test.go b/internal/sheets/calc/inspect_test.go| new file mode 100644 |
| index 0000000..e450cf0 |
| --- /dev/null |
| +++ b/internal/sheets/calc/inspect_test.go |
| @@ -0,0 +1,53 @@ |
| +package calc |
| + |
| +import "testing" |
| + |
| +func TestInspectNamesUnknownAndVolatileCalls(t *testing.T) { |
| + cases := []struct { |
| + src string |
| + unknown bool |
| + volatile bool |
| + }{ |
| + {"1+2", false, false}, |
| + {"SUM(A1:A3)*2", false, false}, |
| + {"IF(A1>0,VLOOKUP(A1,B1:C9,2,FALSE),-A1)", false, false}, |
| + {"NOW()-TODAY()", false, true}, |
| + {"FOO(1)", true, false}, |
| + {"SUM(1,QUERY(A1))", true, false}, |
| + {"-NOTAFUNCTION(A1)", true, false}, |
| + {"IF(TRUE,1,BAR())+NOW()", true, true}, |
| + } |
| + for _, c := range cases { |
| + n, err := Parse(c.src) |
| + if err != nil { |
| + t.Fatalf("Parse(%q): %v", c.src, err) |
| + } |
| + got := Inspect(n) |
| + if got.Unknown != c.unknown || got.Volatile != c.volatile { |
| + t.Errorf("Inspect(%q) = %+v, want unknown=%v volatile=%v", c.src, got, c.unknown, c.volatile) |
| + } |
| + } |
| +} |
| + |
| +// The import converter treats a formula that fails to parse as |
| +// unsupported. These are the shapes Google and Excel write for things |
| +// this engine has no model of; each must fail here rather than parse |
| +// into something that evaluates. |
| +func TestParseRefusesShapesImportCannotKeep(t *testing.T) { |
| + for _, src := range []string{ |
| + "Sheet2!A1", |
| + "'My Sheet'!A1:B2", |
| + "[1]Sheet1!A1", |
| + "TaxRate*A1", |
| + "_xlfn.XLOOKUP(1,A1:A2,B1:B2)", |
| + `IFERROR(__xludf.DUMMYFUNCTION("QUERY(A1)"),3)`, |
| + "SUM(Table1[Col])", |
| + "{1,2}", |
| + "A1#", |
| + "@A1", |
| + } { |
| + if n, err := Parse(src); err == nil { |
| + t.Errorf("Parse(%q) = %#v, want an error", src, n) |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/format/currency.go b/internal/sheets/format/currency.go| new file mode 100644 |
| index 0000000..dbdc475 |
| --- /dev/null |
| +++ b/internal/sheets/format/currency.go |
| @@ -0,0 +1,73 @@ |
| +package format |
| + |
| +import ( |
| + "strings" |
| + "unicode" |
| + "unicode/utf8" |
| +) |
| + |
| +// expandCurrency turns Google/Excel currency tokens into quoted literals |
| +// before date detection: the D in [$CAD] is a currency code, not a day. |
| +// Google ignores an optional hexadecimal locale suffix. Keep the stored |
| +// format unchanged; this normalization only controls display. |
| +// https://developers.google.com/workspace/sheets/api/guides/formats |
| +func expandCurrency(section string) string { |
| + var out strings.Builder |
| + quoted := false |
| + for i := 0; i < len(section); { |
| + switch { |
| + case section[i] == '\\' && i+1 < len(section): |
| + _, size := utf8.DecodeRuneInString(section[i+1:]) |
| + out.WriteString(section[i : i+1+size]) |
| + i += 1 + size |
| + case section[i] == '"': |
| + quoted = !quoted |
| + out.WriteByte(section[i]) |
| + i++ |
| + case !quoted && strings.HasPrefix(section[i:], "[$"): |
| + end := strings.IndexByte(section[i+2:], ']') |
| + if end >= 0 { |
| + if symbol, ok := currencyLiteral(section[i+2 : i+2+end]); ok { |
| + out.WriteByte('"') |
| + out.WriteString(symbol) |
| + out.WriteByte('"') |
| + i += end + 3 |
| + continue |
| + } |
| + } |
| + out.WriteByte(section[i]) |
| + i++ |
| + default: |
| + out.WriteByte(section[i]) |
| + i++ |
| + } |
| + } |
| + return out.String() |
| +} |
| + |
| +func currencyLiteral(token string) (string, bool) { |
| + symbol, locale, hasLocale := strings.Cut(token, "-") |
| + if hasLocale { |
| + if len(locale) == 0 || len(locale) > 8 { |
| + return "", false |
| + } |
| + for _, r := range locale { |
| + if !strings.ContainsRune("0123456789abcdefABCDEF", r) { |
| + return "", false |
| + } |
| + } |
| + } |
| + r, size := utf8.DecodeRuneInString(symbol) |
| + if size == len(symbol) && unicode.Is(unicode.Sc, r) { |
| + return symbol, true |
| + } |
| + if len(symbol) != 3 { |
| + return "", false |
| + } |
| + for _, r := range symbol { |
| + if r < 'A' || r > 'Z' { |
| + return "", false |
| + } |
| + } |
| + return symbol, true |
| +} |
diff --git a/internal/sheets/format/currency_test.go b/internal/sheets/format/currency_test.go| new file mode 100644 |
| index 0000000..dc4dbb5 |
| --- /dev/null |
| +++ b/internal/sheets/format/currency_test.go |
| @@ -0,0 +1,52 @@ |
| +package format |
| + |
| +import "testing" |
| + |
| +func TestDisplayCurrencySymbols(t *testing.T) { |
| + for _, tc := range []struct{ code, want string }{ |
| + {`€#,##0.00`, "€1,234.50"}, |
| + {`\€#,##0.00`, "€1,234.50"}, |
| + {`[$€]#,##0.00`, "€1,234.50"}, |
| + {`[$£]#,##0.00`, "£1,234.50"}, |
| + {`[$$]#,##0.00`, "$1,234.50"}, |
| + {`[$CAD]#,##0.00`, "CAD1,234.50"}, |
| + {`[$CAD-1009]#,##0.00`, "CAD1,234.50"}, |
| + {`[$€-407]#,##0.00`, "€1,234.50"}, |
| + {`#,##0.00[$€]`, "1,234.50€"}, |
| + {`"[$€]"#,##0.00`, "[$€]1,234.50"}, |
| + {`\[$€]#,##0.00`, "[$€]1,234.50"}, |
| + } { |
| + t.Run(tc.code, func(t *testing.T) { |
| + if got := Display(numValue(1234.5), tc.code); got != tc.want { |
| + t.Fatalf("Display = %q, want %q", got, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCurrencySectionsAndUnicodeDates(t *testing.T) { |
| + for _, tc := range []struct { |
| + code string |
| + num float64 |
| + want string |
| + }{ |
| + {`[$€]0.00`, -12.5, "-€12.50"}, |
| + {`[$€]0.00;([$€]0.00);"zero"`, -12.5, "(€12.50)"}, |
| + {`[$€]0.00;([$€]0.00);"zero"`, 0, "zero"}, |
| + {`[$CAD]`, -12.5, "CAD"}, |
| + {`yyyy年mm月dd日`, 1, "1899年12月31日"}, |
| + {`yyyy\年mm\月dd\日`, 1, "1899年12月31日"}, |
| + } { |
| + if got := Display(numValue(tc.num), tc.code); got != tc.want { |
| + t.Errorf("Display(%v, %q) = %q, want %q", tc.num, tc.code, got, tc.want) |
| + } |
| + } |
| +} |
| + |
| +func TestCurrencyExpansionDoesNotInterpretOtherSyntax(t *testing.T) { |
| + for _, code := range []string{`[$]0`, `[$€-]0`, `[$€-garbage]0`, `[$€`, `[Red]0`, `[$"x"]0`, `[$€;0]`} { |
| + if got := expandCurrency(code); got != code { |
| + t.Errorf("unsupported currency token changed: %q -> %q", code, got) |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/format/dates.go b/internal/sheets/format/dates.go| index 514ce41..dcf760f 100644 |
| --- a/internal/sheets/format/dates.go |
| +++ b/internal/sheets/format/dates.go |
| @@ -5,16 +5,13 @@ import ( |
| "strconv" |
| "strings" |
| "time" |
| + "unicode/utf8" |
| ) |
| -// excelEpoch mirrors calc/fn_date.go's constant of the same name and |
| -// value: day zero in spreadsheet date-serial numbering (Dec 30, 1899). |
| -// format cannot reach calc's unexported var (its only allowed import |
| -// from calc is Value), so the value is restated here; it must stay in |
| -// lockstep with calc's, or a date serial stops rendering as the |
| -// calendar date that produced it. See calc/fn_date.go for why this |
| -// epoch (one day off "real" Dec 31, 1899) reproduces Excel's numbering |
| -// with ordinary calendar arithmetic, no fake-leap-day case needed. |
| +// excelEpoch mirrors calc/fn_date.go's unexported epoch: Dec 30, 1899. |
| +// Keep them in lockstep so a date serial renders as the date that produced |
| +// it. See calc/fn_date.go for why this reproduces Excel's numbering with |
| +// ordinary calendar arithmetic, without a fake-leap-day special case. |
| var excelEpoch = time.Date(1899, time.December, 30, 0, 0, 0, 0, time.UTC) |
| type dateTokKind int |
| @@ -57,8 +54,9 @@ func tokenizeDate(section string) ([]dateTok, bool) { |
| c := section[i] |
| switch { |
| case c == '\\' && i+1 < len(section): |
| - toks = append(toks, dateTok{kind: dtLiteral, lit: string(section[i+1])}) |
| - i += 2 |
| + _, size := utf8.DecodeRuneInString(section[i+1:]) |
| + toks = append(toks, dateTok{kind: dtLiteral, lit: section[i+1 : i+1+size]}) |
| + i += 1 + size |
| case c == '"': |
| j := strings.IndexByte(section[i+1:], '"') |
| if j < 0 { |
| @@ -87,8 +85,9 @@ func tokenizeDate(section string) ([]dateTok, bool) { |
| case isASCIILetter(c): |
| return nil, false |
| default: |
| - toks = append(toks, dateTok{kind: dtLiteral, lit: string(c)}) |
| - i++ |
| + _, size := utf8.DecodeRuneInString(section[i:]) |
| + toks = append(toks, dateTok{kind: dtLiteral, lit: section[i : i+size]}) |
| + i += size |
| } |
| } |
| return toks, true |
diff --git a/internal/sheets/format/format.go b/internal/sheets/format/format.go| index 6e2e544..3190810 100644 |
| --- a/internal/sheets/format/format.go |
| +++ b/internal/sheets/format/format.go |
| @@ -24,6 +24,10 @@ |
| // percent (scales by 100), literal text via "quoted" runs or a |
| // \-escaped single character, and any other bare character as a |
| // literal (so a currency symbol like "€" or "$" needs no quoting). |
| +// - Currency literals containing one Unicode currency symbol or three |
| +// uppercase ASCII letters, such as [$€], [$$] and [$CAD], optionally with |
| +// a hexadecimal locale suffix ([$CAD-1009]); the suffix is ignored, |
| +// matching Google Sheets. The original format remains stored intact. |
| // - Up to four ';'-separated sections: positive;negative;zero;text, |
| // per Excel's own convention. With one section it is used for |
| // every number and a negative value gets an automatic "-" prefix |
diff --git a/internal/sheets/format/section.go b/internal/sheets/format/section.go| index 6e41e1e..6718e90 100644 |
| --- a/internal/sheets/format/section.go |
| +++ b/internal/sheets/format/section.go |
| @@ -1,6 +1,9 @@ |
| package format |
| -import "strings" |
| +import ( |
| + "strings" |
| + "unicode/utf8" |
| +) |
| // sectionMode classifies one ';'-separated format section so renderSection |
| // knows which tokenizer to run. |
| @@ -67,6 +70,7 @@ func walkBareRunes(section string, fn func(byte) bool) { |
| // fixed literal label — used to decide whether a single-section format |
| // gets an automatic "-" for a negative value. |
| func rendersNumber(section string) bool { |
| + section = expandCurrency(section) |
| if strings.EqualFold(strings.TrimSpace(section), "General") { |
| return true |
| } |
| @@ -78,6 +82,7 @@ func rendersNumber(section string) bool { |
| // construct this package does not support, telling the caller to fall |
| // back to General. |
| func renderSection(section string, val float64) (string, bool) { |
| + section = expandCurrency(section) |
| if strings.EqualFold(strings.TrimSpace(section), "General") { |
| return generalNumber(val), true |
| } |
| @@ -137,8 +142,9 @@ func walkLiteralAndPlaceholders(section string, onLiteral func(string), onOther |
| c := section[i] |
| switch { |
| case c == '\\' && i+1 < len(section): |
| - onLiteral(string(section[i+1])) |
| - i += 2 |
| + _, size := utf8.DecodeRuneInString(section[i+1:]) |
| + onLiteral(section[i+1 : i+1+size]) |
| + i += 1 + size |
| case c == '"': |
| j := strings.IndexByte(section[i+1:], '"') |
| if j < 0 { |
| @@ -148,6 +154,10 @@ func walkLiteralAndPlaceholders(section string, onLiteral func(string), onOther |
| onLiteral(section[i+1 : i+1+j]) |
| i = i + 1 + j + 1 |
| } |
| + case c >= utf8.RuneSelf: |
| + _, size := utf8.DecodeRuneInString(section[i:]) |
| + onLiteral(section[i : i+size]) |
| + i += size |
| default: |
| if onOther(c) { |
| return |
diff --git a/internal/sheets/google_import_browser_test.go b/internal/sheets/google_import_browser_test.go| new file mode 100644 |
| index 0000000..526157d |
| --- /dev/null |
| +++ b/internal/sheets/google_import_browser_test.go |
| @@ -0,0 +1,94 @@ |
| +//go:build browser |
| + |
| +package sheets |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/estilo.git/googleimport" |
| +) |
| + |
| +// The Google SDK and export are controlled, while the app, upload, job, |
| +// converter, report and editors are real. This synthesized workbook does |
| +// not replace a live Google account/export check. |
| +func TestGoogleImportBrowserKeepsValuesAndEdits(t *testing.T) { |
| + server := httptest.NewUnstartedServer(nil) |
| + origin := "https://" + server.Listener.Addr().String() |
| + base, cookies := signIn(t) |
| + app := New(Config{DB: base.db, Auth: base.auth, Sealer: base.sealer, Origin: origin, Admit: base.admit, |
| + GoogleImport: googleimport.Config{ClientID: "123456789-client.apps.googleusercontent.com", APIKey: "AIzaPublicBrowserKey123456789", AppID: "123456789"}}) |
| + served := productionHandler(t, app) |
| + server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost && r.URL.Path == "/sheets/import" { |
| + body, err := io.ReadAll(io.LimitReader(r.Body, 21<<20)) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + _ = r.Body.Close() |
| + r.Body = io.NopCloser(bytes.NewReader(body)) |
| + if bytes.Contains(body, []byte("controlled-google-bearer")) || strings.Contains(r.Header.Get("Authorization"), "controlled-google-bearer") || strings.Contains(r.URL.String(), "controlled-google-bearer") { |
| + t.Error("Google token reached Sheets") |
| + } |
| + } |
| + served.ServeHTTP(w, r) |
| + }) |
| + server.StartTLS() |
| + t.Cleanup(server.Close) |
| + config, err := json.Marshal(map[string]any{"origin": origin, "cookies": cookies, "fixture": googleBrowserXLSX(t)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, "node", "google-import.mjs") |
| + cmd.Dir = "../../tools/drive" |
| + cmd.Env = append(os.Environ(), "SHEETS_GOOGLE_IMPORT_TEST="+string(config)) |
| + if out, err := cmd.CombinedOutput(); err != nil { |
| + t.Fatalf("Google import browser flow: %v\n%s", err, out) |
| + } |
| +} |
| + |
| +func googleBrowserXLSX(t *testing.T) []byte { |
| + t.Helper() |
| + data := corpusFile(t, "formulas.xlsx") |
| + source, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var buf bytes.Buffer |
| + out := zip.NewWriter(&buf) |
| + for _, part := range source.File { |
| + w, err := out.Create(part.Name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if part.Name == "xl/worksheets/sheet1.xml" { |
| + _, err = io.WriteString(w, `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="A1:B3"/><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>00123</t></is></c><c r="B1"><f>IFERROR(__xludf.DUMMYFUNCTION("GOOGLEFINANCE"),0)</f><v>7</v></c></row><row r="2"><c r="A2"><v>2</v></c><c r="B2"><f>A2+3</f><v>5</v></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>=x</t></is></c><c r="B3" t="inlineStr"><is><t>TRUE</t></is></c></row></sheetData></worksheet>`) |
| + } else { |
| + r, openErr := part.Open() |
| + if openErr != nil { |
| + t.Fatal(openErr) |
| + } |
| + _, err = io.Copy(w, r) |
| + _ = r.Close() |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := out.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return buf.Bytes() |
| +} |
diff --git a/internal/sheets/googleimport.go b/internal/sheets/googleimport.go| new file mode 100644 |
| index 0000000..cdd845d |
| --- /dev/null |
| +++ b/internal/sheets/googleimport.go |
| @@ -0,0 +1,71 @@ |
| +package sheets |
| + |
| +import ( |
| + "net/http" |
| + "os" |
| + |
| + "amadan.net/oficina/estilo.git/googleimport" |
| +) |
| + |
| +// Google Drive import is estilo's chooser (googleimport) on the import |
| +// page: it exports one Google spreadsheet as XLSX in the browser and |
| +// submits it through the page's own upload form. Sheets never talks to |
| +// Google and never sees a Google token; everything after the upload is |
| +// the ordinary import. |
| +// |
| +// Off unless all three public settings are set. They are browser |
| +// configuration, not secrets. |
| + |
| +// LoadGoogleImport reads SHEETS_GOOGLE_* and validates them together: |
| +// none set is off, all three valid is on, anything else refuses boot. |
| +func LoadGoogleImport() (googleimport.Config, error) { |
| + cfg := googleimport.Config{ |
| + ClientID: os.Getenv("SHEETS_GOOGLE_CLIENT_ID"), |
| + APIKey: os.Getenv("SHEETS_GOOGLE_API_KEY"), |
| + AppID: os.Getenv("SHEETS_GOOGLE_APP_ID"), |
| + } |
| + if err := cfg.Validate(); err != nil { |
| + return googleimport.Config{}, err |
| + } |
| + return cfg, nil |
| +} |
| + |
| +// googleScriptPath serves the chooser's module. Its name carries the |
| +// script's hash, so it may be cached for good. |
| +var googleScriptPath = "/static/google/" + googleimport.JSName() |
| + |
| +func serveGoogleScript(w http.ResponseWriter, _ *http.Request) { |
| + w.Header().Set("Content-Type", "text/javascript; charset=utf-8") |
| + w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") |
| + w.Write(googleimport.JS()) |
| +} |
| + |
| +// The import form and its file input, named for the chooser. |
| +const ( |
| + importFormID = "import-form" |
| + importInputID = "file" |
| +) |
| + |
| +// googleView is the chooser's view on the import page. Its Enabled is |
| +// false with Google import off, and the template renders nothing. |
| +// |
| +// English labels, like the rest of Sheets: estilo's catalog has twelve |
| +// locales, and Sheets has no locale plumbing to choose among them. |
| +func (a *App) googleView() googleimport.View { |
| + return googleimport.View{ |
| + Config: a.google, Kind: googleimport.Sheets, |
| + FormID: importFormID, InputID: importInputID, |
| + Labels: googleimport.Text("en"), |
| + } |
| +} |
| + |
| +// googleHeaders extends the page policy for Google's script, frame and |
| +// connection origins on the import page alone, and sets no-store. It |
| +// adds no Cross-Origin-Opener-Policy: none is set anywhere, and the |
| +// sign-in popup needs none. With Google import off it does nothing. |
| +func (a *App) googleHeaders(w http.ResponseWriter) error { |
| + if !a.google.Enabled() { |
| + return nil |
| + } |
| + return googleimport.Headers(w, ContentSecurityPolicy) |
| +} |
diff --git a/internal/sheets/googleimport_test.go b/internal/sheets/googleimport_test.go| new file mode 100644 |
| index 0000000..f59bced |
| --- /dev/null |
| +++ b/internal/sheets/googleimport_test.go |
| @@ -0,0 +1,133 @@ |
| +package sheets |
| + |
| +import ( |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/estilo.git/googleimport" |
| +) |
| + |
| +var testGoogle = googleimport.Config{ |
| + ClientID: "123456789-client.apps.googleusercontent.com", |
| + APIKey: "AIzaPublicBrowserKey123456789", |
| + AppID: "123456789", |
| +} |
| + |
| +func TestLoadGoogleImportIsAllOrNothing(t *testing.T) { |
| + set := func(id, key, app string) { |
| + t.Setenv("SHEETS_GOOGLE_CLIENT_ID", id) |
| + t.Setenv("SHEETS_GOOGLE_API_KEY", key) |
| + t.Setenv("SHEETS_GOOGLE_APP_ID", app) |
| + } |
| + set("", "", "") |
| + if cfg, err := LoadGoogleImport(); err != nil || cfg.Enabled() { |
| + t.Errorf("none set = %+v, %v; want off", cfg, err) |
| + } |
| + set(testGoogle.ClientID, testGoogle.APIKey, testGoogle.AppID) |
| + if cfg, err := LoadGoogleImport(); err != nil || cfg != testGoogle { |
| + t.Errorf("all set = %+v, %v; want on", cfg, err) |
| + } |
| + set(testGoogle.ClientID, "", testGoogle.AppID) |
| + if _, err := LoadGoogleImport(); err == nil { |
| + t.Error("two of three set: want a refusal") |
| + } |
| + set(testGoogle.ClientID, testGoogle.APIKey, "not-a-project-number") |
| + if _, err := LoadGoogleImport(); err == nil { |
| + t.Error("malformed project number: want a refusal") |
| + } else if strings.Contains(err.Error(), "not-a-project-number") || strings.Contains(err.Error(), testGoogle.APIKey) { |
| + t.Errorf("refusal carries a value: %v", err) |
| + } |
| +} |
| + |
| +// googleApp is a signed-in app with Google import configured. |
| +func googleApp(t *testing.T) (*App, []*http.Cookie) { |
| + t.Helper() |
| + app, cookies := signIn(t) |
| + app.google = testGoogle |
| + return app, cookies |
| +} |
| + |
| +func TestImportPageWithGoogleOffIsUnchanged(t *testing.T) { |
| + app, cookies := signIn(t) |
| + rec := httptest.NewRecorder() |
| + productionHandler(t, app).ServeHTTP(rec, as(httptest.NewRequest(http.MethodGet, "/sheets/import", nil), cookies)) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("import page = %d", rec.Code) |
| + } |
| + if got := rec.Header().Get("Content-Security-Policy"); got != ContentSecurityPolicy { |
| + t.Errorf("policy = %q, want the app's own %q", got, ContentSecurityPolicy) |
| + } |
| + body := rec.Body.String() |
| + for _, absent := range []string{"estilo-google-import", "google.com", googleScriptPath} { |
| + if strings.Contains(body, absent) { |
| + t.Errorf("page with Google off carries %q", absent) |
| + } |
| + } |
| + if !strings.Contains(body, `id="import-form"`) || !strings.Contains(body, `id="file"`) { |
| + t.Error("the upload form is missing") |
| + } |
| +} |
| + |
| +func TestImportPageWithGoogleOnWidensOnlyItsOwnPolicy(t *testing.T) { |
| + app, cookies := googleApp(t) |
| + want, err := googleimport.Policy(ContentSecurityPolicy) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := productionHandler(t, app) |
| + for name, req := range map[string]*http.Request{ |
| + "page": httptest.NewRequest(http.MethodGet, "/sheets/import", nil), |
| + "refused re-render": uploadRequest(t, "notes.txt", []byte("not a workbook")), |
| + } { |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, as(req, cookies)) |
| + if got := rec.Header().Get("Content-Security-Policy"); got != want { |
| + t.Errorf("%s: policy = %q, want %q", name, got, want) |
| + } |
| + if n := len(rec.Header().Values("Content-Security-Policy")); n != 1 { |
| + t.Errorf("%s: %d policies, want exactly one", name, n) |
| + } |
| + if got := rec.Header().Get("Cross-Origin-Opener-Policy"); got != "" { |
| + t.Errorf("%s: COOP = %q, want none", name, got) |
| + } |
| + if got := rec.Header().Get("Cache-Control"); !strings.Contains(got, "no-store") { |
| + t.Errorf("%s: Cache-Control = %q, want no-store", name, got) |
| + } |
| + body := rec.Body.String() |
| + for _, present := range []string{ |
| + `estilo-google-import`, `data-google-form="import-form"`, `data-google-input="file"`, |
| + `data-google-kind="sheets"`, `<script type="module" src="` + googleScriptPath + `">`, |
| + `id="import-form"`, `<noscript>`, |
| + } { |
| + if !strings.Contains(body, present) { |
| + t.Errorf("%s: page lacks %q", name, present) |
| + } |
| + } |
| + } |
| + |
| + // Every other page keeps the app's own policy. |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, as(httptest.NewRequest(http.MethodGet, "/sheets", nil), cookies)) |
| + if got := rec.Header().Get("Content-Security-Policy"); got != ContentSecurityPolicy { |
| + t.Errorf("sheet list policy = %q, want the app's own", got) |
| + } |
| +} |
| + |
| +func TestGoogleScriptIsServedAsImmutableJavaScript(t *testing.T) { |
| + app, _ := signIn(t) |
| + rec := httptest.NewRecorder() |
| + productionHandler(t, app).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, googleScriptPath, nil)) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("script = %d", rec.Code) |
| + } |
| + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/javascript") { |
| + t.Errorf("Content-Type = %q", ct) |
| + } |
| + body, _ := io.ReadAll(rec.Body) |
| + if string(body) != string(googleimport.JS()) { |
| + t.Error("script body is not estilo's module") |
| + } |
| +} |
diff --git a/internal/sheets/handlers_grid.go b/internal/sheets/handlers_grid.go| index b3c71d9..a4adda0 100644 |
| --- a/internal/sheets/handlers_grid.go |
| +++ b/internal/sheets/handlers_grid.go |
| @@ -15,8 +15,9 @@ import ( |
| // |
| // A formula or a label, not a document. The engine would happily parse |
| // a megabyte of nesting and spend a long time doing it, and the cell |
| -// that holds it is one nobody can read anyway. |
| -const maxRawBytes = 8 << 10 |
| +// that holds it is one nobody can read anyway. The number is |
| +// store.MaxInputBytes, which import holds normalised text to as well. |
| +const maxRawBytes = store.MaxInputBytes |
| // cellWrite is the POST body. |
| // |
diff --git a/internal/sheets/handlers_import.go b/internal/sheets/handlers_import.go| index 78661db..22b9942 100644 |
| --- a/internal/sheets/handlers_import.go |
| +++ b/internal/sheets/handlers_import.go |
| @@ -5,7 +5,6 @@ import ( |
| "context" |
| "errors" |
| "net/http" |
| - "strconv" |
| "amadan.net/rastrillo/rastrillo/jobs" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -127,7 +126,10 @@ func (a *App) handleSheetImport(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - location := "/sheets/" + strconv.FormatUint(s.ID, 10) |
| + // The job lands on the import report, which says what came across |
| + // and links to the sheet; the native client is given the sheet |
| + // itself (handleNativeJob). |
| + location := importReportPath(s.ID) |
| job, err := a.jobs.Start(sess.Subject, importJobName, location, |
| func(ctx context.Context, progress func(string)) error { |
| return a.runImport(ctx, s, data, progress) |
| @@ -181,15 +183,17 @@ func (a *App) runImport(ctx context.Context, s SheetSummary, data []byte, progre |
| } |
| defer h.Release() |
| - if err := xlsx.Import(bytes.NewReader(data), h); err != nil { |
| + rep, err := xlsx.Import(bytes.NewReader(data), h) |
| + if err != nil { |
| a.discardSheet(s.ID) |
| return importFailure(err) |
| } |
| - // Reveal it, and only then report success. If this fails the sheet |
| - // stays hidden and the job says so, which is the right way round: |
| - // the alternative is telling somebody their import worked and |
| - // sending them to a sheet the list will not show. |
| - if err := a.markFilled(s.ID); err != nil { |
| + // Reveal it with its report, and only then report success. If this |
| + // fails the sheet stays hidden, without a report, and the job says |
| + // so, which is the right way round: the alternative is telling |
| + // somebody their import worked and sending them to a sheet the list |
| + // will not show. |
| + if err := a.revealImport(s.ID, rep); err != nil { |
| return errors.New("that sheet could not be opened") |
| } |
| // The list orders by real activity, and an imported sheet's |
diff --git a/internal/sheets/handlers_import_page.go b/internal/sheets/handlers_import_page.go| index 8ef317d..c3713b3 100644 |
| --- a/internal/sheets/handlers_import_page.go |
| +++ b/internal/sheets/handlers_import_page.go |
| @@ -1,6 +1,31 @@ |
| package sheets |
| -import "net/http" |
| +import ( |
| + "net/http" |
| + |
| + "amadan.net/oficina/estilo.git/googleimport" |
| + |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +// importRoutes mounts import: the page, the upload, and the report. |
| +// |
| +// The page is static before the {sheetID} pattern. chi prefers an |
| +// exact segment over a wildcard whatever the order, so this is belt |
| +// and braces rather than load-bearing — but a route that only works |
| +// because of resolution order is a route one refactor away from |
| +// parsing "import" as a sheet id. TestImportPathIsNotASheetID pins it. |
| +// |
| +// The upload: a whole workbook is too much work for a request, so it |
| +// 303s to a job (spec §11) rather than holding the connection open — |
| +// and the drop zone and the Google chooser both submit exactly this |
| +// form, because each is an enhancement over the form, not a second way |
| +// in. |
| +func (a *App) importRoutes(r chi.Router) { |
| + r.Get("/sheets/import", a.handleImportPage) |
| + r.Post("/sheets/import", a.handleSheetImport) |
| + r.Get("/sheets/{sheetID}/import-report", a.handleImportReport) |
| +} |
| // The import page. |
| // |
| @@ -17,6 +42,10 @@ type importPageView struct { |
| // everything shown here is read by somebody deciding what to do |
| // differently. |
| Error string |
| + // Google is the Drive chooser; it renders nothing when off. |
| + Google googleimport.View |
| + // GoogleScript is the chooser's module path, set only when on. |
| + GoogleScript string |
| } |
| // handleImportPage draws the import form on a page of its own. |
| @@ -55,6 +84,15 @@ func (a *App) handleImportPage(w http.ResponseWriter, r *http.Request) { |
| // construction. That reasoning arrived here from renderSheetList along |
| // with the form itself. |
| func (a *App) renderImportPage(w http.ResponseWriter, r *http.Request, status int, refusal string) { |
| - a.render(w, r, "import", titled("Import a spreadsheet"), status, |
| - importPageView{Error: refusal}) |
| + // The refused POST's re-render too: it is the same page, and the |
| + // person retries from it. |
| + if err := a.googleHeaders(w); err != nil { |
| + a.fail(w, r, err) |
| + return |
| + } |
| + view := importPageView{Error: refusal, Google: a.googleView()} |
| + if view.Google.Enabled() { |
| + view.GoogleScript = googleScriptPath |
| + } |
| + a.render(w, r, "import", titled("Import a spreadsheet"), status, view) |
| } |
diff --git a/internal/sheets/handlers_import_report.go b/internal/sheets/handlers_import_report.go| new file mode 100644 |
| index 0000000..2576055 |
| --- /dev/null |
| +++ b/internal/sheets/handlers_import_report.go |
| @@ -0,0 +1,121 @@ |
| +package sheets |
| + |
| +import ( |
| + "net/http" |
| + "strconv" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// importReportPath is where an import's report lives, and where its |
| +// job lands. |
| +func importReportPath(sheetID uint64) string { |
| + return "/sheets/" + strconv.FormatUint(sheetID, 10) + "/import-report" |
| +} |
| + |
| +// reportLine is one entry of the report as a person reads it. |
| +type reportLine struct { |
| + Title, Detail string |
| + Count int |
| + Cells []string |
| + More int // coordinates past xlsx.MaxListedCells |
| +} |
| + |
| +type importReportView struct { |
| + Sheet SheetSummary |
| + OmittedWorksheets int |
| + Lines []reportLine |
| +} |
| + |
| +// reportCopy is each code's wording, in the order the page lists them: |
| +// what changed in the cells first, then what was left out. A code this |
| +// table does not name is still shown, under its code, rather than |
| +// dropped. |
| +var reportCopy = []struct { |
| + code xlsx.Code |
| + title, detail string |
| +}{ |
| + {xlsx.FormulaGoogleOnly, "Google-only formulas kept as values", |
| + "These used a function only Google Sheets has. Each cell holds the value Google saved, not the formula."}, |
| + {xlsx.FormulaOtherSheet, "Formulas reading other sheets kept as values", |
| + "These referred to another worksheet or workbook, which did not come across. Each cell holds its saved value."}, |
| + {xlsx.FormulaArray, "Array formulas kept as values", |
| + "Sheets cannot fill a range from one formula. Each cell holds its saved value."}, |
| + {xlsx.FormulaUnsupported, "Other formulas kept as values", |
| + "Sheets cannot calculate these. Each cell holds the value the workbook saved."}, |
| + {xlsx.FormulaDiffers, "Formulas that calculate differently here", |
| + "These stayed formulas, but Sheets' result differs from the value the workbook saved. Check them."}, |
| + {xlsx.FormulaUnchecked, "Formulas not checked", |
| + "These stayed formulas. There was no saved value to compare them with, or they read the clock, so their results here were not checked."}, |
| + {xlsx.TextKept, "Text kept as text", |
| + `This text would otherwise have become a number, a true/false value, a formula or a blank cell, so it is written as ="…" to stay exactly as it was.`}, |
| + {xlsx.FormatPartial, "Formatting partly kept", |
| + "These cells used formatting Sheets does not have, such as borders, fonts, wrapping or built-in number formats."}, |
| + {xlsx.OmittedMerges, "Merged cells", "Each merge was left out; the cells are separate here."}, |
| + {xlsx.OmittedComments, "Comments and notes", "Not imported."}, |
| + {xlsx.OmittedValidation, "Data validation rules", "Not imported."}, |
| + {xlsx.OmittedConditional, "Conditional formatting rules", "Not imported."}, |
| + {xlsx.OmittedHyperlinks, "Links", "The cell text came across; the links did not."}, |
| + {xlsx.OmittedDefinedNames, "Named ranges", "Not imported."}, |
| + {xlsx.OmittedHiddenRows, "Hidden rows", "They are visible here."}, |
| + {xlsx.OmittedHiddenCols, "Hidden columns", "They are visible here."}, |
| + {xlsx.OmittedFrozenPanes, "Frozen rows or columns", "Not imported."}, |
| + {xlsx.OmittedFilter, "Filters", "Not imported."}, |
| + {xlsx.OmittedPictures, "Pictures in cells", "Not imported."}, |
| + {xlsx.OmittedWorkbookChart, "Charts in the workbook", "Not imported."}, |
| + {xlsx.OmittedWorkbookImage, "Images in the workbook", "Not imported."}, |
| + {xlsx.OmittedUndetected, "Parts that could not be checked", |
| + "Some features could not be read, so this report may not list everything that was left out."}, |
| +} |
| + |
| +// reportLines puts a report in reading order. |
| +func reportLines(rep xlsx.Report) []reportLine { |
| + byCode := map[xlsx.Code]xlsx.Entry{} |
| + for _, e := range rep.Entries { |
| + byCode[e.Code] = e |
| + } |
| + line := func(e xlsx.Entry, title, detail string) reportLine { |
| + return reportLine{Title: title, Detail: detail, Count: e.Count, |
| + Cells: e.Cells, More: max(0, e.Count-len(e.Cells))} |
| + } |
| + var out []reportLine |
| + for _, c := range reportCopy { |
| + if e, ok := byCode[c.code]; ok && e.Count > 0 { |
| + out = append(out, line(e, c.title, c.detail)) |
| + delete(byCode, c.code) |
| + } |
| + } |
| + for _, e := range rep.Entries { |
| + if _, ok := byCode[e.Code]; ok && e.Count > 0 { |
| + out = append(out, line(e, string(e.Code), "")) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// handleImportReport shows what an import changed or left behind. |
| +// |
| +// Read access to the sheet is the whole rule: the report is a fact |
| +// about the sheet, so anyone who may read the sheet may read it, and |
| +// anyone who may not gets the same 404 as for the sheet itself. A |
| +// sheet with no report is a 404 too. |
| +func (a *App) handleImportReport(w http.ResponseWriter, r *http.Request) { |
| + s, ok := a.sheetFromURL(w, r) |
| + if !ok { |
| + return |
| + } |
| + rep, ok, err := a.importReport(s.ID) |
| + if err != nil { |
| + a.fail(w, r, err) |
| + return |
| + } |
| + if !ok { |
| + a.notFound(w, r) |
| + return |
| + } |
| + a.render(w, r, "import_report", titled("Import report", s.Title), http.StatusOK, importReportView{ |
| + Sheet: s, |
| + OmittedWorksheets: rep.OmittedWorksheets(), |
| + Lines: reportLines(rep), |
| + }) |
| +} |
diff --git a/internal/sheets/handlers_import_test.go b/internal/sheets/handlers_import_test.go| index 09afd84..bc38a15 100644 |
| --- a/internal/sheets/handlers_import_test.go |
| +++ b/internal/sheets/handlers_import_test.go |
| @@ -113,8 +113,14 @@ func TestImportedSheetIsThereAndEditable(t *testing.T) { |
| if location == "" { |
| t.Fatalf("import did not finish on a sheet; last page said %q", page) |
| } |
| - if !strings.HasPrefix(location, "/sheets/") { |
| - t.Fatalf("job sent us to %q, want a /sheets/ path", location) |
| + sheetPath, ok := strings.CutSuffix(location, "/import-report") |
| + if !strings.HasPrefix(location, "/sheets/") || !ok { |
| + t.Fatalf("job sent us to %q, want a sheet's /import-report", location) |
| + } |
| + // The report opens, and leads to the sheet. |
| + rep := do(t, app, as(httptest.NewRequest(http.MethodGet, location, nil), cookies)) |
| + if rep.Code != http.StatusOK || !strings.Contains(rep.Body.String(), `href="`+sheetPath+`"`) { |
| + t.Fatalf("import report answered %d without a link to %s", rep.Code, sheetPath) |
| } |
| // The sheet is in the list, named after the file. |
| @@ -155,7 +161,7 @@ func TestImportedSheetIsThereAndEditable(t *testing.T) { |
| // And the scriptless view opens it, which is what "available to |
| // edit" means for the path that does not need JavaScript. |
| - rec := do(t, app, as(httptest.NewRequest(http.MethodGet, location+"/table", nil), cookies)) |
| + rec := do(t, app, as(httptest.NewRequest(http.MethodGet, sheetPath+"/table", nil), cookies)) |
| if rec.Code != http.StatusOK { |
| t.Fatalf("table view answered %d, want 200", rec.Code) |
| } |
diff --git a/internal/sheets/handlers_sheets.go b/internal/sheets/handlers_sheets.go| index fea4cae..cad991d 100644 |
| --- a/internal/sheets/handlers_sheets.go |
| +++ b/internal/sheets/handlers_sheets.go |
| @@ -47,7 +47,8 @@ type sheetPageView struct { |
| // the grid can paint. It is rendered as an attribute the page can |
| // read rather than as prose in Go, so the wording lives with the |
| // rest of the copy. |
| - Truncated bool |
| + Truncated bool |
| + ImportReport bool // offers the File menu's "Import report" item |
| // MayShare drives whether the page offers a Share link. The route |
| // checks again — this only decides what to render, and a button |
| // that 404s is worse than no button. |
| @@ -191,6 +192,7 @@ func (a *App) handleSheetPage(w http.ResponseWriter, r *http.Request) { |
| Sheet: s, Rows: defaultWindowRows, Cols: defaultWindowCols, |
| FillSwatches: fillSwatches, InkSwatches: inkSwatches, |
| NumberFormats: numberFormats, |
| + ImportReport: a.hasImportReport(s.ID), |
| } |
| if viewer, ok := a.actor(r); ok { |
| view.MayShare = a.mayShare(s.ID, viewer) |
diff --git a/internal/sheets/importlifecycle.go b/internal/sheets/importlifecycle.go| index a318eb4..5e4b55f 100644 |
| --- a/internal/sheets/importlifecycle.go |
| +++ b/internal/sheets/importlifecycle.go |
| @@ -81,7 +81,7 @@ func (a *App) markFilled(id uint64) error { |
| return res.Error |
| } |
| if res.RowsAffected == 0 { |
| - return errors.New("sheets: that sheet was discarded before its import finished") |
| + return errDiscardedBeforeReveal |
| } |
| return nil |
| } |
| @@ -101,15 +101,18 @@ func importFailure(err error) error { |
| if errors.Is(err, store.ErrTabTooLarge) { |
| return errors.New("that workbook holds more cells than one sheet can take") |
| } |
| + // Op is this package's own fixed wording ("a formula has no usable |
| + // saved value at"), never content, so it can be shown and logged. |
| var cell *xlsx.CellError |
| if errors.As(err, &cell) { |
| - return errors.New("the import stopped at cell " + cell.Ref) |
| + return errors.New("the import stopped: " + cell.Op + " " + cell.Ref) |
| } |
| return errors.New("that file could not be read as a spreadsheet") |
| } |
| // discardSheet throws away a sheet whose import did not finish: it |
| -// soft-deletes the row and removes the grants that were minted with it. |
| +// soft-deletes the row and removes the grants that were minted with it, |
| +// and any import report. |
| // |
| // The grants matter on their own. Admits counts a member's grants to |
| // decide whether an address may sign in at all, so an owner grant left |
| @@ -131,4 +134,8 @@ func (a *App) discardSheet(id uint64) { |
| now := time.Now().UTC() |
| a.db.Model(&store.Sheet{}).Where("id = ?", id).Update("deleted_at", now) |
| a.db.Where("sheet_id = ?", id).Delete(&Grant{}) |
| + // revealImport writes a report only with the reveal, so a discarded |
| + // import should have none; removing any is the same tidiness as the |
| + // grants, for a report that must never outlive its import. |
| + a.db.Where("sheet_id = ?", id).Delete(&store.ImportReport{}) |
| } |
diff --git a/internal/sheets/importreport.go b/internal/sheets/importreport.go| new file mode 100644 |
| index 0000000..f7afa0f |
| --- /dev/null |
| +++ b/internal/sheets/importreport.go |
| @@ -0,0 +1,95 @@ |
| +package sheets |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// sealPurposeImportReport is the seal purpose an import report is |
| +// stored under. Its own purpose, so a report can never be opened as a |
| +// cell, a title or an event, nor any of those as a report. |
| +const sealPurposeImportReport = "import.report" |
| + |
| +// errDiscardedBeforeReveal is an import whose sheet was discarded (by a |
| +// stale-import sweep) before it could be revealed. |
| +var errDiscardedBeforeReveal = errors.New("sheets: that sheet was discarded before its import finished") |
| + |
| +// revealImport stores an import's report and reveals its sheet, in one |
| +// transaction. |
| +// |
| +// One transaction is the point. A visible imported sheet always has |
| +// its report, and a report never exists for a sheet that was not |
| +// revealed: if the reveal finds the sheet already discarded, the |
| +// report rolls back with it. The deleted_at condition is markFilled's, |
| +// for markFilled's reason. |
| +func (a *App) revealImport(id uint64, rep xlsx.Report) error { |
| + if a.db == nil { |
| + return errNoDB |
| + } |
| + body, err := json.Marshal(rep) |
| + if err != nil { |
| + return err |
| + } |
| + sealed, err := a.sealer.Seal(sealPurposeImportReport, body) |
| + if err != nil { |
| + return err |
| + } |
| + return a.db.Transaction(func(tx *gorm.DB) error { |
| + if err := tx.Where("sheet_id = ?", id).Delete(&store.ImportReport{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Create(&store.ImportReport{SheetID: id, ReportSealed: sealed}).Error; err != nil { |
| + return err |
| + } |
| + res := tx.Model(&store.Sheet{}).Where("id = ? AND deleted_at IS NULL", id). |
| + Update("filling_since", nil) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return errDiscardedBeforeReveal |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// importReport opens a sheet's import report. ok is false when the |
| +// sheet has none: it was not imported, or was imported before reports |
| +// existed. |
| +// |
| +// The caller has already decided the viewer may read the sheet; a |
| +// report is never served on its own authority. |
| +func (a *App) importReport(sheetID uint64) (rep xlsx.Report, ok bool, err error) { |
| + if a.db == nil { |
| + return xlsx.Report{}, false, errNoDB |
| + } |
| + var row store.ImportReport |
| + err = a.db.Where("sheet_id = ?", sheetID).Limit(1).Find(&row).Error |
| + if err != nil || row.SheetID == 0 { |
| + return xlsx.Report{}, false, err |
| + } |
| + body, err := a.sealer.Open(sealPurposeImportReport, row.ReportSealed) |
| + if err != nil { |
| + return xlsx.Report{}, false, err |
| + } |
| + if err := json.Unmarshal(body, &rep); err != nil { |
| + return xlsx.Report{}, false, err |
| + } |
| + return rep, true, nil |
| +} |
| + |
| +// hasImportReport is importReport without opening the seal: whether |
| +// the sheet's File menu offers the report at all. |
| +func (a *App) hasImportReport(sheetID uint64) bool { |
| + if a.db == nil { |
| + return false |
| + } |
| + var n int64 |
| + a.db.Model(&store.ImportReport{}).Where("sheet_id = ?", sheetID).Count(&n) |
| + return n > 0 |
| +} |
diff --git a/internal/sheets/importreport_test.go b/internal/sheets/importreport_test.go| new file mode 100644 |
| index 0000000..2346eac |
| --- /dev/null |
| +++ b/internal/sheets/importreport_test.go |
| @@ -0,0 +1,209 @@ |
| +package sheets |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/sealtest" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// googleWorkbook is a two-worksheet workbook in the shapes a Google |
| +// Sheets export writes: typed text that looks like a number, a sealed |
| +// canary cell, a Google-only function wrapped in __xludf.DUMMYFUNCTION |
| +// with its saved value, and a kept formula over them. |
| +func googleWorkbook(t *testing.T, firstSheetRows string) []byte { |
| + t.Helper() |
| + const rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" |
| + sheet := func(rows string) string { |
| + return `<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>` + rows + `</sheetData></worksheet>` |
| + } |
| + parts := map[string]string{ |
| + "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>`, |
| + "_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="` + rel + `/officeDocument" Target="xl/workbook.xml"/></Relationships>`, |
| + "xl/workbook.xml": `<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="` + rel + `"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/><sheet name="Sheet2" sheetId="2" r:id="rId2"/></sheets></workbook>`, |
| + "xl/_rels/workbook.xml.rels": `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="` + rel + `/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="` + rel + `/worksheet" Target="worksheets/sheet2.xml"/><Relationship Id="rIdS" Type="` + rel + `/styles" Target="styles.xml"/></Relationships>`, |
| + "xl/styles.xml": `<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="10"/><name val="Arial"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf/></cellStyleXfs><cellXfs count="1"><xf xfId="0"/></cellXfs></styleSheet>`, |
| + "xl/worksheets/sheet1.xml": sheet(firstSheetRows), |
| + "xl/worksheets/sheet2.xml": sheet(`<row r="1"><c r="A1"><v>1</v></c></row>`), |
| + } |
| + var buf bytes.Buffer |
| + zw := zip.NewWriter(&buf) |
| + for name, body := range parts { |
| + w, err := zw.Create(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w.Write([]byte(body)) |
| + } |
| + if err := zw.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return buf.Bytes() |
| +} |
| + |
| +const googleRows = `<row r="1">` + |
| + `<c r="A1" t="inlineStr"><is><t>00123</t></is></c>` + |
| + `<c r="B1" t="str"><f>IFERROR(__xludf.DUMMYFUNCTION("GOOGLEFINANCE(""X"")"),"7")</f><v>7</v></c>` + |
| + `<c r="C1" t="inlineStr"><is><t>CANARY-CELL-VALUE-8f3a</t></is></c>` + |
| + `</row><row r="2"><c r="A2"><v>4</v></c><c r="B2"><f>A2+3</f><v>7</v></c></row>` |
| + |
| +// importWorkbook posts body through the import form and waits for the |
| +// job, returning where it landed. |
| +func importWorkbook(t *testing.T, app *App, cookies []*http.Cookie, body []byte) string { |
| + t.Helper() |
| + rec := do(t, app, as(uploadRequest(t, "export.xlsx", body), cookies)) |
| + if rec.Code != http.StatusSeeOther { |
| + t.Fatalf("import answered %d", rec.Code) |
| + } |
| + location, page := awaitJob(t, app, cookies, rec.Header().Get("Location")) |
| + if location == "" { |
| + t.Fatalf("import did not finish; page said %q", page) |
| + } |
| + return location |
| +} |
| + |
| +func TestImportLandsOnItsReportAndTheSheetOffersIt(t *testing.T) { |
| + app, cookies := signIn(t) |
| + location := importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| + sheetPath, ok := strings.CutSuffix(location, "/import-report") |
| + if !ok { |
| + t.Fatalf("job landed on %q, want an import report", location) |
| + } |
| + |
| + rec := do(t, app, as(httptest.NewRequest(http.MethodGet, location, nil), cookies)) |
| + page := rec.Body.String() |
| + for _, want := range []string{"What import carries", "Google-only formulas kept as values", |
| + "B1", "Text kept as text", "A1", "1 other worksheet(s) were left out", `href="` + sheetPath + `"`} { |
| + if !strings.Contains(page, want) { |
| + t.Errorf("report page lacks %q", want) |
| + } |
| + } |
| + |
| + rec = do(t, app, as(httptest.NewRequest(http.MethodGet, sheetPath, nil), cookies)) |
| + if !strings.Contains(rec.Body.String(), `href="`+location+`"`) { |
| + t.Error("the sheet's File menu does not offer its import report") |
| + } |
| + |
| + rec = do(t, app, as(httptest.NewRequest(http.MethodGet, sheetPath+"/table", nil), cookies)) |
| + table := rec.Body.String() |
| + for _, want := range []string{"00123", ">7<", ""00123""} { |
| + if !strings.Contains(table, want) { |
| + t.Errorf("table view lacks %q", want) |
| + } |
| + } |
| +} |
| + |
| +func TestImportReportIsSealedAtRest(t *testing.T) { |
| + app, cookies := signIn(t) |
| + importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| + path := dbPath(t, app) |
| + sealtest.AssertNoPlaintext(t, path) |
| + for _, suffix := range []string{"", "-wal", "-shm"} { |
| + b, err := os.ReadFile(path + suffix) |
| + if err != nil { |
| + continue |
| + } |
| + for _, plain := range []string{"formula-google-only", `"entries"`, "text-kept"} { |
| + if bytes.Contains(b, []byte(plain)) { |
| + t.Errorf("%s holds report plaintext %q", suffix, plain) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// dbPath is the file behind app's database. |
| +func dbPath(t *testing.T, app *App) string { |
| + t.Helper() |
| + var rows []struct { |
| + Name, File string |
| + } |
| + if err := app.db.Raw("PRAGMA database_list").Scan(&rows).Error; err != nil || len(rows) == 0 { |
| + t.Fatalf("database_list: %v", err) |
| + } |
| + return rows[0].File |
| +} |
| + |
| +func TestImportReportFollowsSheetAccess(t *testing.T) { |
| + app, cookies := signIn(t) |
| + location := importWorkbook(t, app, cookies, googleWorkbook(t, googleRows)) |
| + |
| + // A guest admitted on another sheet does not see this one's report. |
| + other, _ := newSheet(t, app, cookies, "Elsewhere") |
| + guestOn(t, app, other.ID, "guest@example.com", SheetViewer) |
| + guest := signInAs(t, app, "guest@example.com") |
| + if rec := do(t, app, as(httptest.NewRequest(http.MethodGet, location, nil), guest)); rec.Code != http.StatusNotFound { |
| + t.Errorf("stranger report = %d, want 404", rec.Code) |
| + } |
| + // A sheet that was never imported has none, and offers none. |
| + other404 := importReportPath(other.ID) |
| + if rec := do(t, app, as(httptest.NewRequest(http.MethodGet, other404, nil), cookies)); rec.Code != http.StatusNotFound { |
| + t.Errorf("unimported sheet report = %d, want 404", rec.Code) |
| + } |
| + rec := do(t, app, as(httptest.NewRequest(http.MethodGet, strings.TrimSuffix(other404, "/import-report"), nil), cookies)) |
| + if strings.Contains(rec.Body.String(), "/import-report") { |
| + t.Error("an unimported sheet offers an import report") |
| + } |
| +} |
| + |
| +func TestADiscardedImportLeavesNoReport(t *testing.T) { |
| + app, cookies := signIn(t) |
| + count := func() int64 { |
| + var n int64 |
| + app.db.Model(&store.ImportReport{}).Count(&n) |
| + return n |
| + } |
| + |
| + // Refused mid-import: the formula has no saved value to keep. |
| + refused := `<row r="1"><c r="A1"><v>1</v></c><c r="B1"><f>GOOGLEFINANCE("CANARY-CELL-VALUE-8f3a")</f></c></row>` |
| + rec := do(t, app, as(uploadRequest(t, "refused.xlsx", googleWorkbook(t, refused)), cookies)) |
| + _, page := awaitJob(t, app, cookies, rec.Header().Get("Location")) |
| + if !strings.Contains(page, "B1") || strings.Contains(page, "CANARY") { |
| + t.Errorf("refusal should name B1 and nothing it held: %q", page) |
| + } |
| + if n := count(); n != 0 { |
| + t.Errorf("refused import left %d reports", n) |
| + } |
| + |
| + // Discarded before its reveal: the report rolls back with it. |
| + s, err := app.createFillingSheet(nil, "late", signedInMember(t, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app.discardSheet(s.ID) |
| + if err := app.revealImport(s.ID, xlsxReportForTest()); err != errDiscardedBeforeReveal { |
| + t.Errorf("reveal after discard = %v, want errDiscardedBeforeReveal", err) |
| + } |
| + if n := count(); n != 0 { |
| + t.Errorf("discarded import left %d reports", n) |
| + } |
| +} |
| + |
| +func TestNativeImportJobKeepsTheSheetAsItsLocation(t *testing.T) { |
| + app, cookies := signIn(t) |
| + job, err := app.jobs.Start(signedInMember(t, app).Address, "Native test", importReportPath(42), |
| + func(context.Context, func(string)) error { return nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var got struct{ Status, Location, Report string } |
| + for i := 0; i < 100 && got.Status != "done"; i++ { |
| + rec := do(t, app, as(nativeGet("/api/native/jobs/"+job.ID), cookies)) |
| + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if got.Location != "/sheets/42" || got.Report != "/sheets/42/import-report" { |
| + t.Errorf("native job = %+v, want the sheet as location and the report beside it", got) |
| + } |
| +} |
| + |
| +func xlsxReportForTest() xlsx.Report { return xlsx.Report{Worksheets: 1} } |
diff --git a/internal/sheets/migrations.go b/internal/sheets/migrations.go| index 3b8622c..096c239 100644 |
| --- a/internal/sheets/migrations.go |
| +++ b/internal/sheets/migrations.go |
| @@ -55,4 +55,5 @@ var Models = []any{ |
| sheetAgentState{}, sheetAgentReceipt{}, sheetAgentAttribution{}, sheetAgentEdit{}, |
| store.Sheet{}, store.Tab{}, store.Row{}, store.Col{}, |
| store.Cell{}, store.Format{}, store.Event{}, Member{}, Grant{}, ShareLink{}, Comment{}, TabView{}, |
| + store.ImportReport{}, |
| } |
diff --git a/internal/sheets/migrations/0011_create_import_reports.sql b/internal/sheets/migrations/0011_create_import_reports.sql| new file mode 100644 |
| index 0000000..95cbe92 |
| --- /dev/null |
| +++ b/internal/sheets/migrations/0011_create_import_reports.sql |
| @@ -0,0 +1,2 @@ |
| +CREATE TABLE `import_reports` (`sheet_id` integer,`report_sealed` blob,`created_at` datetime,PRIMARY KEY (`sheet_id`)); |
| + |
diff --git a/internal/sheets/migrations/schema.sql b/internal/sheets/migrations/schema.sql| index f3952dc..01c6910 100644 |
| --- a/internal/sheets/migrations/schema.sql |
| +++ b/internal/sheets/migrations/schema.sql |
| @@ -13,6 +13,8 @@ CREATE TABLE `formats` (`id` integer PRIMARY KEY AUTOINCREMENT,`digest` text,`nu |
| CREATE TABLE `grants` (`id` integer PRIMARY KEY AUTOINCREMENT,`sheet_id` integer,`member_id` integer,`role` text,`granted_by` integer,`created_at` datetime,`updated_at` datetime); |
| +CREATE TABLE `import_reports` (`sheet_id` integer,`report_sealed` blob,`created_at` datetime,PRIMARY KEY (`sheet_id`)); |
| + |
| CREATE TABLE `members` (`id` integer PRIMARY KEY AUTOINCREMENT,`address` text,`created_at` datetime, `team_role` text); |
| CREATE TABLE `rows` (`id` integer PRIMARY KEY AUTOINCREMENT,`tab_id` integer,`position` integer,`height` integer); |
diff --git a/internal/sheets/native.go b/internal/sheets/native.go| index e6a3e81..1947650 100644 |
| --- a/internal/sheets/native.go |
| +++ b/internal/sheets/native.go |
| @@ -87,7 +87,15 @@ func (a *App) handleNativeJob(w http.ResponseWriter, r *http.Request) { |
| a.notFound(w, r) |
| return |
| } |
| - nativeJSON(w, 200, map[string]any{"status": job.Status, "progress": job.Progress, "error": job.Err, "location": job.Location}) |
| + // An import job lands on its report, but the native client reads |
| + // the sheet id from location's last segment: it keeps getting the |
| + // sheet, and the report rides beside it. |
| + location, report := job.Location, "" |
| + if sheet, ok := strings.CutSuffix(location, "/import-report"); ok { |
| + location, report = sheet, job.Location |
| + } |
| + nativeJSON(w, 200, map[string]any{"status": job.Status, "progress": job.Progress, |
| + "error": job.Err, "location": location, "report": report}) |
| } |
| func (a *App) streamAuthorized(r *http.Request, sheetID uint64) bool { |
| if a.team != nil { |
diff --git a/internal/sheets/render.go b/internal/sheets/render.go| index e7de2f8..c66bf9e 100644 |
| --- a/internal/sheets/render.go |
| +++ b/internal/sheets/render.go |
| @@ -15,6 +15,7 @@ import ( |
| "amadan.net/oficina/estilo.git/base" |
| "amadan.net/oficina/estilo.git/busy" |
| "amadan.net/oficina/estilo.git/chrome" |
| + "amadan.net/oficina/estilo.git/googleimport" |
| estilomenu "amadan.net/oficina/estilo.git/menu" |
| "amadan.net/oficina/estilo.git/theme" |
| @@ -139,6 +140,7 @@ func parsePages() map[string]*template.Template { |
| t = template.Must(t.ParseFS(connect.Templates(), "templates/*.html")) |
| t = template.Must(t.ParseFS(estilomenu.Templates(), "templates/*.html")) |
| t = template.Must(t.ParseFS(chrome.Templates(), "templates/*.html")) |
| + t = template.Must(t.ParseFS(googleimport.Templates(), "templates/*.html")) |
| t = template.Must(t.ParseFS(templatesFS, "templates/"+layoutFile, f)) |
| out[name] = t |
| } |
diff --git a/internal/sheets/store/models.go b/internal/sheets/store/models.go| index 9bd5195..7dc527f 100644 |
| --- a/internal/sheets/store/models.go |
| +++ b/internal/sheets/store/models.go |
| @@ -50,6 +50,21 @@ type Sheet struct { |
| FillingSince *time.Time `gorm:"index"` |
| } |
| +// ImportReport is what an import changed or left behind, one per |
| +// imported sheet: xlsx.Report's codes, coordinates and counts, never |
| +// content. Sealed all the same, because which cells were frozen or |
| +// differ is a fact about the sheet, and the bucket holds none of those |
| +// in plaintext. |
| +// |
| +// It is written in the same transaction that reveals the sheet, so a |
| +// visible imported sheet always has its report and a discarded import |
| +// never leaves one behind. |
| +type ImportReport struct { |
| + SheetID uint64 `gorm:"primaryKey;autoIncrement:false"` |
| + ReportSealed []byte // seal purpose "import.report" |
| + CreatedAt time.Time |
| +} |
| + |
| // Tab is one sheet within a document — the tabs along the bottom. |
| type Tab struct { |
| ID uint64 `gorm:"primaryKey"` |
diff --git a/internal/sheets/store/textinput.go b/internal/sheets/store/textinput.go| new file mode 100644 |
| index 0000000..ca427c5 |
| --- /dev/null |
| +++ b/internal/sheets/store/textinput.go |
| @@ -0,0 +1,38 @@ |
| +package store |
| + |
| +import ( |
| + "strings" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| +) |
| + |
| +// MaxInputBytes caps one cell's raw input: what a person may type into |
| +// a cell, and what import may write when it has to wrap text to keep |
| +// it text. A formula or a label, not a document. |
| +const MaxInputBytes = 8 << 10 |
| + |
| +// TextInput returns the raw input that stores s as the text s, and |
| +// whether that took a wrapper. |
| +// |
| +// Raw input has one channel. contentNode reads "" as blank, a leading |
| +// "=" as a formula, and anything strconv.ParseFloat or TRUE/FALSE |
| +// accepts as a number or a boolean, so text such as "00123", "TRUE", |
| +// "NaN", "=total" or "" cannot be written as itself without becoming |
| +// something else. Those become a constant string expression, ="...", |
| +// with every quote doubled: the existing parser reads it back as |
| +// exactly s, its value is the text s, and an editor shows the |
| +// expression rather than a number nobody typed. |
| +// |
| +// Nothing here changes how existing input is read. The wrapper is an |
| +// ordinary formula any person could have typed; the decision whether |
| +// a string needs one is contentNode's own, asked rather than restated, |
| +// so the two cannot drift apart. |
| +func TextInput(s string) (raw string, wrapped bool) { |
| + node, blank, err := contentNode(s) |
| + if err == nil && !blank { |
| + if str, ok := node.(*calc.Str); ok && str.V == s { |
| + return s, false |
| + } |
| + } |
| + return `="` + strings.ReplaceAll(s, `"`, `""`) + `"`, true |
| +} |
diff --git a/internal/sheets/store/textinput_test.go b/internal/sheets/store/textinput_test.go| new file mode 100644 |
| index 0000000..63b0ac4 |
| --- /dev/null |
| +++ b/internal/sheets/store/textinput_test.go |
| @@ -0,0 +1,68 @@ |
| +package store |
| + |
| +import ( |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| +) |
| + |
| +// textOf is what raw input evaluates to when it holds no references: |
| +// a literal's node, or a constant formula's single node. |
| +func textOf(t *testing.T, raw string) (calc.Node, bool) { |
| + t.Helper() |
| + node, blank, err := contentNode(raw) |
| + if err != nil { |
| + t.Fatalf("contentNode(%q): %v", raw, err) |
| + } |
| + return node, blank |
| +} |
| + |
| +func TestTextInputWrapsOnlyAmbiguousText(t *testing.T) { |
| + cases := []struct { |
| + in string |
| + raw string |
| + wrapped bool |
| + }{ |
| + {"hello", "hello", false}, |
| + {" 123", " 123", false}, |
| + {"1,000", "1,000", false}, |
| + {"+353 1 234 5678", "+353 1 234 5678", false}, |
| + {"", `=""`, true}, |
| + {"00123", `="00123"`, true}, |
| + {"+5", `="+5"`, true}, |
| + {"1e5", `="1e5"`, true}, |
| + {"TRUE", `="TRUE"`, true}, |
| + {"false", `="false"`, true}, |
| + {"NaN", `="NaN"`, true}, |
| + {"Inf", `="Inf"`, true}, |
| + {"-infinity", `="-infinity"`, true}, |
| + {"0x1p-2", `="0x1p-2"`, true}, |
| + {"=SUM(A1)", `="=SUM(A1)"`, true}, |
| + {`="quoted"`, `="=""quoted"""`, true}, |
| + } |
| + for _, c := range cases { |
| + raw, wrapped := TextInput(c.in) |
| + if raw != c.raw || wrapped != c.wrapped { |
| + t.Errorf("TextInput(%q) = %q, %v; want %q, %v", c.in, raw, wrapped, c.raw, c.wrapped) |
| + } |
| + } |
| +} |
| + |
| +// Whatever the text, the raw input TextInput returns must read back |
| +// as exactly that text and nothing else. |
| +func FuzzTextInputReadsBackAsItself(f *testing.F) { |
| + for _, s := range []string{"", "0", "00123", "TRUE", "NaN", "=A1", `"`, `""`, "a\"b", "\n", "1e999", "é"} { |
| + f.Add(s) |
| + } |
| + f.Fuzz(func(t *testing.T, s string) { |
| + raw, _ := TextInput(s) |
| + node, blank := textOf(t, raw) |
| + if blank { |
| + t.Fatalf("TextInput(%q) = %q reads as blank", s, raw) |
| + } |
| + str, ok := node.(*calc.Str) |
| + if !ok || str.V != s { |
| + t.Fatalf("TextInput(%q) = %q reads as %#v", s, raw, node) |
| + } |
| + }) |
| +} |
diff --git a/internal/sheets/templates/import.html b/internal/sheets/templates/import.html| index c3ec8da..e9ef46f 100644 |
| --- a/internal/sheets/templates/import.html |
| +++ b/internal/sheets/templates/import.html |
| @@ -7,6 +7,9 @@ |
| This moved here with the form it decorates. It used to sit on the |
| sheet list, which is where the import form used to be. */}} |
| <script defer src="{{asset "static/drop.js"}}"></script> |
| +{{/* Google Drive's chooser, only where it is configured: its module, |
| + and with it the page's widened policy (googleimport.go). */}} |
| +{{with .Data.GoogleScript}}<script type="module" src="{{.}}"></script>{{end}} |
| {{end}} |
| {{define "content"}} |
| @@ -22,8 +25,10 @@ |
| because this page has the room the dropdown they nearly went in |
| did not, and because drop.js overwrites the hint to speak about |
| a drop — which would take the file limits down with it. */}} |
| -<p rst-page-header-sub>Excel .xlsx or .xlsm, up to 20 MB. The first |
| -worksheet is imported.</p> |
| +<p rst-page-header-sub>Excel .xlsx or .xlsm, up to 20 MB. Only the first |
| +worksheet is imported. Values, formulas Sheets can calculate and basic |
| +formatting come across; anything else is listed in an import report when |
| +the import finishes.</p> |
| </div> |
| </header> |
| @@ -38,7 +43,7 @@ worksheet is imported.</p> |
| </div> |
| {{end}} |
| -<form rst-form method="post" action="/sheets/import" enctype="multipart/form-data"> |
| +<form rst-form id="import-form" method="post" action="/sheets/import" enctype="multipart/form-data"> |
| <div data-drop> |
| <div rst-field-row> |
| <div rst-field> |
| @@ -50,4 +55,17 @@ worksheet is imported.</p> |
| </div> |
| </div> |
| </form> |
| + |
| +{{/* After the form it fills: the chooser exports one Google sheet as |
| + XLSX in this browser and submits it through the form above, so it |
| + is the same route, the same checks and the same report. Nothing |
| + renders here when Google import is not configured, and with |
| + scripting off the component says how to download from Google and |
| + use the form instead. */}} |
| +{{if .Data.Google.Enabled}} |
| +<section> |
| +<h2>From Google Drive</h2> |
| +{{template "estilo-google-import" .Data.Google}} |
| +</section> |
| +{{end}} |
| {{end}} |
diff --git a/internal/sheets/templates/import_report.html b/internal/sheets/templates/import_report.html| new file mode 100644 |
| index 0000000..68f63ef |
| --- /dev/null |
| +++ b/internal/sheets/templates/import_report.html |
| @@ -0,0 +1,42 @@ |
| +{{define "content"}} |
| +<header rst-page-header> |
| +<div rst-page-header-titles> |
| +<h1>Import report</h1> |
| +<p rst-page-header-sub>What came across from the workbook, and what did not.</p> |
| +</div> |
| +<a rst-btn="primary" href="/sheets/{{.Data.Sheet.ID}}">Open the sheet</a> |
| +</header> |
| + |
| +{{/* Always shown, whatever the report holds: a report can only list |
| + what it detected, so the page says what import carries at all |
| + rather than let an empty list read as "everything". */}} |
| +<section> |
| +<h2>What import carries</h2> |
| +<p>The first worksheet's values; formulas Sheets can calculate; number |
| +formats written as format codes; fill and text colours; bold, italic and |
| +alignment; column widths and row heights. Everything else stays in the |
| +original file.</p> |
| +</section> |
| + |
| +{{if .Data.OmittedWorksheets}} |
| +{{template "callout" (dict "Body" (printf "Only the first worksheet came across. %d other worksheet(s) were left out." .Data.OmittedWorksheets) "Tone" "warning")}} |
| +{{end}} |
| + |
| +<section> |
| +<h2>What changed or was left out</h2> |
| +{{if .Data.Lines}} |
| +<ul data-import-report> |
| +{{range .Data.Lines}} |
| +<li> |
| +<p><strong>{{.Title}}</strong>: {{.Count}}</p> |
| +{{with .Detail}}<p>{{.}}</p>{{end}} |
| +{{if .Cells}}<p rst-field-help>Cells: {{range $i, $c := .Cells}}{{if $i}}, {{end}}{{$c}}{{end}}{{if .More}}, and {{.More}} more{{end}}.</p>{{end}} |
| +</li> |
| +{{end}} |
| +</ul> |
| +{{else}} |
| +<p>Nothing else was detected. Anything not listed under "What import |
| +carries" did not come across.</p> |
| +{{end}} |
| +</section> |
| +{{end}} |
diff --git a/internal/sheets/templates/sheet.html b/internal/sheets/templates/sheet.html| index e164468..fed9d8d 100644 |
| --- a/internal/sheets/templates/sheet.html |
| +++ b/internal/sheets/templates/sheet.html |
| @@ -120,6 +120,7 @@ |
| <hr> |
| <a estilo-menu-item href="/sheets/{{.Data.Sheet.ID}}/table"><span estilo-menu-label>Open as table</span></a> |
| <a estilo-menu-item href="/sheets/{{.Data.Sheet.ID}}/history"><span estilo-menu-label>Version history</span></a> |
| +{{if .Data.ImportReport}}<a estilo-menu-item href="/sheets/{{.Data.Sheet.ID}}/import-report"><span estilo-menu-label>Import report</span></a>{{end}} |
| {{if .Data.MayShare}}<a estilo-menu-item href="/sheets/{{.Data.Sheet.ID}}/share"><span estilo-menu-label>Share…</span></a>{{end}} |
| </div> |
| </details> |
diff --git a/internal/sheets/xlsx/agree_test.go b/internal/sheets/xlsx/agree_test.go| new file mode 100644 |
| index 0000000..bd80bbf |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/agree_test.go |
| @@ -0,0 +1,34 @@ |
| +package xlsx |
| + |
| +import ( |
| + "errors" |
| + "testing" |
| + |
| + "github.com/xuri/excelize/v2" |
| +) |
| + |
| +// agree is the check that keeps either reader from supplying a value |
| +// alone. Both read the same bytes, so a real workbook rarely makes |
| +// them differ; this drives the check directly with a scan that says |
| +// something excelize does not. |
| +func TestAgreeRefusesAScanExcelizeDoesNotConfirm(t *testing.T) { |
| + f := excelize.NewFile() |
| + defer f.Close() |
| + sheet := f.GetSheetList()[0] |
| + if err := f.SetCellFormula(sheet, "A1", "FOO(1)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + im := &importer{f: f, sheet: sheet} |
| + for name, sc := range map[string]scannedCell{ |
| + "a saved value excelize did not read": {HasF: true, T: "str", HasV: true, V: "3"}, |
| + "a declared type excelize did not read": {HasF: true, T: "b"}, |
| + } { |
| + if err := im.agree("A1", sc); !errors.Is(err, errScanInconsistent) { |
| + t.Errorf("%s: agree = %v, want errScanInconsistent", name, err) |
| + } |
| + } |
| + // excelize holds a formula it was given in memory as t="str". |
| + if err := im.agree("A1", scannedCell{HasF: true, T: "str"}); err != nil { |
| + t.Errorf("matching scan: agree = %v, want nil", err) |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/blob.go b/internal/sheets/xlsx/blob.go| index 7911f77..a3473c8 100644 |
| --- a/internal/sheets/xlsx/blob.go |
| +++ b/internal/sheets/xlsx/blob.go |
| @@ -48,11 +48,12 @@ func StoreSealed(ctx context.Context, underlying blobs.Store, key []byte, h *sto |
| } |
| // LoadSealed reads a blob written by StoreSealed (or any XLSX blob sealed |
| -// under key with blobs.Sealed) and imports it into h. |
| -func LoadSealed(ctx context.Context, underlying blobs.Store, key []byte, ref blobs.Ref, h *store.Handle) error { |
| +// under key with blobs.Sealed) and imports it into h, with Import's |
| +// report. |
| +func LoadSealed(ctx context.Context, underlying blobs.Store, key []byte, ref blobs.Ref, h *store.Handle) (Report, error) { |
| rc, err := blobs.Sealed(underlying, key).Get(ctx, ref.Hash) |
| if err != nil { |
| - return fmt.Errorf("xlsx: load sealed import: %w", err) |
| + return Report{}, fmt.Errorf("xlsx: load sealed import: %w", err) |
| } |
| defer rc.Close() |
| return Import(rc, h) |
diff --git a/internal/sheets/xlsx/blob_test.go b/internal/sheets/xlsx/blob_test.go| index 5e59a43..313e07a 100644 |
| --- a/internal/sheets/xlsx/blob_test.go |
| +++ b/internal/sheets/xlsx/blob_test.go |
| @@ -83,7 +83,7 @@ func TestStoreSealedNeverWritesPlaintext(t *testing.T) { |
| // And the round trip itself must still work: LoadSealed recovers |
| // exactly what was stored. |
| h2 := newTab(t, db, testSealer(t)) |
| - if err := xlsx.LoadSealed(context.Background(), underlying, key, ref, h2); err != nil { |
| + if _, err := xlsx.LoadSealed(context.Background(), underlying, key, ref, h2); err != nil { |
| t.Fatalf("LoadSealed: %v", err) |
| } |
| rowID2, colID2, ok := cellAt(h2, 0, 0) |
diff --git a/internal/sheets/xlsx/cell.go b/internal/sheets/xlsx/cell.go| new file mode 100644 |
| index 0000000..e358732 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/cell.go |
| @@ -0,0 +1,247 @@ |
| +package xlsx |
| + |
| +import ( |
| + "errors" |
| + "math" |
| + "strconv" |
| + |
| + "github.com/xuri/excelize/v2" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +// importer carries one import's state across its cells. |
| +type importer struct { |
| + f *excelize.File |
| + sheet string |
| + h *store.Handle |
| + scan *sheetScan |
| + base *excelize.Style |
| + rep *Report |
| + kept []keptFormula |
| + // capped is set when any write's recalculation was too wide to |
| + // run (calc.MaxDirtyPerPass): its dependents stay dirty until the |
| + // tab is next opened, so no value read during this import can be |
| + // trusted as final. |
| + capped bool |
| +} |
| + |
| +// keptFormula is a formula written as a formula, remembered so its |
| +// result can be compared with its saved value once every cell it could |
| +// depend on has been written. |
| +type keptFormula struct { |
| + pos posKey |
| + rowID, colID uint64 |
| + saved scannedCell |
| + volatile bool |
| +} |
| + |
| +// Refusals a cell can cause. Each becomes a CellError, so the |
| +// coordinate is data and the cause stays out of the error's text. |
| +var ( |
| + errTextTooLong = errors.New("xlsx: text needs a wrapper past the input limit") |
| + errCellIsError = errors.New("xlsx: cell holds an error value") |
| + errCellNotNumber = errors.New("xlsx: number cell is not a finite number") |
| + errCellType = errors.New("xlsx: cell type is not one import reads") |
| +) |
| + |
| +// cell imports one position. It creates the backing Row/Col only if |
| +// the cell has content or a format worth recording — an interior blank |
| +// cell with neither leaves no trace, matching the sparse model |
| +// (models.go's comment on Cell). |
| +func (im *importer) cell(p posKey, raw string) error { |
| + ref, err := excelize.CoordinatesToCellName(p.Col+1, p.Row+1) |
| + if err != nil { |
| + return cellErr("cannot address cell", p.Row, p.Col, err) |
| + } |
| + formula, err := im.f.GetCellFormula(im.sheet, ref) |
| + if err != nil { |
| + return cellErr("cannot read the formula at", p.Row, p.Col, err) |
| + } |
| + sc, scanned := im.scan.Cells[p] |
| + if (formula != "") != (scanned && sc.HasF) { |
| + return cellErr("the workbook's parts disagree at", p.Row, p.Col, errScanInconsistent) |
| + } |
| + if scanned { |
| + if err := im.agree(ref, sc); err != nil { |
| + return cellErr("the workbook's parts disagree at", p.Row, p.Col, err) |
| + } |
| + } |
| + |
| + var ( |
| + input string |
| + cls formulaClass |
| + ) |
| + if formula != "" { |
| + cls = classify(formula, sc.FType) |
| + input, err = im.formulaInput(p, formula, cls, sc) |
| + } else { |
| + input, err = im.literalInput(p, ref, raw, sc, scanned) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + |
| + styleID, err := im.f.GetCellStyle(im.sheet, ref) |
| + if err != nil { |
| + return cellErr("cannot read the style at", p.Row, p.Col, err) |
| + } |
| + style, err := im.f.GetStyle(styleID) |
| + if err != nil { |
| + return cellErr("cannot read the style at", p.Row, p.Col, err) |
| + } |
| + format, hasFormat := formatFromStyle(style) |
| + if input == "" && !hasFormat { |
| + return nil // nothing here worth a Row/Col at all |
| + } |
| + if partialStyle(style, im.base) { |
| + im.rep.cell(FormatPartial, p.Row, p.Col) |
| + } |
| + |
| + rowID, err := im.h.EnsureRow(p.Row) |
| + if err != nil { |
| + return cellErr("cannot make the row for cell", p.Row, p.Col, err) |
| + } |
| + colID, err := im.h.EnsureCol(p.Col) |
| + if err != nil { |
| + return cellErr("cannot make the column for cell", p.Row, p.Col, err) |
| + } |
| + if input != "" { |
| + rep, err := im.h.SetReport(rowID, colID, input, importActor) |
| + if err != nil { |
| + return cellErr("cannot parse cell", p.Row, p.Col, err) |
| + } |
| + im.capped = im.capped || rep.Capped |
| + } |
| + if hasFormat { |
| + if err := im.h.SetFormat(rowID, colID, format); err != nil { |
| + return cellErr("cannot set the format at", p.Row, p.Col, err) |
| + } |
| + } |
| + if formula != "" && cls.Supported { |
| + im.kept = append(im.kept, keptFormula{pos: p, rowID: rowID, colID: colID, |
| + saved: sc, volatile: cls.Volatile}) |
| + } |
| + return nil |
| +} |
| + |
| +// formulaInput is a formula cell's raw input: the formula itself when |
| +// it is supported, otherwise its saved value, reported. |
| +func (im *importer) formulaInput(p posKey, formula string, cls formulaClass, sc scannedCell) (string, error) { |
| + if cls.Supported { |
| + return "=" + formula, nil |
| + } |
| + v, err := savedValue(sc) |
| + if err != nil { |
| + return "", cellErr("a formula has no usable saved value at", p.Row, p.Col, err) |
| + } |
| + input, wrapped := frozenInput(v) |
| + if wrapped && len(input) > store.MaxInputBytes { |
| + return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong) |
| + } |
| + im.rep.cell(cls.Code, p.Row, p.Col) |
| + if wrapped { |
| + im.rep.cell(TextKept, p.Row, p.Col) |
| + } |
| + return input, nil |
| +} |
| + |
| +// literalInput is a non-formula cell's raw input, typed by what the |
| +// workbook declared the cell to be rather than by what its text looks |
| +// like. |
| +func (im *importer) literalInput(p posKey, ref, raw string, sc scannedCell, scanned bool) (string, error) { |
| + cellType, err := im.f.GetCellType(im.sheet, ref) |
| + if err != nil { |
| + return "", cellErr("cannot read the cell type at", p.Row, p.Col, err) |
| + } |
| + switch cellType { |
| + case excelize.CellTypeSharedString, excelize.CellTypeInlineString, excelize.CellTypeFormula: |
| + // Text. An empty string is text too, where the workbook wrote |
| + // one: an inline string, or a <v> the scan saw. |
| + if raw == "" && !(scanned && (sc.HasV || sc.T == "inlineStr")) { |
| + return "", nil |
| + } |
| + input, wrapped := store.TextInput(raw) |
| + if wrapped { |
| + if len(input) > store.MaxInputBytes { |
| + return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong) |
| + } |
| + im.rep.cell(TextKept, p.Row, p.Col) |
| + } |
| + return input, nil |
| + case excelize.CellTypeBool: |
| + switch raw { |
| + case "1": |
| + return "TRUE", nil |
| + case "0": |
| + return "FALSE", nil |
| + } |
| + return "", cellErr("cannot read the boolean at", p.Row, p.Col, errCellType) |
| + case excelize.CellTypeUnset, excelize.CellTypeNumber: |
| + if raw == "" { |
| + return "", nil |
| + } |
| + n, err := strconv.ParseFloat(raw, 64) |
| + if err != nil || math.IsNaN(n) || math.IsInf(n, 0) { |
| + return "", cellErr("cannot read the number at", p.Row, p.Col, errCellNotNumber) |
| + } |
| + return raw, nil |
| + case excelize.CellTypeError: |
| + return "", cellErr("a cell holds an error value at", p.Row, p.Col, errCellIsError) |
| + } |
| + return "", cellErr("cannot read the cell type at", p.Row, p.Col, errCellType) |
| +} |
| + |
| +// compare checks every kept formula against the value its workbook |
| +// saved, after the last cell is written so each result is final. |
| +// |
| +// Final only if no write was capped. A capped write leaves dependents |
| +// dirty until the tab is next opened, and a stale value could match or |
| +// miss a saved one by accident, so then nothing is compared: every |
| +// kept formula is reported unchecked instead. |
| +func (im *importer) compare() { |
| + for _, k := range im.kept { |
| + saved, ok := comparableSaved(k.saved) |
| + if !ok || k.volatile || im.capped { |
| + im.rep.cell(FormulaUnchecked, k.pos.Row, k.pos.Col) |
| + continue |
| + } |
| + if !sameValue(im.h.Value(k.rowID, k.colID), saved) { |
| + im.rep.cell(FormulaDiffers, k.pos.Row, k.pos.Col) |
| + } |
| + } |
| +} |
| + |
| +// scanTypes maps a c element's t to excelize's reading of it, absent |
| +// and unknown both reading as Unset, as excelize's own table does. |
| +var scanTypes = map[string]excelize.CellType{ |
| + "b": excelize.CellTypeBool, "d": excelize.CellTypeDate, "n": excelize.CellTypeNumber, |
| + "e": excelize.CellTypeError, "s": excelize.CellTypeSharedString, |
| + "str": excelize.CellTypeFormula, "inlineStr": excelize.CellTypeInlineString, |
| +} |
| + |
| +// agree checks that excelize read a scanned cell as the scan did: the |
| +// same declared type and, for a formula whose <v> is the value itself |
| +// rather than an index or a date, the same saved value. Either reader |
| +// could be the one that is wrong; a disagreement stops the import |
| +// rather than let one of them quietly supply the value. |
| +func (im *importer) agree(ref string, sc scannedCell) error { |
| + cellType, err := im.f.GetCellType(im.sheet, ref) |
| + if err != nil { |
| + return err |
| + } |
| + if cellType != scanTypes[sc.T] { |
| + return errScanInconsistent |
| + } |
| + if !sc.HasF || sc.T == "s" || sc.T == "inlineStr" || sc.T == "d" { |
| + return nil |
| + } |
| + raw, err := im.f.GetCellValue(im.sheet, ref, excelize.Options{RawCellValue: true}) |
| + if err != nil { |
| + return err |
| + } |
| + if raw != sc.V { |
| + return errScanInconsistent |
| + } |
| + return nil |
| +} |
diff --git a/internal/sheets/xlsx/classify.go b/internal/sheets/xlsx/classify.go| new file mode 100644 |
| index 0000000..b38ea96 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/classify.go |
| @@ -0,0 +1,70 @@ |
| +package xlsx |
| + |
| +import ( |
| + "strings" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| +) |
| + |
| +// formulaClass is what import decides about one workbook formula. |
| +type formulaClass struct { |
| + // Supported is true when the formula is kept as a formula: it |
| + // parses, and every function it calls is one this engine has. |
| + Supported bool |
| + // Volatile is true when a kept formula reads the clock, so its |
| + // saved value was computed at another moment and is not compared. |
| + Volatile bool |
| + // Code says why an unsupported formula is not kept. |
| + Code Code |
| +} |
| + |
| +// classify decides whether formula (excelize's text, no leading "=") |
| +// stays a formula, given the type its <f> element declared. |
| +// |
| +// Order matters only for which reason a report names; any one of them |
| +// is enough to freeze the cell. The textual checks come before the |
| +// parser on purpose: a sheet-qualified or external reference must not |
| +// be kept even if a later parser learned to read one, because only |
| +// the first worksheet comes across and the reference would point at |
| +// nothing. |
| +func classify(formula, fType string) formulaClass { |
| + if fType == "array" || fType == "dataTable" { |
| + return formulaClass{Code: FormulaArray} |
| + } |
| + bare := outsideStrings(formula) |
| + if strings.Contains(strings.ToUpper(bare), "__XLUDF.") { |
| + return formulaClass{Code: FormulaGoogleOnly} |
| + } |
| + if strings.ContainsAny(bare, "![") { |
| + return formulaClass{Code: FormulaOtherSheet} |
| + } |
| + node, err := calc.Parse(formula) |
| + if err != nil { |
| + return formulaClass{Code: FormulaUnsupported} |
| + } |
| + in := calc.Inspect(node) |
| + if in.Unknown { |
| + return formulaClass{Code: FormulaUnsupported} |
| + } |
| + return formulaClass{Supported: true, Volatile: in.Volatile} |
| +} |
| + |
| +// outsideStrings is formula with the contents of its double-quoted |
| +// string constants removed, so text inside a string ("Sheet2!A1" as a |
| +// label) cannot read as a reference. A doubled quote inside a string |
| +// toggles twice and so stays inside it. |
| +func outsideStrings(formula string) string { |
| + var b strings.Builder |
| + in := false |
| + for i := 0; i < len(formula); i++ { |
| + c := formula[i] |
| + if c == '"' { |
| + in = !in |
| + continue |
| + } |
| + if !in { |
| + b.WriteByte(c) |
| + } |
| + } |
| + return b.String() |
| +} |
diff --git a/internal/sheets/xlsx/currency_test.go b/internal/sheets/xlsx/currency_test.go| new file mode 100644 |
| index 0000000..47fe3eb |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/currency_test.go |
| @@ -0,0 +1,54 @@ |
| +package xlsx_test |
| + |
| +import ( |
| + "bytes" |
| + "testing" |
| + |
| + "github.com/xuri/excelize/v2" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/format" |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// Synthetic workbook: retain Google's currency code and numeric value |
| +// across import/export, while displaying the symbol rather than its syntax. |
| +func TestImportedGoogleCurrencyDisplayAndRoundTrip(t *testing.T) { |
| + f := excelize.NewFile() |
| + defer f.Close() |
| + code := `[$€]#,##0.00` |
| + style, err := f.NewStyle(&excelize.Style{CustomNumFmt: &code}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.SetCellValue("Sheet1", "A1", 1234.5); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil { |
| + t.Fatal(err) |
| + } |
| + buf, err := f.WriteToBuffer() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + first := importReader(t, buf) |
| + var exported bytes.Buffer |
| + if err := xlsx.Export(first, &exported); err != nil { |
| + t.Fatal(err) |
| + } |
| + second := importReader(t, &exported) |
| + if diff := diffTabs(t, first, second); diff != "" { |
| + t.Fatalf("currency round trip changed cells: %s", diff) |
| + } |
| + styleOut := formatOf(t, second, 0, 0) |
| + if styleOut.NumberFmt != code { |
| + t.Fatalf("currency format changed: %q", styleOut.NumberFmt) |
| + } |
| + row, col, ok := cellAt(second, 0, 0) |
| + if !ok { |
| + t.Fatal("missing imported cell") |
| + } |
| + value := second.Value(row, col) |
| + if value.Num != 1234.5 || format.Display(value, styleOut.NumberFmt) != "€1,234.50" { |
| + t.Fatalf("currency value or display changed: %+v", value) |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/helpers_test.go b/internal/sheets/xlsx/helpers_test.go| index c3cc600..6b69924 100644 |
| --- a/internal/sheets/xlsx/helpers_test.go |
| +++ b/internal/sheets/xlsx/helpers_test.go |
| @@ -115,7 +115,7 @@ func importReader(t *testing.T, r io.Reader) *store.Handle { |
| t.Helper() |
| db := openTestDB(t) |
| h := newTab(t, db, testSealer(t)) |
| - if err := xlsx.Import(r, h); err != nil { |
| + if _, err := xlsx.Import(r, h); err != nil { |
| t.Fatalf("Import: %v", err) |
| } |
| return h |
diff --git a/internal/sheets/xlsx/import.go b/internal/sheets/xlsx/import.go| index 2c90676..eba8a44 100644 |
| --- a/internal/sheets/xlsx/import.go |
| +++ b/internal/sheets/xlsx/import.go |
| @@ -6,9 +6,11 @@ |
| package xlsx |
| import ( |
| + "bytes" |
| "errors" |
| "fmt" |
| "io" |
| + "sort" |
| "github.com/xuri/excelize/v2" |
| @@ -55,152 +57,124 @@ var openLimits = excelize.Options{ |
| UnzipXMLSizeLimit: 64 << 20, |
| } |
| -// Import reads an XLSX workbook's first worksheet into h, cell by cell: |
| -// literal values become literal input, formulas are parsed and |
| -// evaluated by this app's own engine (never excelize's — see the package |
| -// doc), and each cell's fill, number format, bold, italic and alignment |
| -// are carried over via SetFormat. |
| +// maxWorkbookBytes bounds what Import reads from r. The upload handler |
| +// caps a file at 20 MB; this is the converter's own bound, since both |
| +// excelize and the worksheet scan need the whole file in memory. |
| +const maxWorkbookBytes = 32 << 20 |
| + |
| +// Import reads an XLSX workbook's first worksheet into h and reports |
| +// what it changed or left behind. |
| +// |
| +// Literal values become literal input; text that would otherwise read |
| +// as something else is kept as text (store.TextInput). A formula is |
| +// kept when this app's own engine can calculate it (never excelize's — |
| +// see the package doc), and its result is compared with the value the |
| +// workbook saved. Any other formula is replaced by its saved value, and |
| +// a formula with no trustworthy saved value refuses the whole import: |
| +// a value is never manufactured. Fill, number format, bold, italic, |
| +// ink and alignment are carried over via SetFormat. |
| // |
| // Errors carry coordinates and codes, never cell content (spec §2.4): |
| // import runs as a background job whose error text reaches the owner and |
| // platform logs this app cannot grep, so "cannot parse cell B7" is what |
| // gets said — never what B7 actually contained. |
| -func Import(r io.Reader, h *store.Handle) error { |
| - f, err := excelize.OpenReader(r, openLimits) |
| +func Import(r io.Reader, h *store.Handle) (Report, error) { |
| + data, err := io.ReadAll(io.LimitReader(r, maxWorkbookBytes+1)) |
| + if err != nil { |
| + return Report{}, fmt.Errorf("xlsx: read workbook: %w", err) |
| + } |
| + if len(data) > maxWorkbookBytes { |
| + return Report{}, errScanLimit |
| + } |
| + f, err := excelize.OpenReader(bytes.NewReader(data), openLimits) |
| if err != nil { |
| - return fmt.Errorf("xlsx: open workbook: %w", err) |
| + return Report{}, fmt.Errorf("xlsx: open workbook: %w", err) |
| } |
| defer f.Close() |
| sheetList := f.GetSheetList() |
| if len(sheetList) == 0 { |
| - return errors.New("xlsx: workbook has no worksheets") |
| + return Report{}, errors.New("xlsx: workbook has no worksheets") |
| } |
| sheetName := sheetList[0] |
| + // The second reader: what the worksheet XML itself says about |
| + // formulas and their saved values. It must name the same first |
| + // sheet excelize does, or neither is trusted. |
| + scan, err := scanWorkbook(data) |
| + if err != nil { |
| + return Report{}, fmt.Errorf("xlsx: scan worksheet: %w", err) |
| + } |
| + if scan.Name != sheetName { |
| + return Report{}, errScanInconsistent |
| + } |
| + |
| rows, err := f.GetRows(sheetName, excelize.Options{RawCellValue: true}) |
| if err != nil { |
| - return fmt.Errorf("xlsx: read worksheet: %w", err) |
| + return Report{}, fmt.Errorf("xlsx: read worksheet: %w", err) |
| } |
| // Fail before writing anything: a partial import left behind by |
| - // hitting the cap mid-way through would be a confusing half state, |
| - // and the bounding box is a cheap, conservative upper bound on the |
| - // cell count to check it against up front. |
| - total := 0 |
| - for _, row := range rows { |
| - total += len(row) |
| - } |
| - if total > store.MaxCellsPerTab { |
| - return store.ErrTabTooLarge |
| + // hitting the cap mid-way through would be a confusing half state. |
| + positions := cellPositions(rows, scan) |
| + if len(positions) > store.MaxCellsPerTab { |
| + return Report{}, store.ErrTabTooLarge |
| } |
| - for rowPos, row := range rows { |
| - for colPos, raw := range row { |
| - if err := importCell(f, sheetName, h, rowPos, colPos, raw); err != nil { |
| - return err |
| - } |
| + base, err := f.GetStyle(0) |
| + if err != nil { |
| + return Report{}, fmt.Errorf("xlsx: read the default style: %w", err) |
| + } |
| + im := &importer{f: f, sheet: sheetName, h: h, scan: scan, base: base, |
| + rep: &Report{Worksheets: len(sheetList)}} |
| + for _, p := range positions { |
| + raw := "" |
| + if p.Row < len(rows) && p.Col < len(rows[p.Row]) { |
| + raw = rows[p.Row][p.Col] |
| + } |
| + if err := im.cell(p, raw); err != nil { |
| + return Report{}, err |
| } |
| } |
| + im.compare() |
| + reportOmissions(f, sheetName, scan, im.rep) |
| // Layout last, and best effort. A workbook whose widths cannot be |
| // read is still a workbook whose cells can, and refusing the import |
| // over its margins would trade the document for its formatting. |
| widest := 0 |
| - for _, row := range rows { |
| - if len(row) > widest { |
| - widest = len(row) |
| - } |
| + for _, p := range positions { |
| + widest = max(widest, p.Col+1) |
| } |
| importSizes(f, sheetName, h, len(rows), widest) |
| - return nil |
| + return *im.rep, nil |
| } |
| -// importCell imports one XLSX cell at (rowPos, colPos) (0-based). It |
| -// creates the backing Row/Col only if the cell actually has content or a |
| -// format worth recording — an interior blank cell with neither leaves no |
| -// trace, matching the sparse model (models.go's comment on Cell). |
| -func importCell(f *excelize.File, sheetName string, h *store.Handle, rowPos, colPos int, raw string) error { |
| - cellRef, err := excelize.CoordinatesToCellName(colPos+1, rowPos+1) |
| - if err != nil { |
| - return cellErr("cannot address cell", rowPos, colPos, err) |
| - } |
| - |
| - input, err := cellInputText(f, sheetName, cellRef, rowPos, colPos, raw) |
| - if err != nil { |
| - return err |
| - } |
| - |
| - styleID, err := f.GetCellStyle(sheetName, cellRef) |
| - if err != nil { |
| - return cellErr("cannot read the style at", rowPos, colPos, err) |
| - } |
| - style, err := f.GetStyle(styleID) |
| - if err != nil { |
| - return cellErr("cannot read the style at", rowPos, colPos, err) |
| - } |
| - format, hasFormat := formatFromStyle(style) |
| - |
| - if input == "" && !hasFormat { |
| - return nil // nothing here worth a Row/Col at all |
| - } |
| - |
| - rowID, err := h.EnsureRow(rowPos) |
| - if err != nil { |
| - return cellErr("cannot make the row for cell", rowPos, colPos, err) |
| - } |
| - colID, err := h.EnsureCol(colPos) |
| - if err != nil { |
| - return cellErr("cannot make the column for cell", rowPos, colPos, err) |
| - } |
| - |
| - if input != "" { |
| - if err := h.Set(rowID, colID, input, importActor); err != nil { |
| - return cellErr("cannot parse cell", rowPos, colPos, err) |
| +// cellPositions is every position import visits, in row-major order: |
| +// each cell excelize's row reader returned, plus each formula or |
| +// string cell the scan found. The second half matters because the row |
| +// reader drops empty values from the end of a row, and a formula whose |
| +// saved value is "" or an empty-string text cell is not nothing. |
| +func cellPositions(rows [][]string, scan *sheetScan) []posKey { |
| + seen := make(map[posKey]bool, len(scan.Cells)) |
| + var out []posKey |
| + for r, row := range rows { |
| + for c := range row { |
| + p := posKey{Row: r, Col: c} |
| + seen[p] = true |
| + out = append(out, p) |
| } |
| } |
| - if hasFormat { |
| - if err := h.SetFormat(rowID, colID, format); err != nil { |
| - return cellErr("cannot set the format at", rowPos, colPos, err) |
| + for p := range scan.Cells { |
| + if !seen[p] { |
| + out = append(out, p) |
| } |
| } |
| - return nil |
| -} |
| - |
| -// cellInputText decides what raw text (this app's own Set contract: |
| -// "" is blank, a leading "=" is a formula, anything else is a literal — |
| -// store/handle_codec.go) a cell becomes. |
| -// |
| -// A genuine XLSX formula is detected through excelize's own formula |
| -// reader, never by sniffing raw's leading character — but a plain TEXT |
| -// cell whose content happens to start with "=" is indistinguishable from |
| -// a formula once it becomes this app's raw text, because Set's contract |
| -// (predating this task — store/handle_codec.go, task 10) has exactly one |
| -// signal for "is this a formula": a leading "=" in the one text field a |
| -// cell has. That is a pre-existing modeling gap this task inherits, not |
| -// one introduced by XLSX import; it is called out in the task report |
| -// rather than worked around here. |
| -func cellInputText(f *excelize.File, sheetName, cellRef string, rowPos, colPos int, raw string) (string, error) { |
| - formula, err := f.GetCellFormula(sheetName, cellRef) |
| - if err != nil { |
| - return "", cellErr("cannot read the formula at", rowPos, colPos, err) |
| - } |
| - if formula != "" { |
| - return "=" + formula, nil |
| - } |
| - if raw == "" { |
| - return "", nil |
| - } |
| - |
| - cellType, err := f.GetCellType(sheetName, cellRef) |
| - if err != nil { |
| - return "", cellErr("cannot read the cell type at", rowPos, colPos, err) |
| - } |
| - if cellType == excelize.CellTypeBool { |
| - if raw == "1" { |
| - return "TRUE", nil |
| + sort.Slice(out, func(i, j int) bool { |
| + if out[i].Row != out[j].Row { |
| + return out[i].Row < out[j].Row |
| } |
| - return "FALSE", nil |
| - } |
| - return raw, nil |
| + return out[i].Col < out[j].Col |
| + }) |
| + return out |
| } |
diff --git a/internal/sheets/xlsx/import_omissions_test.go b/internal/sheets/xlsx/import_omissions_test.go| new file mode 100644 |
| index 0000000..9b07670 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/import_omissions_test.go |
| @@ -0,0 +1,105 @@ |
| +package xlsx_test |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "image" |
| + "image/png" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/xuri/excelize/v2" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// featureBook is a workbook carrying one of each feature the import |
| +// leaves behind, built with excelize so each is written the way a real |
| +// spreadsheet writes it. |
| +func featureBook(t *testing.T) *bytes.Buffer { |
| + t.Helper() |
| + f := excelize.NewFile() |
| + s := f.GetSheetList()[0] |
| + must := func(err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i, v := range []float64{1, 2, 3} { |
| + cell, _ := excelize.CoordinatesToCellName(1, i+1) |
| + must(f.SetCellFloat(s, cell, v, -1, 64)) |
| + } |
| + must(f.SetCellStr(s, "B1", canary)) |
| + must(f.MergeCell(s, "B1", "C1")) |
| + must(f.AddComment(s, excelize.Comment{Cell: "A1", Author: "a", Text: canary})) |
| + dv := excelize.NewDataValidation(true) |
| + dv.Sqref = "A1:A3" |
| + must(dv.SetDropList([]string{"1", "2"})) |
| + must(f.AddDataValidation(s, dv)) |
| + style, err := f.NewConditionalStyle(&excelize.Style{Font: &excelize.Font{Bold: true}}) |
| + must(err) |
| + must(f.SetConditionalFormat(s, "A1:A3", []excelize.ConditionalFormatOptions{ |
| + {Type: "cell", Criteria: ">", Format: &style, Value: "1"}})) |
| + must(f.SetCellHyperLink(s, "A2", "https://example.com/"+canary, "External")) |
| + must(f.SetDefinedName(&excelize.DefinedName{Name: "TaxRate", RefersTo: s + "!$A$1"})) |
| + must(f.SetRowVisible(s, 3, false)) |
| + must(f.SetColVisible(s, "D", false)) |
| + must(f.SetPanes(s, &excelize.Panes{Freeze: true, YSplit: 1, TopLeftCell: "A2", ActivePane: "bottomLeft"})) |
| + must(f.AutoFilter(s, "A1:A3", nil)) |
| + var img bytes.Buffer |
| + must(png.Encode(&img, image.NewRGBA(image.Rect(0, 0, 2, 2)))) |
| + must(f.AddPictureFromBytes(s, "E1", &excelize.Picture{Extension: ".png", File: img.Bytes()})) |
| + must(f.AddChart(s, "G1", &excelize.Chart{Type: excelize.Col, Series: []excelize.ChartSeries{ |
| + {Name: s + "!$A$1", Values: s + "!$A$1:$A$3"}}})) |
| + border, err := f.NewStyle(&excelize.Style{Border: []excelize.Border{{Type: "left", Color: "000000", Style: 1}}}) |
| + must(err) |
| + must(f.SetCellStyle(s, "A3", "A3", border)) |
| + for _, name := range []string{"Second", "Third"} { |
| + if _, err := f.NewSheet(name); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var buf bytes.Buffer |
| + must(f.Write(&buf)) |
| + return &buf |
| +} |
| + |
| +func TestImportReportsWhatItLeavesBehind(t *testing.T) { |
| + h := newTab(t, openTestDB(t), testSealer(t)) |
| + rep, err := xlsx.Import(featureBook(t), h) |
| + if err != nil { |
| + t.Fatalf("Import: %v", err) |
| + } |
| + if rep.OmittedWorksheets() != 2 { |
| + t.Errorf("omitted worksheets = %d, want 2", rep.OmittedWorksheets()) |
| + } |
| + want := map[xlsx.Code]int{ |
| + xlsx.OmittedMerges: 1, xlsx.OmittedComments: 1, xlsx.OmittedValidation: 1, |
| + xlsx.OmittedConditional: 1, xlsx.OmittedHyperlinks: 1, xlsx.OmittedDefinedNames: 1, |
| + xlsx.OmittedHiddenRows: 1, xlsx.OmittedHiddenCols: 1, xlsx.OmittedFrozenPanes: 1, |
| + xlsx.OmittedFilter: 1, xlsx.OmittedPictures: 1, xlsx.OmittedWorkbookChart: 1, |
| + xlsx.OmittedWorkbookImage: 1, xlsx.FormatPartial: 1, |
| + } |
| + for code, n := range want { |
| + if got := entry(rep, code); got.Count != n { |
| + t.Logf("%s cells %v", code, got.Cells) |
| + t.Errorf("%s = %d, want %d", code, got.Count, n) |
| + } |
| + } |
| + if got := entry(rep, xlsx.OmittedUndetected).Count; got != 0 { |
| + t.Errorf("undetected = %d, want every detector to have read its part", got) |
| + } |
| + |
| + // The report is codes, coordinates and counts. No text from the |
| + // workbook reaches it — not a cell, a comment, a link or a name. |
| + body, err := json.Marshal(rep) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, leak := range []string{canary, "TaxRate", "example.com", "Second", "Sheet1"} { |
| + if strings.Contains(string(body), leak) { |
| + t.Errorf("report carries %q: %s", leak, body) |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/import_refusals_test.go b/internal/sheets/xlsx/import_refusals_test.go| new file mode 100644 |
| index 0000000..6d6b29e |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/import_refusals_test.go |
| @@ -0,0 +1,114 @@ |
| +package xlsx_test |
| + |
| +import ( |
| + "errors" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// canary is content no refusal may repeat. |
| +const canary = "SECRET-LEDGER-7731" |
| + |
| +// Each workbook here must refuse the whole import. Where the cell is |
| +// known, the refusal names it as data (xlsx.CellError) and its text |
| +// carries the coordinate and nothing the cell held. |
| +func TestImportRefusesWhatItCannotTrust(t *testing.T) { |
| + long := strings.Repeat("x", 9000) |
| + cases := []struct { |
| + name string |
| + book rawBook |
| + ref string // "" when the refusal precedes any one cell |
| + }{ |
| + {"unsupported formula without a saved value", |
| + rawBook{sheets: []string{row(1, formula("A1", "", `FOO("`+canary+`")`, nil))}}, "A1"}, |
| + {"unsupported formula that saved an error", |
| + rawBook{sheets: []string{row(1, formula("A1", "e", `FOO("`+canary+`")`, ptr("#N/A")))}}, "A1"}, |
| + {"unsupported formula that saved a shared-string index", |
| + rawBook{sheets: []string{row(1, formula("A1", "s", "FOO(1)", ptr("0")))}}, "A1"}, |
| + {"unsupported formula that saved a non-number", |
| + rawBook{sheets: []string{row(1, formula("A1", "", "FOO(1)", ptr(canary)))}}, "A1"}, |
| + {"unsupported formula that saved an infinite number", |
| + rawBook{sheets: []string{row(1, formula("A1", "", "FOO(1)", ptr("1e999")))}}, "A1"}, |
| + {"unsupported formula that saved a boolean other than 0 or 1", |
| + rawBook{sheets: []string{row(1, formula("A1", "b", "FOO(1)", ptr("2")))}}, "A1"}, |
| + {"unsupported formula that saved a date", |
| + rawBook{sheets: []string{row(1, formula("A1", "d", "FOO(1)", ptr("2026-11-01")))}}, "A1"}, |
| + {"a literal error value", |
| + rawBook{sheets: []string{row(1, `<c r="A1" t="e"><v>#N/A</v></c>`)}}, "A1"}, |
| + {"a number cell that is not a number", |
| + rawBook{sheets: []string{row(1, num("A1", canary))}}, "A1"}, |
| + {"ambiguous text past the input limit once wrapped", |
| + rawBook{sheets: []string{row(1, inline("A1", "="+long))}}, "A1"}, |
| + {"a frozen saved string past the input limit once wrapped", |
| + rawBook{sheets: []string{row(1, formula("A1", "str", "FOO(1)", ptr("="+long)))}}, "A1"}, |
| + {"a shared formula follower whose master is missing", |
| + rawBook{sheets: []string{row(1, `<c r="A1"><f t="shared" si="5"/><v>1</v></c>`)}}, "A1"}, |
| + {"a cell written twice", |
| + rawBook{sheets: []string{row(1, num("A1", "1"), formula("A1", "", "FOO(1)", ptr("2")))}}, ""}, |
| + {"a cell written twice in different case", |
| + rawBook{sheets: []string{row(1, num("A1", "1"), num("a1", "2"))}}, ""}, |
| + {"a cell with two formulas", |
| + rawBook{sheets: []string{row(1, `<c r="A1"><f>1+1</f><f>FOO(1)</f><v>2</v></c>`)}}, ""}, |
| + {"a cell with two saved values", |
| + rawBook{sheets: []string{row(1, `<c r="A1"><f>FOO(1)</f><v>2</v><v>3</v></c>`)}}, ""}, |
| + {"a formula of a type the standard does not define", |
| + rawBook{sheets: []string{row(1, `<c r="A1"><f t="bogus">1+1</f><v>2</v></c>`)}}, ""}, |
| + {"a formula cell with no reference", |
| + rawBook{sheets: []string{`<row r="1"><c><f>FOO(1)</f><v>2</v></c></row>`}}, ""}, |
| + {"a formula cell filed under another row", |
| + rawBook{sheets: []string{row(1, formula("A5", "", "FOO(1)", ptr("2")))}}, ""}, |
| + {"nesting past the depth bound", |
| + rawBook{sheets: []string{row(1, num("A1", "1"))}, |
| + extra: `<extLst>` + strings.Repeat("<x>", 80) + strings.Repeat("</x>", 80) + `</extLst>`}, ""}, |
| + {"a chartsheet first", |
| + rawBook{sheets: []string{row(1, num("A1", "1"))}, parts: map[string]string{ |
| + "xl/_rels/workbook.xml.rels": `<?xml version="1.0" encoding="UTF-8"?> |
| +<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> |
| +<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="worksheets/sheet1.xml"/> |
| +<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/> |
| +</Relationships>`}}, ""}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + _, _, err := importRaw(t, c.book) |
| + if err == nil { |
| + t.Fatal("Import succeeded, want a refusal") |
| + } |
| + if strings.Contains(err.Error(), canary) || strings.Contains(err.Error(), "xxxx") { |
| + t.Fatalf("refusal carries cell content: %q", err.Error()) |
| + } |
| + var cell *xlsx.CellError |
| + if c.ref != "" && (!errors.As(err, &cell) || cell.Ref != c.ref) { |
| + t.Fatalf("refusal = %v, want a CellError at %s", err, c.ref) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A <c> or <v> anywhere but its own place in sheetData is not a cell |
| +// and not a saved value, for this reader as for excelize; a decoy |
| +// there must neither add a cell nor replace the real saved value. |
| +func TestImportIgnoresDecoysOutsideTheCellPath(t *testing.T) { |
| + book := rawBook{ |
| + sheets: []string{row(1, |
| + `<c r="A1"><f>FOO(1)</f><extLst><ext><v>9</v><c r="B1"><f>FOO(2)</f></c></ext></extLst><v>7</v></c>`)}, |
| + extra: `<extLst><ext><sheetData><row r="2"><c r="A2"><f>FOO(3)</f></c></row></sheetData></ext></extLst>`, |
| + } |
| + h, rep, err := importRaw(t, book) |
| + if err != nil { |
| + t.Fatalf("Import: %v", err) |
| + } |
| + if raw, v := cellByRef(t, h, "A1"); raw != "7" || v.Num != 7 { |
| + t.Errorf("A1 = %q %+v, want the saved 7", raw, v) |
| + } |
| + for _, ref := range []string{"B1", "A2"} { |
| + if raw, _ := cellByRef(t, h, ref); raw != "" { |
| + t.Errorf("%s = %q, want nothing: it was a decoy", ref, raw) |
| + } |
| + } |
| + if got := entry(rep, xlsx.FormulaUnsupported); got.Count != 1 { |
| + t.Errorf("unsupported = %+v, want A1 alone", got) |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/import_values_test.go b/internal/sheets/xlsx/import_values_test.go| new file mode 100644 |
| index 0000000..f612797 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/import_values_test.go |
| @@ -0,0 +1,161 @@ |
| +package xlsx_test |
| + |
| +import ( |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// googleBook is a first worksheet in the shapes a Google Sheets export |
| +// writes, with a second worksheet that must not come across. |
| +func googleBook() rawBook { |
| + return rawBook{sheets: []string{strings.Join([]string{ |
| + row(1, |
| + num("A1", "5"), |
| + formula("B1", "", "SUM(A1,1)", ptr("6")), |
| + `<c r="C1"><f t="shared" ref="C1:C2" si="0">$A$1+1</f><v>6</v></c>`, |
| + // Trailing, with an empty saved string: excelize's row |
| + // reader drops it, and it must still come across. |
| + formula("D1", "str", `IF(TRUE,"","x")`, ptr("")), |
| + ), |
| + row(2, |
| + inline("A2", "00123"), |
| + formula("B2", "", "A1*2", ptr("11")), |
| + `<c r="C2"><f t="shared" ref="C1:C2" si="0"/><v>6</v></c>`, |
| + inline("E2", ""), |
| + ), |
| + row(3, inline("A3", ""), formula("B3", "", "A1/3", ptr("1.66666666666667"))), |
| + row(4, inline("A4", "TRUE"), formula("B4", "", "Sheet2!A1", ptr("42"))), |
| + row(5, inline("A5", "=SUM(A1)"), |
| + formula("B5", "str", `IFERROR(__xludf.DUMMYFUNCTION("SPLIT(""a,007"","","")"),"a")`, ptr("a"))), |
| + row(6, inline("A6", "NaN"), |
| + formula("B6", "str", `IFERROR(__xludf.DUMMYFUNCTION("""COMPUTED_VALUE"""),"007")`, ptr("007"))), |
| + row(7, inline("A7", "hello"), `<c r="B7"><f t="array" ref="B7">SUM(A1*2)</f><v>10</v></c>`), |
| + row(8, `<c r="A8" t="b"><v>1</v></c>`, formula("B8", "str", "FOO(1)", ptr("x"))), |
| + row(9, formula("B9", "str", `IF(A1>0,"","x")`, ptr(""))), |
| + row(10, formula("B10", "b", "TaxRate*2", ptr("1"))), |
| + row(11, formula("B11", "", "NOW()", ptr("45000"))), |
| + row(12, formula("B12", "", "A1+1", nil)), |
| + row(13, formula("B13", "e", "1/0", ptr("#DIV/0!"))), |
| + row(14, formula("B14", "", "A99", ptr("0"))), |
| + }, ""), row(1, num("A1", "42"))}} |
| +} |
| + |
| +func TestImportKeepsTypedValuesAndFreezesWhatItCannotCalculate(t *testing.T) { |
| + h, rep, err := importRaw(t, googleBook()) |
| + if err != nil { |
| + t.Fatalf("Import: %v", err) |
| + } |
| + str := func(s string) calc.Value { return calc.Value{Kind: calc.KindStr, Str: s} } |
| + n := func(v float64) calc.Value { return calc.Value{Kind: calc.KindNum, Num: v} } |
| + cases := []struct { |
| + ref string |
| + raw string |
| + value calc.Value |
| + }{ |
| + {"A1", "5", n(5)}, |
| + {"A2", `="00123"`, str("00123")}, |
| + {"A3", `=""`, str("")}, |
| + {"A4", `="TRUE"`, str("TRUE")}, |
| + {"A5", `="=SUM(A1)"`, str("=SUM(A1)")}, |
| + {"A6", `="NaN"`, str("NaN")}, |
| + {"A7", "hello", str("hello")}, |
| + {"A8", "TRUE", calc.Value{Kind: calc.KindBool, Bool: true}}, |
| + {"B1", "=SUM(A1,1)", n(6)}, |
| + {"B2", "=A1*2", n(10)}, |
| + {"B4", "42", n(42)}, |
| + {"B5", "a", str("a")}, |
| + {"B6", `="007"`, str("007")}, |
| + {"B7", "10", n(10)}, |
| + {"B8", "x", str("x")}, |
| + {"B9", `=IF(A1>0,"","x")`, str("")}, |
| + {"B10", "TRUE", calc.Value{Kind: calc.KindBool, Bool: true}}, |
| + {"B12", "=A1+1", n(6)}, |
| + {"B13", "=1/0", calc.Value{Kind: calc.KindErr, Err: calc.ErrDiv0}}, |
| + {"C1", "=$A$1+1", n(6)}, |
| + {"C2", "=$A$1+1", n(6)}, |
| + {"D1", `=IF(TRUE,"","x")`, str("")}, |
| + {"E2", `=""`, str("")}, |
| + } |
| + for _, c := range cases { |
| + raw, value := cellByRef(t, h, c.ref) |
| + if raw != c.raw || value != c.value { |
| + t.Errorf("%s = %q %+v, want %q %+v", c.ref, raw, value, c.raw, c.value) |
| + } |
| + } |
| + |
| + if rep.Worksheets != 2 || rep.OmittedWorksheets() != 1 { |
| + t.Errorf("worksheets = %d (omitted %d), want 2 (1)", rep.Worksheets, rep.OmittedWorksheets()) |
| + } |
| + wantCells := map[xlsx.Code][]string{ |
| + xlsx.TextKept: {"A2", "E2", "A3", "A4", "A5", "A6", "B6"}, |
| + xlsx.FormulaDiffers: {"B2", "B14"}, |
| + xlsx.FormulaOtherSheet: {"B4"}, |
| + xlsx.FormulaGoogleOnly: {"B5", "B6"}, |
| + xlsx.FormulaArray: {"B7"}, |
| + xlsx.FormulaUnsupported: {"B8", "B10"}, |
| + xlsx.FormulaUnchecked: {"B11", "B12"}, |
| + } |
| + for code, want := range wantCells { |
| + got := entry(rep, code) |
| + if got.Count != len(want) || !sameStrings(got.Cells, want) { |
| + t.Errorf("%s = %d %v, want %v", code, got.Count, got.Cells, want) |
| + } |
| + } |
| +} |
| + |
| +// cellByRef reads one cell's raw input and value by its A1 reference. |
| +func cellByRef(t *testing.T, h *store.Handle, ref string) (string, calc.Value) { |
| + t.Helper() |
| + for _, rp := range h.GridRows() { |
| + for _, cp := range h.GridCols() { |
| + if calc.A1(rp.Pos, cp.Pos) == ref { |
| + raw, _ := h.RawInput(rp.ID, cp.ID) |
| + return raw, h.Value(rp.ID, cp.ID) |
| + } |
| + } |
| + } |
| + return "", calc.Value{} |
| +} |
| + |
| +func sameStrings(a, b []string) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for i := range a { |
| + if a[i] != b[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// A write whose dependents pass calc.MaxDirtyPerPass is not |
| +// recalculated until the tab next opens, so no value read during the |
| +// import is final. Then nothing is compared: a stale value could match |
| +// a saved one by accident and hide a difference. |
| +func TestImportComparesNothingAfterACappedRecalculation(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("writes over calc.MaxDirtyPerPass cells") |
| + } |
| + n := calc.MaxDirtyPerPass + 1 |
| + rows := make([]string, 0, n+1) |
| + for i := 1; i <= n; i++ { |
| + rows = append(rows, row(i, formula("B"+strconv.Itoa(i), "", "$A$"+strconv.Itoa(n+1), ptr("1")))) |
| + } |
| + rows = append(rows, row(n+1, num("A"+strconv.Itoa(n+1), "1"))) |
| + _, rep, err := importRaw(t, rawBook{sheets: []string{strings.Join(rows, "")}}) |
| + if err != nil { |
| + t.Fatalf("Import: %v", err) |
| + } |
| + if got := entry(rep, xlsx.FormulaUnchecked).Count; got != n { |
| + t.Errorf("unchecked = %d, want all %d", got, n) |
| + } |
| + if got := entry(rep, xlsx.FormulaDiffers).Count; got != 0 { |
| + t.Errorf("differs = %d, want none: nothing final was compared", got) |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/omissions.go b/internal/sheets/xlsx/omissions.go| new file mode 100644 |
| index 0000000..1e60ef6 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/omissions.go |
| @@ -0,0 +1,96 @@ |
| +package xlsx |
| + |
| +import ( |
| + "strings" |
| + |
| + "github.com/xuri/excelize/v2" |
| +) |
| + |
| +// reportOmissions counts what the first worksheet and the workbook |
| +// hold that import does not carry. Counts, never content: a comment's |
| +// text, a validation's list and a defined name's formula stay where |
| +// they are. |
| +func reportOmissions(f *excelize.File, sheet string, scan *sheetScan, rep *Report) { |
| + undetected := 0 |
| + count := func(code Code, n int, err error) { |
| + if err != nil { |
| + undetected++ |
| + return |
| + } |
| + rep.add(code, n) |
| + } |
| + |
| + merges, err := f.GetMergeCells(sheet, true) |
| + count(OmittedMerges, len(merges), err) |
| + comments, err := f.GetComments(sheet) |
| + count(OmittedComments, len(comments), err) |
| + validations, err := f.GetDataValidations(sheet) |
| + count(OmittedValidation, len(validations), err) |
| + conditional, err := f.GetConditionalFormats(sheet) |
| + count(OmittedConditional, len(conditional), err) |
| + pictures, err := f.GetPictureCells(sheet) |
| + count(OmittedPictures, len(pictures), err) |
| + rep.add(OmittedDefinedNames, definedNames(f.GetDefinedName())) |
| + |
| + rep.add(OmittedHyperlinks, scan.Hyperlinks) |
| + rep.add(OmittedHiddenRows, scan.HiddenRows) |
| + rep.add(OmittedHiddenCols, scan.HiddenCols) |
| + if scan.FrozenPane { |
| + rep.add(OmittedFrozenPanes, 1) |
| + } |
| + if scan.AutoFilter { |
| + rep.add(OmittedFilter, 1) |
| + } |
| + rep.add(OmittedWorkbookChart, scan.Charts) |
| + rep.add(OmittedWorkbookImage, scan.Images) |
| + rep.add(OmittedUndetected, undetected) |
| +} |
| + |
| +// partialStyle reports whether a cell's style uses something |
| +// formatFromStyle does not carry. base is the workbook's default |
| +// style: every cell has a font family and size, and only one that |
| +// differs from the default was a choice somebody made. |
| +func partialStyle(st, base *excelize.Style) bool { |
| + if len(st.Border) > 0 { |
| + return true |
| + } |
| + if st.NumFmt != 0 && (st.CustomNumFmt == nil || *st.CustomNumFmt == "") { |
| + return true // a built-in number format: only custom ones come across |
| + } |
| + if st.Fill.Type == "gradient" || (st.Fill.Type == "pattern" && st.Fill.Pattern > 1) { |
| + return true |
| + } |
| + if a := st.Alignment; a != nil { |
| + if a.WrapText || a.Indent != 0 || a.TextRotation != 0 || a.ShrinkToFit || |
| + a.Vertical == "top" || a.Vertical == "center" { |
| + return true |
| + } |
| + } |
| + if ft := st.Font; ft != nil { |
| + if ft.Underline != "" || ft.Strike || ft.VertAlign != "" { |
| + return true |
| + } |
| + if b := base.Font; b != nil && (ft.Family != b.Family || ft.Size != b.Size || |
| + (ft.Color == "" && !sameTheme(ft.ColorTheme, b.ColorTheme))) { |
| + return true // a theme ink differing from the default's: only literal ink comes across |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func sameTheme(a, b *int) bool { |
| + return (a == nil && b == nil) || (a != nil && b != nil && *a == *b) |
| +} |
| + |
| +// definedNames counts the names a person defined. Excel's own _xlnm. |
| +// names (a filter's range, a print area) are how other features are |
| +// stored, and those are reported as themselves. |
| +func definedNames(names []excelize.DefinedName) int { |
| + n := 0 |
| + for _, d := range names { |
| + if !strings.HasPrefix(d.Name, "_xlnm.") { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
diff --git a/internal/sheets/xlsx/plaintext_test.go b/internal/sheets/xlsx/plaintext_test.go| index d670de2..2a0d71e 100644 |
| --- a/internal/sheets/xlsx/plaintext_test.go |
| +++ b/internal/sheets/xlsx/plaintext_test.go |
| @@ -61,7 +61,7 @@ func TestImportDoesNotLeakPlaintext(t *testing.T) { |
| // also checks the WAL directly, but a checkpoint proves the main file |
| // itself is clean too). |
| target := newTab(t, d.G, sealer) |
| - if err := xlsx.Import(&buf, target); err != nil { |
| + if _, err := xlsx.Import(&buf, target); err != nil { |
| t.Fatalf("Import: %v", err) |
| } |
| if err := d.G.Exec("PRAGMA wal_checkpoint(TRUNCATE)").Error; err != nil { |
diff --git a/internal/sheets/xlsx/rawbook_test.go b/internal/sheets/xlsx/rawbook_test.go| new file mode 100644 |
| index 0000000..c49cd13 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/rawbook_test.go |
| @@ -0,0 +1,140 @@ |
| +package xlsx_test |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| +) |
| + |
| +// rawBook writes a workbook part by part, so a test controls the exact |
| +// XML a cell is written with: whether a formula has a <v>, what t it |
| +// declares, how Google wraps a function Excel lacks. excelize cannot |
| +// write most of these shapes, which is the point of reading them. |
| +// |
| +// sheets are each worksheet's <sheetData> rows; extra is any further |
| +// worksheet markup (after sheetData) for the first sheet. |
| +type rawBook struct { |
| + sheets []string |
| + extra string |
| + parts map[string]string // replaces or adds a part by name |
| +} |
| + |
| +const rawStyles = `<?xml version="1.0" encoding="UTF-8"?> |
| +<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> |
| +<fonts count="1"><font><sz val="10"/><name val="Arial"/></font></fonts> |
| +<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills> |
| +<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders> |
| +<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs> |
| +<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs> |
| +</styleSheet>` |
| + |
| +func (b rawBook) bytes(t *testing.T) []byte { |
| + t.Helper() |
| + parts := map[string]string{ |
| + "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?> |
| +<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"> |
| +<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/> |
| +<Default Extension="xml" ContentType="application/xml"/> |
| +<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/> |
| +</Types>`, |
| + "_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?> |
| +<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> |
| +<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/> |
| +</Relationships>`, |
| + "xl/styles.xml": rawStyles, |
| + } |
| + var sheets, rels strings.Builder |
| + for i, data := range b.sheets { |
| + n := i + 1 |
| + fmt.Fprintf(&sheets, `<sheet name="Sheet%d" sheetId="%d" r:id="rId%d"/>`, n, n, n) |
| + fmt.Fprintf(&rels, `<Relationship Id="rId%d" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet%d.xml"/>`, n, n) |
| + extra := "" |
| + if i == 0 { |
| + extra = b.extra |
| + } |
| + parts[fmt.Sprintf("xl/worksheets/sheet%d.xml", n)] = `<?xml version="1.0" encoding="UTF-8"?> |
| +<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>` + |
| + data + `</sheetData>` + extra + `</worksheet>` |
| + } |
| + fmt.Fprintf(&rels, `<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`) |
| + parts["xl/workbook.xml"] = `<?xml version="1.0" encoding="UTF-8"?> |
| +<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>` + |
| + sheets.String() + `</sheets></workbook>` |
| + parts["xl/_rels/workbook.xml.rels"] = `<?xml version="1.0" encoding="UTF-8"?> |
| +<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` + rels.String() + `</Relationships>` |
| + for name, body := range b.parts { |
| + parts[name] = body |
| + } |
| + |
| + var buf bytes.Buffer |
| + zw := zip.NewWriter(&buf) |
| + for name, body := range parts { |
| + w, err := zw.Create(name) |
| + if err != nil { |
| + t.Fatalf("zip create %s: %v", name, err) |
| + } |
| + if _, err := w.Write([]byte(body)); err != nil { |
| + t.Fatalf("zip write %s: %v", name, err) |
| + } |
| + } |
| + if err := zw.Close(); err != nil { |
| + t.Fatalf("zip close: %v", err) |
| + } |
| + return buf.Bytes() |
| +} |
| + |
| +// importRaw imports b into a fresh tab and returns the handle, the |
| +// report and Import's error. |
| +func importRaw(t *testing.T, b rawBook) (*store.Handle, xlsx.Report, error) { |
| + t.Helper() |
| + h := newTab(t, openTestDB(t), testSealer(t)) |
| + rep, err := xlsx.Import(bytes.NewReader(b.bytes(t)), h) |
| + return h, rep, err |
| +} |
| + |
| +// row wraps cells in a <row r="n">. |
| +func row(n int, cells ...string) string { |
| + return fmt.Sprintf(`<row r="%d">%s</row>`, n, strings.Join(cells, "")) |
| +} |
| + |
| +// inline is an inline-string cell; num a number cell. |
| +func inline(ref, text string) string { |
| + return fmt.Sprintf(`<c r="%s" t="inlineStr"><is><t xml:space="preserve">%s</t></is></c>`, ref, xmlEscape(text)) |
| +} |
| + |
| +func num(ref, v string) string { return fmt.Sprintf(`<c r="%s"><v>%s</v></c>`, ref, v) } |
| + |
| +// formula is a formula cell; t is its declared type and v its saved |
| +// value, with v == nil meaning no <v> element at all. |
| +func formula(ref, t, f string, v *string) string { |
| + attrs := fmt.Sprintf(`r="%s"`, ref) |
| + if t != "" { |
| + attrs += fmt.Sprintf(` t="%s"`, t) |
| + } |
| + body := "<f>" + xmlEscape(f) + "</f>" |
| + if v != nil { |
| + body += "<v>" + xmlEscape(*v) + "</v>" |
| + } |
| + return "<c " + attrs + ">" + body + "</c>" |
| +} |
| + |
| +func ptr(s string) *string { return &s } |
| + |
| +func xmlEscape(s string) string { |
| + return strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """).Replace(s) |
| +} |
| + |
| +// entry finds code in rep, or a zero Entry. |
| +func entry(rep xlsx.Report, code xlsx.Code) xlsx.Entry { |
| + for _, e := range rep.Entries { |
| + if e.Code == code { |
| + return e |
| + } |
| + } |
| + return xlsx.Entry{} |
| +} |
diff --git a/internal/sheets/xlsx/report.go b/internal/sheets/xlsx/report.go| new file mode 100644 |
| index 0000000..b77cde9 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/report.go |
| @@ -0,0 +1,119 @@ |
| +package xlsx |
| + |
| +import "amadan.net/oficina/sheets/internal/sheets/calc" |
| + |
| +// Code names one kind of thing an import changed or left behind. |
| +// |
| +// A report is codes, coordinates and counts, never content: no cell |
| +// text, no formula, no sheet or file name. That is what lets it be |
| +// shown, stored sealed and carried around without becoming a second |
| +// copy of the workbook. |
| +type Code string |
| + |
| +// Per-cell codes: each carries the coordinates it applies to. |
| +const ( |
| + // A formula calling a function Google Sheets has and Excel does |
| + // not; Google exports it wrapped in __xludf.DUMMYFUNCTION. Kept as |
| + // its saved value. |
| + FormulaGoogleOnly Code = "formula-google-only" |
| + // An array formula (one formula filling a range). Kept as its |
| + // saved value. |
| + FormulaArray Code = "formula-array" |
| + // A reference to another worksheet or another workbook. Kept as |
| + // its saved value: only the first worksheet comes across. |
| + FormulaOtherSheet Code = "formula-other-sheet" |
| + // Any other formula this app cannot calculate. Kept as its saved |
| + // value. |
| + FormulaUnsupported Code = "formula-unsupported" |
| + // A formula this app calculates, whose result here differs from |
| + // the value the workbook saved. Kept as a formula. |
| + FormulaDiffers Code = "formula-differs" |
| + // A formula kept as a formula with no saved value to check it |
| + // against. |
| + FormulaUnchecked Code = "formula-unchecked" |
| + // Text that would otherwise read as a number, a boolean, a formula |
| + // or a blank, kept as text by a constant string formula ="...". |
| + TextKept Code = "text-kept" |
| + // A cell whose style used something this app does not carry: |
| + // fonts, sizes, borders, wrapping, underline and the like. |
| + FormatPartial Code = "format-partial" |
| +) |
| + |
| +// Count-only codes: what the worksheet or workbook had, none of it |
| +// imported. |
| +const ( |
| + OmittedMerges Code = "merges" |
| + OmittedComments Code = "comments" |
| + OmittedValidation Code = "validation" |
| + OmittedConditional Code = "conditional-formats" |
| + OmittedHyperlinks Code = "hyperlinks" |
| + OmittedDefinedNames Code = "defined-names" |
| + OmittedHiddenRows Code = "hidden-rows" |
| + OmittedHiddenCols Code = "hidden-columns" |
| + OmittedFrozenPanes Code = "frozen-panes" |
| + OmittedFilter Code = "filter" |
| + OmittedPictures Code = "pictures" |
| + OmittedWorkbookChart Code = "workbook-charts" |
| + OmittedWorkbookImage Code = "workbook-images" |
| + // The detectors that could not read their part of the workbook, |
| + // so a report says it did not look rather than imply there was |
| + // nothing to find. |
| + OmittedUndetected Code = "undetected" |
| +) |
| + |
| +// MaxListedCells is how many coordinates one entry names; Count keeps |
| +// the true total past it. |
| +const MaxListedCells = 200 |
| + |
| +// Entry is one code and where it applies. |
| +type Entry struct { |
| + Code Code `json:"code"` |
| + Count int `json:"count"` |
| + Cells []string `json:"cells,omitempty"` |
| +} |
| + |
| +// Report is what one import did beyond copying values across. |
| +// |
| +// It never claims completeness. An empty Entries says nothing was |
| +// detected, which is all it can say; the page that shows it states |
| +// the supported subset beside it. |
| +type Report struct { |
| + // Worksheets is how many the workbook held. Only the first comes |
| + // across, so Worksheets-1 were omitted. |
| + Worksheets int `json:"worksheets"` |
| + Entries []Entry `json:"entries,omitempty"` |
| +} |
| + |
| +// OmittedWorksheets is how many worksheets did not come across. |
| +func (r Report) OmittedWorksheets() int { |
| + if r.Worksheets <= 1 { |
| + return 0 |
| + } |
| + return r.Worksheets - 1 |
| +} |
| + |
| +func (r *Report) entry(code Code) *Entry { |
| + for i := range r.Entries { |
| + if r.Entries[i].Code == code { |
| + return &r.Entries[i] |
| + } |
| + } |
| + r.Entries = append(r.Entries, Entry{Code: code}) |
| + return &r.Entries[len(r.Entries)-1] |
| +} |
| + |
| +// cell records code at a 0-based position. |
| +func (r *Report) cell(code Code, rowPos, colPos int) { |
| + e := r.entry(code) |
| + e.Count++ |
| + if len(e.Cells) < MaxListedCells { |
| + e.Cells = append(e.Cells, calc.A1(rowPos, colPos)) |
| + } |
| +} |
| + |
| +// add records n of a count-only code; zero records nothing. |
| +func (r *Report) add(code Code, n int) { |
| + if n > 0 { |
| + r.entry(code).Count += n |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/roundtrip_test.go b/internal/sheets/xlsx/roundtrip_test.go| index c191bbb..7913c20 100644 |
| --- a/internal/sheets/xlsx/roundtrip_test.go |
| +++ b/internal/sheets/xlsx/roundtrip_test.go |
| @@ -98,7 +98,7 @@ func TestImportErrorsContainNoCellContent(t *testing.T) { |
| sealer := testSealer(t) |
| h := newTab(t, db, sealer) |
| - err := xlsx.Import(buf, h) |
| + _, err := xlsx.Import(buf, h) |
| if err == nil { |
| t.Fatal("want an error importing a deliberately unparseable formula, got nil") |
| } |
diff --git a/internal/sheets/xlsx/saved.go b/internal/sheets/xlsx/saved.go| new file mode 100644 |
| index 0000000..b0a099f |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/saved.go |
| @@ -0,0 +1,128 @@ |
| +package xlsx |
| + |
| +import ( |
| + "errors" |
| + "math" |
| + "strconv" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +// Why a formula's saved value cannot stand in for it. Each refuses the |
| +// import at the cell's coordinate: there is no trustworthy value to |
| +// keep, and import never manufactures one. |
| +var ( |
| + errNoSavedValue = errors.New("xlsx: formula has no saved value") |
| + errSavedError = errors.New("xlsx: formula saved an error value") |
| + errSavedUnreadable = errors.New("xlsx: formula saved a value of an unexpected type") |
| +) |
| + |
| +// savedValue reads the value a workbook saved with a formula, by the |
| +// rules a frozen cell is held to: |
| +// |
| +// - a <v> must be present: absent is not the empty string; |
| +// - t absent or "n": a finite number, parsed exactly; |
| +// - t "b": exactly "0" or "1"; |
| +// - t "str": any text, the empty string included; |
| +// - t "e": refused, because no value in this app is an error that a |
| +// person did not compute, and error-to-text would change what the |
| +// cell means; |
| +// - anything else: refused. |
| +func savedValue(c scannedCell) (calc.Value, error) { |
| + if !c.HasV { |
| + return calc.Value{}, errNoSavedValue |
| + } |
| + switch c.T { |
| + case "", "n": |
| + n, err := strconv.ParseFloat(c.V, 64) |
| + if err != nil || math.IsNaN(n) || math.IsInf(n, 0) { |
| + return calc.Value{}, errSavedUnreadable |
| + } |
| + return calc.Value{Kind: calc.KindNum, Num: n}, nil |
| + case "b": |
| + switch c.V { |
| + case "0": |
| + return calc.Value{Kind: calc.KindBool}, nil |
| + case "1": |
| + return calc.Value{Kind: calc.KindBool, Bool: true}, nil |
| + } |
| + return calc.Value{}, errSavedUnreadable |
| + case "str": |
| + return calc.Value{Kind: calc.KindStr, Str: c.V}, nil |
| + case "e": |
| + return calc.Value{}, errSavedError |
| + } |
| + return calc.Value{}, errSavedUnreadable |
| +} |
| + |
| +// frozenInput is the raw input that holds v as a literal, and whether |
| +// holding it took the ="..." wrapper. |
| +func frozenInput(v calc.Value) (raw string, wrapped bool) { |
| + switch v.Kind { |
| + case calc.KindNum: |
| + return strconv.FormatFloat(v.Num, 'g', -1, 64), false |
| + case calc.KindBool: |
| + if v.Bool { |
| + return "TRUE", false |
| + } |
| + return "FALSE", false |
| + default: |
| + return store.TextInput(v.Str) |
| + } |
| +} |
| + |
| +// savedErrors are the error values a workbook can save that this |
| +// engine also produces. Any other (#SPILL!, #CALC!, Google's #ERROR!) |
| +// compares unequal to everything, which is the truth. |
| +var savedErrors = map[string]calc.ErrKind{ |
| + "#DIV/0!": calc.ErrDiv0, "#VALUE!": calc.ErrValue, "#REF!": calc.ErrRef, |
| + "#NAME?": calc.ErrName, "#NUM!": calc.ErrNum, "#N/A": calc.ErrNA, |
| +} |
| + |
| +// comparableSaved is a kept formula's saved value, to check this |
| +// engine's result against. Unlike savedValue it accepts an error, |
| +// because a kept formula is not being replaced by what it saved. |
| +func comparableSaved(c scannedCell) (calc.Value, bool) { |
| + if c.HasV && c.T == "e" { |
| + kind, ok := savedErrors[c.V] |
| + if !ok { |
| + return calc.Value{Kind: calc.KindErr, Err: calc.ErrNone}, true |
| + } |
| + return calc.Value{Kind: calc.KindErr, Err: kind}, true |
| + } |
| + v, err := savedValue(c) |
| + return v, err == nil |
| +} |
| + |
| +// Numbers compare within a relative tolerance. Google writes 15 |
| +// significant digits and Excel computes in its own order, so exact |
| +// comparison would flag nearly every division; anything past one part |
| +// in a billion is a different answer, not a rounding. |
| +const ( |
| + relTolerance = 1e-9 |
| + absTolerance = 1e-12 |
| +) |
| + |
| +// sameValue reports whether this engine's result matches a saved one. |
| +func sameValue(ours, saved calc.Value) bool { |
| + // Kinds compare strictly. A formula that computes to nothing here |
| + // where the workbook saved 0 or "" is a real difference: blank, |
| + // zero and the empty string answer ISBLANK, ISNUMBER and = apart. |
| + if ours.Kind != saved.Kind { |
| + return false |
| + } |
| + switch ours.Kind { |
| + case calc.KindNum: |
| + diff := math.Abs(ours.Num - saved.Num) |
| + scale := math.Max(math.Abs(ours.Num), math.Abs(saved.Num)) |
| + return diff <= absTolerance || diff <= relTolerance*scale |
| + case calc.KindStr: |
| + return ours.Str == saved.Str |
| + case calc.KindBool: |
| + return ours.Bool == saved.Bool |
| + case calc.KindErr: |
| + return saved.Err != calc.ErrNone && ours.Err == saved.Err |
| + } |
| + return false |
| +} |
diff --git a/internal/sheets/xlsx/scan_parts.go b/internal/sheets/xlsx/scan_parts.go| new file mode 100644 |
| index 0000000..ef8abfd |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/scan_parts.go |
| @@ -0,0 +1,229 @@ |
| +package xlsx |
| + |
| +import ( |
| + "archive/zip" |
| + "bytes" |
| + "encoding/xml" |
| + "errors" |
| + "io" |
| + "path" |
| + "strings" |
| +) |
| + |
| +// The scan's own bounds. excelize's openLimits bound what excelize |
| +// decompresses; these bound what this package's second reader does, |
| +// since a bound on one reader says nothing about the other. |
| +const ( |
| + maxZipEntries = 10_000 |
| + maxPartBytes = 8 << 20 // _rels/.rels, the workbook and its rels |
| + maxSheetBytes = 256 << 20 |
| + maxXMLDepth = 64 |
| + maxCachedBytes = 1 << 20 // one <v>; Excel caps a cell at 32,767 characters |
| +) |
| + |
| +const ( |
| + relOfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" |
| + relWorksheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" |
| + relNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" |
| +) |
| + |
| +// errScanInconsistent is a workbook this package's reader and |
| +// excelize's disagree about. Either could be the one that is right; |
| +// neither is trusted to decide alone, so the import stops. |
| +var errScanInconsistent = errors.New("xlsx: workbook parts disagree") |
| + |
| +// errScanLimit is a part past one of the bounds above. |
| +var errScanLimit = errors.New("xlsx: workbook part exceeds a limit") |
| + |
| +// zipParts indexes a workbook's entries by name the way excelize does: |
| +// backslashes read as slashes, and a later duplicate replaces an |
| +// earlier one. |
| +type zipParts map[string]*zip.File |
| + |
| +func openParts(data []byte) (zipParts, error) { |
| + zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(zr.File) > maxZipEntries { |
| + return nil, errScanLimit |
| + } |
| + parts := make(zipParts, len(zr.File)) |
| + for _, f := range zr.File { |
| + parts[strings.ReplaceAll(f.Name, `\`, "/")] = f |
| + } |
| + return parts, nil |
| +} |
| + |
| +// open returns a reader over one part that fails, rather than |
| +// truncating, once it has produced more than limit bytes. |
| +func (p zipParts) open(name string, limit int64) (io.ReadCloser, error) { |
| + f, ok := p[name] |
| + if !ok { |
| + return nil, errScanInconsistent |
| + } |
| + rc, err := f.Open() |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &capReader{rc: rc, left: limit}, nil |
| +} |
| + |
| +// count reports how many entries sit under prefix: charts and images, |
| +// which this import never reads, only counts. |
| +func (p zipParts) count(prefix string) int { |
| + n := 0 |
| + for name := range p { |
| + if strings.HasPrefix(name, prefix) && !strings.HasSuffix(name, "/") { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +type capReader struct { |
| + rc io.ReadCloser |
| + left int64 |
| +} |
| + |
| +func (c *capReader) Read(b []byte) (int, error) { |
| + if c.left < 0 { |
| + return 0, errScanLimit |
| + } |
| + if int64(len(b)) > c.left+1 { |
| + b = b[:c.left+1] |
| + } |
| + n, err := c.rc.Read(b) |
| + c.left -= int64(n) |
| + if c.left < 0 { |
| + return n, errScanLimit |
| + } |
| + return n, err |
| +} |
| + |
| +func (c *capReader) Close() error { return c.rc.Close() } |
| + |
| +// firstWorksheetPath resolves the first <sheet> of the workbook to its |
| +// part, by the same route excelize takes: _rels/.rels names the |
| +// workbook, the workbook's own rels name each sheet's target, and a |
| +// target resolves against the workbook's directory unless it is |
| +// absolute. It also returns that sheet's name, compared in memory with |
| +// excelize's first sheet and never written anywhere. |
| +func firstWorksheetPath(p zipParts) (sheetPath, name string, err error) { |
| + rootRels, err := readRels(p, "_rels/.rels") |
| + if err != nil { |
| + return "", "", err |
| + } |
| + var wbPath string |
| + for _, r := range rootRels { |
| + if r.Type == relOfficeDocument { |
| + wbPath = strings.TrimPrefix(r.Target, "/") |
| + break |
| + } |
| + } |
| + if wbPath == "" { |
| + return "", "", errScanInconsistent |
| + } |
| + sheetID, name, err := firstSheetRelID(p, wbPath) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + dir := path.Dir(wbPath) |
| + relsPath := strings.TrimPrefix(path.Join(dir, "_rels", path.Base(wbPath)+".rels"), "./") |
| + rels, err := readRels(p, relsPath) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + for _, r := range rels { |
| + if r.ID != sheetID { |
| + continue |
| + } |
| + if r.Type != relWorksheet { |
| + return "", "", errScanInconsistent // a chartsheet or dialog first |
| + } |
| + target := strings.ReplaceAll(r.Target, `\`, "/") |
| + if strings.HasPrefix(target, "/") { |
| + return strings.TrimPrefix(path.Clean(target), "/"), name, nil |
| + } |
| + return strings.TrimPrefix(path.Clean(dir+"/"+target), "/"), name, nil |
| + } |
| + return "", "", errScanInconsistent |
| +} |
| + |
| +type relationship struct { |
| + ID string `xml:"Id,attr"` |
| + Type string `xml:"Type,attr"` |
| + Target string `xml:"Target,attr"` |
| +} |
| + |
| +func readRels(p zipParts, name string) ([]relationship, error) { |
| + var doc struct { |
| + Rels []relationship `xml:"Relationship"` |
| + } |
| + if err := decodePart(p, name, &doc); err != nil { |
| + return nil, err |
| + } |
| + return doc.Rels, nil |
| +} |
| + |
| +func firstSheetRelID(p zipParts, wbPath string) (id, name string, err error) { |
| + var doc struct { |
| + Sheets []struct { |
| + Name string `xml:"name,attr"` |
| + Attrs []xml.Attr `xml:",any,attr"` |
| + } `xml:"sheets>sheet"` |
| + } |
| + if err := decodePart(p, wbPath, &doc); err != nil { |
| + return "", "", err |
| + } |
| + if len(doc.Sheets) == 0 { |
| + return "", "", errScanInconsistent |
| + } |
| + for _, a := range doc.Sheets[0].Attrs { |
| + if a.Name.Space == relNamespace && a.Name.Local == "id" { |
| + return a.Value, doc.Sheets[0].Name, nil |
| + } |
| + } |
| + return "", "", errScanInconsistent |
| +} |
| + |
| +// decodePart unmarshals one small part, bounded in bytes and depth. |
| +func decodePart(p zipParts, name string, into any) error { |
| + rc, err := p.open(name, maxPartBytes) |
| + if err != nil { |
| + return err |
| + } |
| + defer rc.Close() |
| + body, err := io.ReadAll(rc) |
| + if err != nil { |
| + return err |
| + } |
| + if err := checkDepth(body); err != nil { |
| + return err |
| + } |
| + return xml.Unmarshal(body, into) |
| +} |
| + |
| +// checkDepth refuses XML nested deeper than maxXMLDepth before |
| +// encoding/xml, which has no depth limit of its own, unmarshals it. |
| +func checkDepth(body []byte) error { |
| + d := xml.NewDecoder(bytes.NewReader(body)) |
| + depth := 0 |
| + for { |
| + tok, err := d.RawToken() |
| + if err == io.EOF { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + switch tok.(type) { |
| + case xml.StartElement: |
| + if depth++; depth > maxXMLDepth { |
| + return errScanLimit |
| + } |
| + case xml.EndElement: |
| + depth-- |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/xlsx/scan_sheet.go b/internal/sheets/xlsx/scan_sheet.go| new file mode 100644 |
| index 0000000..2231562 |
| --- /dev/null |
| +++ b/internal/sheets/xlsx/scan_sheet.go |
| @@ -0,0 +1,236 @@ |
| +package xlsx |
| + |
| +import ( |
| + "encoding/xml" |
| + "errors" |
| + "io" |
| + "strconv" |
| + |
| + "github.com/xuri/excelize/v2" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +// scannedCell is one <c> as the worksheet XML wrote it. |
| +// |
| +// It exists for what excelize cannot say. excelize's cell model keeps |
| +// <v> as a plain string with omitempty, so a formula whose saved value |
| +// is the empty string and a formula with no saved value at all read |
| +// the same; this reader records whether <v> was there. |
| +type scannedCell struct { |
| + T string // the c element's t attribute: "", "n", "b", "e", "s", "str", "inlineStr", "d" |
| + HasF bool |
| + FType string // the f element's t attribute: "", "normal", "shared", "array", "dataTable" |
| + HasV bool |
| + V string |
| +} |
| + |
| +// sheetScan is what a bounded read of the first worksheet found. |
| +type sheetScan struct { |
| + // Name is the first sheet's name, compared with excelize's. |
| + Name string |
| + // Cells holds every formula cell and every string-typed cell. |
| + Cells map[posKey]scannedCell |
| + // Layout and features the import does not carry, counted. |
| + Hyperlinks, HiddenRows, HiddenCols int |
| + FrozenPane, AutoFilter bool |
| + // Charts and Images are workbook-wide part counts. |
| + Charts, Images int |
| +} |
| + |
| +type posKey struct{ Row, Col int } |
| + |
| +// errCellWithoutRef is a formula or string cell whose position the XML |
| +// leaves implicit. excelize would place it by order; this reader does |
| +// not guess, so the two could disagree about where it is. |
| +var errCellWithoutRef = errors.New("xlsx: a cell has no reference") |
| + |
| +// scanWorkbook reads the first worksheet's XML directly, bounded. |
| +func scanWorkbook(data []byte) (*sheetScan, error) { |
| + parts, err := openParts(data) |
| + if err != nil { |
| + return nil, err |
| + } |
| + sheetPath, name, err := firstWorksheetPath(parts) |
| + if err != nil { |
| + return nil, err |
| + } |
| + rc, err := parts.open(sheetPath, maxSheetBytes) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rc.Close() |
| + |
| + s := &sheetScan{ |
| + Name: name, |
| + Cells: map[posKey]scannedCell{}, |
| + Charts: parts.count("xl/charts/chart"), |
| + Images: parts.count("xl/media/"), |
| + } |
| + if err := s.walk(xml.NewDecoder(rc)); err != nil { |
| + return nil, err |
| + } |
| + return s, nil |
| +} |
| + |
| +// Paths the walk acts on, as the stack of local names above an |
| +// element. Matching the whole path, not just the parent, is what keeps |
| +// a <c> or a <v> inside some extension element from being read as a |
| +// cell: excelize unmarshals by the same paths, so anything elsewhere is |
| +// invisible to it, and must be to this reader too. |
| +var ( |
| + pathRow = []string{"worksheet", "sheetData"} |
| + pathCell = []string{"worksheet", "sheetData", "row"} |
| + pathCellChild = []string{"worksheet", "sheetData", "row", "c"} |
| + pathCol = []string{"worksheet", "cols"} |
| + pathHyperlink = []string{"worksheet", "hyperlinks"} |
| + pathPane = []string{"worksheet", "sheetViews", "sheetView"} |
| + pathSheet = []string{"worksheet"} |
| +) |
| + |
| +// formulaTypes are the <f t> values ECMA-376 defines. Any other is a |
| +// formula whose meaning this reader does not know, and is refused. |
| +var formulaTypes = map[string]bool{"": true, "normal": true, "shared": true, "array": true, "dataTable": true} |
| + |
| +// errScanDuplicate is a cell written twice, or a cell with two <f> or |
| +// two <v>. Which one wins is a parser's accident; import refuses to |
| +// depend on it. |
| +var errScanDuplicate = errors.New("xlsx: worksheet repeats a cell or its parts") |
| + |
| +// maxScannedCells bounds the set of every <c> reference the walk has |
| +// seen, which duplicate detection needs. |
| +const maxScannedCells = 2 * store.MaxCellsPerTab |
| + |
| +// walk streams the worksheet, bounded in depth by the stack. |
| +func (s *sheetScan) walk(d *xml.Decoder) error { |
| + var ( |
| + stack []string |
| + cell scannedCell |
| + ref string |
| + rowNum string |
| + fs, vs int |
| + seen = map[posKey]bool{} |
| + ) |
| + for { |
| + tok, err := d.Token() |
| + if err == io.EOF { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + switch t := tok.(type) { |
| + case xml.StartElement: |
| + if len(stack) >= maxXMLDepth { |
| + return errScanLimit |
| + } |
| + name := t.Name.Local |
| + switch { |
| + case name == "row" && at(stack, pathRow): |
| + rowNum = attr(t, "r") |
| + if truthy(attr(t, "hidden")) { |
| + s.HiddenRows++ |
| + } |
| + case name == "c" && at(stack, pathCell): |
| + cell, ref, fs, vs = scannedCell{T: attr(t, "t")}, attr(t, "r"), 0, 0 |
| + if ref != "" { |
| + col, row, err := excelize.CellNameToCoordinates(ref) |
| + if err != nil { |
| + return errScanInconsistent |
| + } |
| + p := posKey{Row: row - 1, Col: col - 1} |
| + if seen[p] { |
| + return errScanDuplicate |
| + } |
| + if len(seen) >= maxScannedCells { |
| + return store.ErrTabTooLarge |
| + } |
| + seen[p] = true |
| + } |
| + case name == "f" && at(stack, pathCellChild): |
| + fs++ |
| + cell.HasF, cell.FType = true, attr(t, "t") |
| + if !formulaTypes[cell.FType] { |
| + return errScanInconsistent |
| + } |
| + case name == "v" && at(stack, pathCellChild): |
| + vs++ |
| + cell.HasV = true |
| + case name == "col" && at(stack, pathCol): |
| + if truthy(attr(t, "hidden")) { |
| + s.HiddenCols++ |
| + } |
| + case name == "hyperlink" && at(stack, pathHyperlink): |
| + s.Hyperlinks++ |
| + case name == "pane" && at(stack, pathPane): |
| + st := attr(t, "state") |
| + s.FrozenPane = s.FrozenPane || st == "frozen" || st == "frozenSplit" |
| + case name == "autoFilter" && at(stack, pathSheet): |
| + s.AutoFilter = true |
| + } |
| + if fs > 1 || vs > 1 { |
| + return errScanDuplicate |
| + } |
| + stack = append(stack, name) |
| + case xml.CharData: |
| + if len(stack) == len(pathCellChild)+1 && stack[len(stack)-1] == "v" && at(stack[:len(stack)-1], pathCellChild) { |
| + if len(cell.V)+len(t) > maxCachedBytes { |
| + return errScanLimit |
| + } |
| + cell.V += string(t) |
| + } |
| + case xml.EndElement: |
| + stack = stack[:len(stack)-1] |
| + if t.Name.Local == "c" && at(stack, pathCell) { |
| + if err := s.keep(ref, rowNum, cell); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// at reports whether stack is exactly path. |
| +func at(stack, path []string) bool { |
| + if len(stack) != len(path) { |
| + return false |
| + } |
| + for i := range path { |
| + if stack[i] != path[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// keep records a cell the import needs to know about: one with a |
| +// formula, or one typed as a string (whose value may be the empty |
| +// string, which excelize's row reader drops from the end of a row). |
| +func (s *sheetScan) keep(ref, rowNum string, c scannedCell) error { |
| + if !c.HasF && c.T != "s" && c.T != "inlineStr" && c.T != "str" { |
| + return nil |
| + } |
| + if ref == "" { |
| + return errCellWithoutRef |
| + } |
| + col, row, err := excelize.CellNameToCoordinates(ref) |
| + if err != nil { |
| + return errScanInconsistent |
| + } |
| + if rowNum != "" && rowNum != strconv.Itoa(row) { |
| + return errScanInconsistent // a cell filed under another row |
| + } |
| + s.Cells[posKey{Row: row - 1, Col: col - 1}] = c |
| + return nil |
| +} |
| + |
| +func attr(t xml.StartElement, local string) string { |
| + for _, a := range t.Attr { |
| + if a.Name.Local == local { // by local name, as excelize's struct tags match |
| + return a.Value |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +func truthy(v string) bool { return v == "1" || v == "true" } |
diff --git a/tools/drive/google-import.mjs b/tools/drive/google-import.mjs| new file mode 100644 |
| index 0000000..250aa5c |
| --- /dev/null |
| +++ b/tools/drive/google-import.mjs |
| @@ -0,0 +1,85 @@ |
| +// Real Sheets app and jobs; synthesized workbook and controlled Google replies. |
| +import assert from 'node:assert/strict' |
| +const playwright = await import(process.env.PLAYWRIGHT || 'playwright') |
| +const config = JSON.parse(process.env.SHEETS_GOOGLE_IMPORT_TEST) |
| +const fixture = Buffer.from(config.fixture, 'base64') |
| +const gis = `window.google={accounts:{oauth2:{initTokenClient(c){return{requestAccessToken(){c.callback({access_token:'controlled-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'})}}},hasGrantedAllScopes(r,s){return r.scope===s}}}};` |
| +const gapi = `window.gapi={load(name,c){google.picker={Action:{PICKED:'picked',CANCEL:'cancel'},DocsView:class{setMimeTypes(){return this}},PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.cb=fn;return this}build(){const cb=this.cb;let el;return{setVisible(){el=document.createElement('button');el.textContent='Select import fixture';el.onclick=()=>cb({action:'picked',docs:[{id:'controlled_file',name:'Import fixture',mimeType:'application/vnd.google-apps.spreadsheet'}]});document.body.append(el)},dispose(){el?.remove()}}}}};c.callback()}};` |
| +for (const engine of ['chromium', 'webkit']) { |
| + const browser = await playwright[engine].launch() |
| + try { |
| + const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1050, height: 850 } }) |
| + const cookies = config.cookies.map(c => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, secure: c.Secure, sameSite: 'Lax' })) |
| + await context.addCookies(cookies) |
| + const page = await context.newPage() |
| + const failures = [], violations = [] |
| + let exports = 0, leaked = false |
| + page.on('pageerror', e => failures.push(e.message)) |
| + await page.addInitScript(() => document.addEventListener('securitypolicyviolation', e => console.log('IMPORT-CSP:' + e.violatedDirective))) |
| + page.on('console', m => { if (m.text().startsWith('IMPORT-CSP:')) violations.push(m.text()) }) |
| + page.on('request', r => { if (r.url().startsWith(config.origin) && ((r.postData() || '').includes('controlled-google-bearer') || JSON.stringify(r.headers()).includes('controlled-google-bearer'))) leaked = true }) |
| + await context.route('https://accounts.google.com/gsi/client', r => r.fulfill({ contentType: 'text/javascript', body: gis })) |
| + await context.route('https://apis.google.com/js/api.js', r => r.fulfill({ contentType: 'text/javascript', body: gapi })) |
| + await context.route('https://www.googleapis.com/drive/v3/files/**', async r => { |
| + exports++ |
| + assert.equal(r.request().headers().authorization, 'Bearer controlled-google-bearer') |
| + await r.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', body: fixture }) |
| + }) |
| + const waitForReport = async p => { |
| + await p.waitForURL(url => /^\/sheets\/\d+\/import-report$/.test(url.pathname), { timeout: 30000 }) |
| + assert.match(await p.locator('body').innerText(), /formula/i) |
| + assert.match(await p.locator('body').innerText(), /text/i) |
| + return p.url() |
| + } |
| + await page.goto(config.origin + '/sheets/import') |
| + assert.match(await page.locator('body').innerText(), /first\s+worksheet/i) |
| + await page.waitForFunction(() => !document.querySelector('[data-google-choose]')?.disabled) |
| + await page.locator('[data-google-choose]').click() |
| + await page.getByRole('button', { name: 'Select import fixture', exact: true }).click() |
| + const reportURL = await waitForReport(page) |
| + const sheetPath = new URL(reportURL).pathname.replace('/import-report', '') |
| + await page.goto(config.origin + sheetPath) |
| + const cell = (r, c) => page.locator(`td[data-x="${c}"][data-y="${r}"]`) |
| + await cell(0, 0).waitFor({ state: 'visible' }) |
| + for (const [r, c, value] of [[0, 0, '00123'], [0, 1, '7'], [1, 0, '2'], [1, 1, '5'], [2, 0, '=x'], [2, 1, 'TRUE']]) { |
| + await page.waitForFunction(([r,c,v]) => document.querySelector(`td[data-x="${c}"][data-y="${r}"]`)?.textContent.trim() === v, [r,c,value]) |
| + } |
| + await cell(1, 0).dblclick() |
| + const editor = cell(1, 0).locator('input,textarea') |
| + await editor.waitFor() |
| + await editor.fill('10') |
| + await editor.press('Enter') |
| + await page.waitForFunction(() => document.querySelector('td[data-x="1"][data-y="1"]')?.textContent.trim() === '13') |
| + await page.evaluate(() => SheetsCellQueue([], SheetsGrid.post)) |
| + await page.reload() |
| + await page.waitForFunction(() => document.querySelector('td[data-x="1"][data-y="1"]')?.textContent.trim() === '13') |
| + assert.equal((await cell(0, 0).innerText()).trim(), '00123') |
| + assert.equal((await cell(0, 1).innerText()).trim(), '7') |
| + await page.goto(reportURL) |
| + assert.match(await page.locator('body').innerText(), /formula/i) |
| + assert.equal(exports, 1) |
| + assert.equal(leaked, false) |
| + assert.deepEqual(violations, []) |
| + assert.deepEqual(failures, []) |
| + |
| + const plainContext = await browser.newContext({ ignoreHTTPSErrors: true, javaScriptEnabled: false }) |
| + await plainContext.addCookies(cookies) |
| + const plain = await plainContext.newPage() |
| + await plain.goto(config.origin + '/sheets/import') |
| + assert.equal(await plain.locator('[data-google-choose]').isVisible(), false) |
| + await plain.locator('input[type="file"]').setInputFiles({ name: 'scriptless.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: fixture }) |
| + await plain.locator('form:has(input[type="file"]) button[type="submit"]').click() |
| + // Scriptless job pages use their ordinary refresh link while the job runs. |
| + for (let i = 0; i < 30 && !/\/sheets\/\d+\/import-report$/.test(new URL(plain.url()).pathname); i++) { |
| + await plain.waitForTimeout(100) |
| + await plain.reload() |
| + } |
| + const plainReport = await waitForReport(plain) |
| + await plain.goto(plainReport.replace('/import-report', '/table')) |
| + assert.match(await plain.locator('table[data-cell-table]').innerText(), /00123/) |
| + assert.match(await plain.locator('table[data-cell-table]').innerText(), /=x/) |
| + await plainContext.close() |
| + await context.close() |
| + console.log(engine + ': real import job, typed text, frozen value, supported formula recalculation, reload, report and scriptless upload passed') |
| + } finally { await browser.close() } |
| +} |