Sheets: Google Drive import page, sealed import report, estilo 7a19588
The import report (xlsx.Report) is sealed under its own purpose,
"import.report", in a new import_reports table (additive migration
0011), and written in the same transaction that reveals the imported
sheet: a visible imported sheet always has its report, a refused or
discarded import never leaves one (discardSheet also deletes any).
The import job now lands on GET /sheets/{id}/import-report: anyone who
can read the sheet may read it, otherwise 404, and a sheet with no
report is 404. The page always states what import carries, then each
entry with its coordinates (capped, with the remainder counted) and the
omitted worksheet count, and links to the sheet. The sheet's File menu
offers "Import report" when one exists. The native job API keeps
location as /sheets/{id}, which the Mac app parses, and adds report.
Job refusals now name the cell and the package's fixed reason, never
content.
Google Drive: estilo googleimport, pinned to estilo main 7a19588 (the
reviewed, merged chooser). sheets.Config.GoogleImport comes from
SHEETS_GOOGLE_CLIENT_ID / _API_KEY / _APP_ID; all or none, and main
refuses boot on a partial or malformed set. Off, nothing changes. On,
the import page renders the chooser after the upload form (form
import-form, input file), loads the hashed module from
/static/google/<JSName>, and googleimport.Headers replaces the page's
policy with the expanded one on the page and on a refused POST's
re-render; no COOP, no-store; every other page keeps the app policy.
The chooser submits the ordinary form, so the same route, CSRF check,
member guard, limits, converter and report apply.
Tests: config all-or-nothing; page policy on/off and on the refused
re-render; script served; job lands on the report; report and File menu
item; table shows 00123 kept as text and the Google-only formula frozen
to 7; report sealed in the database file, WAL and SHM; report follows
sheet access; refused and discarded imports leave no report; native
location shape. Browser: internal/sheets/google_import_browser_test.go
with tools/drive/google-import.mjs (written by the parent session,
validated in Chromium and WebKit) drives the real app with controlled
Google SDK and export responses through upload, job, report, grid edit,
reload and the scriptless table. No live Google consent or real Google
export fixture: Google Cloud is configured after review, so production
stays unconfigured.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+1,006
−41
cmd/sheets/main.go+16 −5go.mod+1 −1go.sum+2 −0internal/sheets/app.go+9 −13internal/sheets/google_import_browser_test.go+94 −0internal/sheets/googleimport.go+71 −0internal/sheets/googleimport_test.go+133 −0internal/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/templates/import.html+21 −3internal/sheets/templates/import_report.html+42 −0internal/sheets/templates/sheet.html+1 −0tools/drive/google-import.mjs+85 −0
CI passed — run details
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go| index 4a89a0a..0ceb0d0 100644 |
| --- a/cmd/sheets/main.go |
| +++ b/cmd/sheets/main.go |
| @@ -111,12 +111,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 33648a6..6058ecd 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -3,7 +3,7 @@ module amadan.net/oficina/sheets |
| go 1.25.0 |
| require ( |
| - 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-20261028171508-67c12e39a9d2 |
| 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 8d2415a..a6b4ecb 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,5 +1,7 @@ |
| 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-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E= |
| amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/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 4595114..f0c52a3 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. |
| @@ -68,6 +72,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 |
| @@ -114,6 +119,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), |
| @@ -202,6 +208,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 |
| @@ -227,19 +234,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/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_import.go b/internal/sheets/handlers_import.go| index 32df3b8..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 1d3dc18..be2db8c 100644 |
| --- a/internal/sheets/migrations.go |
| +++ b/internal/sheets/migrations.go |
| @@ -54,4 +54,5 @@ var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina |
| var Models = []any{ |
| 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 6d8675c..11cafaa 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/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/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() } |
| +} |