Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
1895 lines (1687 loc) · 62.2 KB
/
Copy pathcli.py
File metadata and controls
1895 lines (1687 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ===============================================================================
# Copyright 2025 ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
import os
import re
from enum import Enum
from pathlib import Path
import pandas as pd
import typer
from dotenv import load_dotenv
from cli import ingest_report as report
# Anything reaching db/engine.py must be imported lazily, inside the command
# that needs it: the engine reads its connection settings at import time, and
# load_dotenv() below has not run yet. (This module is safe -- it imports no
# engine.)
from services.materialized_views import MATERIALIZED_VIEWS
# CLI should load `.env` defaults without clobbering an explicitly prepared environment.
load_dotenv()
os.environ.setdefault("OCO_LOG_CONTEXT", "cli")
cli = typer.Typer(help="Command line interface for managing the application.")
water_levels = typer.Typer(help="Water-level utilities")
water_chemistry = typer.Typer(help="Water-chemistry utilities")
data_migrations = typer.Typer(help="Data migration utilities")
cli.add_typer(water_levels, name="water-levels")
cli.add_typer(water_chemistry, name="water-chemistry")
cli.add_typer(data_migrations, name="data-migrations")
class OutputFormat(str, Enum):
json = "json"
class ThemeMode(str, Enum):
auto = "auto"
light = "light"
dark = "dark"
class SmokePopulation(str, Enum):
all = "all"
agreed = "agreed"
def _resolve_theme(theme: ThemeMode) -> ThemeMode:
if theme != ThemeMode.auto:
return theme
env_theme = os.environ.get("OCO_THEME", "").strip().lower()
if env_theme in (ThemeMode.light.value, ThemeMode.dark.value):
return ThemeMode(env_theme)
colorfgbg = os.environ.get("COLORFGBG", "")
if colorfgbg:
try:
bg = int(colorfgbg.split(";")[-1])
return ThemeMode.light if bg >= 8 else ThemeMode.dark
except (TypeError, ValueError):
pass
return ThemeMode.dark
def _validate_sql_identifier(identifier: str) -> str:
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", identifier):
raise typer.BadParameter(f"Invalid SQL identifier: {identifier!r}")
return identifier
def _palette(theme: ThemeMode) -> dict[str, str]:
mode = _resolve_theme(theme)
if mode == ThemeMode.light:
return {
"ok": typer.colors.GREEN,
"issue": typer.colors.RED,
"accent": typer.colors.BLUE,
"muted": typer.colors.BLACK,
"field": typer.colors.RED,
}
return {
"ok": typer.colors.GREEN,
"issue": typer.colors.MAGENTA,
"accent": typer.colors.BRIGHT_BLUE,
"muted": typer.colors.BRIGHT_BLACK,
"field": typer.colors.BRIGHT_YELLOW,
}
def _print_database(colors: dict[str, str]) -> None:
"""Name the database a run used, under a chemistry report's headline.
The ingest wrote through the same engine, so this is where its results went.
It's asked of the server rather than read from POSTGRES_DB, since the name in
.env doesn't prove which server localhost reached. A report still prints when
the database can't be reached (a dry run that only lists Drive files, say),
so a failure here is reported on the line rather than raised.
"""
from cli.database_info import connected_database, describe_failure
try:
name = connected_database().name
except Exception as exc:
typer.secho(
f"Database: not connected ({describe_failure(exc)})",
fg=colors["issue"],
)
return
typer.secho(f"Database: {name}", fg=colors["accent"])
@cli.command("db-info")
def db_info(
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
show which database the CLI is connected to, as the server reports it.
Reads only. Run it before an ingest to check where the data will go.
"""
from cli.database_info import connected_database, describe_failure
colors = _palette(theme)
try:
info = connected_database()
except Exception as exc:
# An operator checking their setup needs the reason, not a traceback.
typer.secho(
f"Could not connect to the database: {describe_failure(exc)}",
fg=colors["issue"],
bold=True,
err=True,
)
raise typer.Exit(1) from exc
typer.secho(f"Database: {info.name}", fg=colors["ok"], bold=True)
typer.echo(f"User: {info.user}")
typer.echo(f"Connected to: {info.connected_to}")
typer.echo(f"Server: {info.server or 'address not reported'}")
@cli.command("initialize-lexicon")
def initialize_lexicon(
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from core.initializers import init_lexicon
init_lexicon()
@cli.command("associate-assets")
def associate_assets_command(
root_directory: str = typer.Argument(
...,
exists=True,
file_okay=False,
dir_okay=True,
readable=True,
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from cli.service_adapter import associate_assets
associate_assets(root_directory)
@cli.command("restore-local-db")
def restore_local_db(
source: str = typer.Argument(
...,
help="Local .sql/.sql.gz path or gs://bucket/path.sql[.gz] URI.",
),
db_name: str | None = typer.Option(
None,
"--db-name",
help="Override POSTGRES_DB for the restore target.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from cli.db_restore import LocalDbRestoreError, restore_local_db_from_sql
try:
result = restore_local_db_from_sql(source, db_name=db_name)
except LocalDbRestoreError as exc:
typer.echo(str(exc), err=True)
raise typer.Exit(code=1) from exc
typer.echo(
"Restored "
f"{result.source} into {result.db_name} "
f"on {result.host}:{result.port} as {result.user}."
)
@cli.command("transfer-results")
def transfer_results(
summary_path: Path = typer.Option(
Path("transfers") / "metrics" / "transfer_results_summary.md",
"--summary-path",
help="Output path for markdown summary table.",
),
sample_limit: int = typer.Option(
25,
"--sample-limit",
min=1,
help="Max missing/extra key samples stored per transfer.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from transfers.transfer_results_builder import TransferResultsBuilder
builder = TransferResultsBuilder(sample_limit=sample_limit)
results = builder.build()
summary_path.parent.mkdir(parents=True, exist_ok=True)
TransferResultsBuilder.write_summary(summary_path, results)
typer.echo(f"Wrote comparison summary: {summary_path}")
typer.echo(f"Transfer comparisons: {len(results.results)}")
@cli.command("scoped-transfer")
def scoped_transfer(
pointid: list[str] = typer.Option(
...,
"--pointid",
help="Legacy PointID to transfer. Repeat --pointid for multiple values.",
),
only: list[str] = typer.Option(
None,
"--only",
help="Optional transfer family to include. Repeat for multiple values.",
),
skip: list[str] = typer.Option(
None,
"--skip",
help="Optional transfer family to skip. Repeat for multiple values.",
),
dry_run: bool = typer.Option(
False,
"--dry-run",
help="Plan the scoped transfer without writing any records.",
),
output_format: OutputFormat | None = typer.Option(
None,
"--output",
help="Optional output format",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from services.scoped_transfer import (
ScopedTransferError,
ScopedTransferOptions,
format_scoped_transfer_json,
run_scoped_transfer,
)
colors = _palette(theme)
normalized_pointids = [
pid.strip().upper() for pid in pointid if pid and pid.strip()
]
if output_format != OutputFormat.json:
# Print a quick status line so a long scoped run does not look stuck.
verb = "Planning" if dry_run else "Starting"
phase = "planning" if dry_run else "execution"
typer.secho(
f"{verb} scoped transfer for PointIDs: {', '.join(normalized_pointids)}",
fg=colors["accent"],
bold=True,
)
typer.secho(
f"Validating requested scope and preparing {phase}...",
fg=colors["muted"],
)
try:
result = run_scoped_transfer(
ScopedTransferOptions(
pointids=pointid,
only=only or [],
skip=skip or [],
dry_run=dry_run,
)
)
except ScopedTransferError as exc:
typer.secho(str(exc), fg=colors["issue"], bold=True, err=True)
raise typer.Exit(1) from exc
if output_format == OutputFormat.json:
typer.echo(format_scoped_transfer_json(result))
raise typer.Exit(result.exit_code)
header = "[SCOPED TRANSFER] DRY RUN" if result.dry_run else "[SCOPED TRANSFER]"
header_color = colors["ok"] if result.exit_code == 0 else colors["issue"]
typer.secho(header, fg=header_color, bold=True)
typer.secho("=" * 72, fg=colors["accent"])
typer.secho(
f"Requested PointIDs: {', '.join(result.pointids)}",
fg=colors["accent"],
)
typer.secho(
f"Selected families: {', '.join(result.selected_families)}",
fg=colors["accent"],
)
if result.added_prerequisites:
typer.secho(
f"Auto-added prerequisites: {', '.join(result.added_prerequisites)}",
fg=colors["muted"],
)
typer.echo()
typer.secho("FAMILY SUMMARY", fg=colors["accent"], bold=True)
for family_result in result.family_results:
detail_parts = [f"rows={family_result.applicable_source_rows}"]
if family_result.created is not None:
detail_parts.append(f"created={family_result.created}")
if family_result.skipped_existing is not None:
detail_parts.append(f"skipped_existing={family_result.skipped_existing}")
if family_result.added_as_prerequisite:
detail_parts.append("prerequisite")
if family_result.detail:
detail_parts.append(family_result.detail)
typer.secho(
f" {family_result.family:<28} {family_result.status:<10} {' '.join(detail_parts)}",
fg=(
colors["ok"]
if family_result.status in ("completed", "planned")
else colors["muted"]
),
)
if result.validation_errors:
typer.echo()
typer.secho("VALIDATION ERRORS", fg=colors["issue"], bold=True)
for error in result.validation_errors:
typer.secho(f" - {error}", fg=colors["issue"])
if result.execution_error:
typer.echo()
typer.secho("EXECUTION ERROR", fg=colors["issue"], bold=True)
typer.secho(result.execution_error, fg=colors["issue"])
raise typer.Exit(result.exit_code)
@cli.command("compare-duplicated-welldata")
def compare_duplicated_welldata(
pointid: list[str] = typer.Option(
None,
"--pointid",
help="Optional PointID filter. Repeat --pointid for multiple values.",
),
apply_transfer_filters: bool = typer.Option(
True,
"--apply-transfer-filters/--no-apply-transfer-filters",
help=(
"Apply WellTransferer-like pre-filters (GW + coordinates + transferable), "
"excluding DB-dependent non-transferred filtering."
),
),
summary_path: Path = typer.Option(
Path("transfers") / "metrics" / "welldata_duplicate_comparison_summary.csv",
"--summary-path",
help="Output CSV path for duplicate PointID summary.",
),
detail_path: Path = typer.Option(
Path("transfers") / "metrics" / "welldata_duplicate_comparison_detail.csv",
"--detail-path",
help="Output CSV path for row x differing-column detail values.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from transfers.util import get_transferable_wells, read_csv, replace_nans
df = read_csv("WellData", dtype={"OSEWelltagID": str})
if apply_transfer_filters:
if "LocationId" in df.columns:
ldf = read_csv("Location")
ldf = ldf.drop(["PointID", "SSMA_TimeStamp"], axis=1, errors="ignore")
df = df.join(ldf.set_index("LocationId"), on="LocationId")
if "SiteType" in df.columns:
df = df[df["SiteType"] == "GW"]
if "Easting" in df.columns and "Northing" in df.columns:
df = df[df["Easting"].notna() & df["Northing"].notna()]
df = replace_nans(df)
df = get_transferable_wells(df)
else:
df = replace_nans(df)
if pointid:
requested = {pid.strip() for pid in pointid if pid and pid.strip()}
df = df[df["PointID"].isin(requested)]
if "PointID" not in df.columns:
typer.echo("WellData has no PointID column after filtering.")
raise typer.Exit(code=1)
dup_mask = df["PointID"].duplicated(keep=False)
dup_df = df.loc[dup_mask].copy()
summary_rows: list[dict] = []
detail_rows: list[dict] = []
if not dup_df.empty:
for pid, group in dup_df.groupby("PointID", sort=True):
diff_cols: list[str] = []
for col in group.columns:
series = group[col]
non_null = series[~series.isna()]
if non_null.empty:
continue
if len({str(v) for v in non_null}) > 1:
diff_cols.append(col)
summary_rows.append(
{
"pointid": pid,
"duplicate_row_count": int(len(group)),
"differing_column_count": int(len(diff_cols)),
"differing_columns": "|".join(diff_cols),
}
)
normalized = group.reset_index(drop=False).rename(
columns={"index": "source_row_index"}
)
for row_num, row in normalized.iterrows():
for col in diff_cols:
value = row.get(col, None)
detail_rows.append(
{
"pointid": pid,
"row_number": int(row_num),
"source_row_index": int(row["source_row_index"]),
"column": col,
"value": value,
}
)
summary_df = pd.DataFrame(summary_rows)
if not summary_df.empty:
summary_df = summary_df.sort_values(
by=["duplicate_row_count", "pointid"], ascending=[False, True]
)
detail_df = pd.DataFrame(detail_rows)
if not detail_df.empty:
detail_df = detail_df.sort_values(
by=["pointid", "row_number", "column"], ascending=[True, True, True]
)
summary_path.parent.mkdir(parents=True, exist_ok=True)
detail_path.parent.mkdir(parents=True, exist_ok=True)
summary_df.to_csv(summary_path, index=False)
detail_df.to_csv(detail_path, index=False)
if summary_df.empty:
typer.echo("No duplicated WellData PointIDs found for current filters.")
typer.echo(f"Wrote empty summary: {summary_path}")
typer.echo(f"Wrote empty detail: {detail_path}")
return
total_dup_rows = int(len(dup_df))
total_dup_pointids = int(summary_df["pointid"].nunique())
typer.echo(
f"Found {total_dup_pointids} duplicated PointIDs across {total_dup_rows} rows."
)
typer.echo(f"Wrote summary: {summary_path}")
typer.echo(f"Wrote detail: {detail_path}")
preview = summary_df.head(20)
typer.echo("\nTop duplicate PointIDs:")
for row in preview.itertuples(index=False):
typer.echo(
f"- {row.pointid}: rows={row.duplicate_row_count}, "
f"differing_columns={row.differing_column_count}"
)
@cli.command("well-smoke-test")
def well_smoke_test(
sample_size: int = typer.Option(
25,
"--sample-size",
min=1,
help="Number of wells to sample.",
),
population: SmokePopulation = typer.Option(
SmokePopulation.agreed,
"--population",
help="Sample from all wells or transfer-agreed wells.",
),
all_wells: bool = typer.Option(
False,
"--all-wells/--sampled",
help="Check all wells in the selected population instead of sampling.",
),
seed: int = typer.Option(
42,
"--seed",
help="Random seed for deterministic sampling.",
),
detail_path: Path = typer.Option(
Path("transfers") / "metrics" / "well_smoke_test_detail.csv",
"--detail-path",
help="Output CSV path for per-well per-entity smoke-test rows.",
),
summary_path: Path = typer.Option(
Path("transfers") / "metrics" / "well_smoke_test_summary.json",
"--summary-path",
help="Output JSON path for smoke-test summary.",
),
fail_on_mismatch: bool = typer.Option(
False,
"--fail-on-mismatch/--no-fail-on-mismatch",
help="Exit with code 1 if any mismatches are found.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
from transfers.smoke_test import (
SmokePopulation as SmokePopulationModel,
run_well_smoke_test,
write_smoke_outputs,
)
payload = run_well_smoke_test(
sample_size=sample_size,
population=SmokePopulationModel(population.value),
seed=seed,
all_wells=all_wells,
)
write_smoke_outputs(payload, detail_path=detail_path, summary_path=summary_path)
sampled_wells = payload.get("sampled_wells", 0)
mismatch_count = payload.get("mismatch_count", 0)
value_mismatch_count = payload.get("value_mismatch_count", 0)
fail_count = payload.get("well_fail_count", 0)
typer.echo(
f"Smoke test complete: sampled_wells={sampled_wells}, "
f"presence_mismatches={mismatch_count}, "
f"value_mismatches={value_mismatch_count}, "
f"failed_wells={fail_count}"
)
typer.echo(f"Wrote detail: {detail_path}")
typer.echo(f"Wrote summary: {summary_path}")
if mismatch_count or value_mismatch_count:
failed_wells = payload.get("failed_wells", [])[:20]
typer.echo(f"Sample failed wells (up to 20): {failed_wells}")
if value_mismatch_count:
entity_results = payload.get("entity_results", [])
value_mismatches = [
r
for r in entity_results
if r.get("value_status") not in {"MATCH", "NOT_APPLICABLE"}
]
typer.echo("\nValue mismatches:")
for row in value_mismatches[:100]:
pointid = row.get("pointid")
entity = row.get("entity")
status = row.get("value_status")
missing = row.get("missing_value_sample") or []
extra = row.get("extra_value_sample") or []
typer.echo(
f"- {pointid} | {entity} | {status} | "
f"missing={missing[:3]} | extra={extra[:3]}"
)
if len(value_mismatches) > 100:
typer.echo(
f"... truncated {len(value_mismatches) - 100} additional value mismatches"
)
if mismatch_count or value_mismatch_count:
if fail_on_mismatch:
raise typer.Exit(code=1)
@cli.command("well-inventory-csv")
def well_inventory_csv(
file_path: str = typer.Argument(
...,
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
parse and upload a csv to database
"""
# TODO: use the same helper function used by api to parse and upload a WI csv
from cli.service_adapter import well_inventory_csv
result = well_inventory_csv(file_path)
payload = result.payload if isinstance(result.payload, dict) else {}
summary = payload.get("summary", {})
validation_errors = payload.get("validation_errors", [])
detail = payload.get("detail")
colors = _palette(theme)
report.banner(
(
"[WELL INVENTORY IMPORT] SUCCESS"
if result.exit_code == 0
else "[WELL INVENTORY IMPORT] COMPLETED WITH ISSUES"
),
colors,
ok=result.exit_code == 0,
)
if summary:
report.summary_section(report.import_summary_rows(summary, colors), colors)
if validation_errors:
# The importer reports a row number with every error, so anything
# without one is still filed under a row -- an unlabeled one.
entries = report.parse_validation_entries(validation_errors, default_row="?")
typer.secho("VALIDATION", fg=colors["accent"], bold=True)
typer.secho(
f"Validation errors: {len(validation_errors)}",
fg=colors["issue"],
bold=True,
)
typer.secho("Most common validation errors:", fg=colors["accent"], bold=True)
report.common_errors_table(entries, colors)
shown = report.grouped_row_errors(entries, colors, show_input=True)
report.truncation_note(len(validation_errors), shown, colors)
if detail:
typer.secho("ERRORS", fg=colors["accent"], bold=True)
typer.secho(f"Error: {detail}", fg=colors["issue"], bold=True)
report.rule(colors)
raise typer.Exit(result.exit_code)
@water_levels.command("bulk-upload")
def water_levels_bulk_upload(
file_path: str = typer.Option(
...,
"--file",
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
help="Path to CSV file containing water level rows",
),
output_format: OutputFormat | None = typer.Option(
None,
"--output",
help="Optional output format",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
parse and upload a csv
"""
# TODO: use the same helper function used by api to parse and upload a WL csv
from cli.service_adapter import water_levels_csv
colors = _palette(theme)
source = Path(file_path)
if not source.exists() or not source.is_file():
typer.secho(
f"File not found: {source}",
fg=colors["issue"],
bold=True,
err=True,
)
raise typer.Exit(1)
pretty_json = output_format == OutputFormat.json
try:
result = water_levels_csv(file_path, pretty_json=pretty_json)
except (FileNotFoundError, PermissionError, IsADirectoryError) as exc:
typer.secho(str(exc), fg=colors["issue"], bold=True, err=True)
raise typer.Exit(1)
# Backward compatibility for tests/mocks that return only an int.
if isinstance(result, int):
raise typer.Exit(result)
if output_format == OutputFormat.json:
typer.echo(result.stdout)
raise typer.Exit(result.exit_code)
payload = result.payload if isinstance(result.payload, dict) else {}
summary = payload.get("summary", {})
validation_errors = payload.get("validation_errors", [])
rows_with_issues = summary.get("validation_errors_or_warnings", 0)
# Rows can load while others fail, so a zero exit with issues is still
# "completed with issues" rather than a clean success.
report.banner(
(
"[WATER LEVEL IMPORT] SUCCESS"
if result.exit_code == 0 and not rows_with_issues
else "[WATER LEVEL IMPORT] COMPLETED WITH ISSUES"
),
colors,
ok=result.exit_code == 0 and not rows_with_issues,
)
# This importer reports most errors as preformatted strings; anything with
# no row number is listed on its own below rather than grouped.
entries = report.parse_validation_entries(validation_errors, default_field="error")
if summary:
report.summary_section(report.import_summary_rows(summary, colors), colors)
if entries:
typer.secho("VALIDATION SUMMARY", fg=colors["accent"], bold=True)
report.common_errors_table(entries, colors)
if validation_errors:
typer.secho("VALIDATION", fg=colors["accent"], bold=True)
typer.secho(
f"Validation errors: {len(validation_errors)}",
fg=colors["issue"],
bold=True,
)
shown = report.grouped_row_errors(entries, colors)
rowless = [
f"{e.field}: {e.message}" if e.field and e.field != "error" else e.message
for e in entries
if e.row is None
]
for entry in rowless[: max(0, report.MAX_ROW_ERRORS_SHOWN - shown)]:
typer.secho(f" - {entry}", fg=colors["issue"])
shown += 1
report.truncation_note(len(validation_errors), shown, colors)
report.rule(colors)
raise typer.Exit(result.exit_code)
@water_chemistry.command("bulk-upload")
def water_chemistry_bulk_upload(
file_path: str = typer.Option(
...,
"--file",
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
help="Path to LIMS .xlsx workbook containing chemistry results.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
parse a LIMS chemistry workbook and load it into the NMA Major/Minor
chemistry tables. Each distinct lab sample (WCLab_ID) goes to the sample
record named with its field sample ID (SamplePointID): the field sheet's,
if it has no lab id yet, or a new one under that ID. A lab sample already
recorded for the well is skipped. A row that fails to map, an unknown well,
a missing letter or SampleDate, or a named record that can't take the
results aborts the whole file.
"""
from cli.service_adapter import chemistry_lims_xlsx
colors = _palette(theme)
result = chemistry_lims_xlsx(file_path)
payload = result.payload if isinstance(result.payload, dict) else {}
summary = payload.get("summary", {})
report.banner(
(
"[WATER CHEMISTRY IMPORT] SUCCESS"
if result.exit_code == 0
else "[WATER CHEMISTRY IMPORT] COMPLETED WITH ISSUES"
),
colors,
ok=result.exit_code == 0,
)
_print_database(colors)
typer.echo()
if summary:
report.summary_section(report.import_summary_rows(summary, colors), colors)
# These lists are what the engineer acts on, so they print in full.
report.bullet_section(
"CREATED SAMPLES",
payload.get("created_samples", []),
colors,
color_key="ok",
limit=None,
formatter=lambda sample: (
f"{sample['sample_point_id']} (WCLab_ID {sample.get('wclab_id')}): "
f"{sample.get('rows', 0)} row(s)"
),
)
report.bullet_section(
"ADOPTED (field-sheet sample)",
payload.get("adopted_samples", []),
colors,
color_key="ok",
limit=None,
formatter=lambda sample: (
f"{sample['sample_point_id']} (WCLab_ID {sample.get('wclab_id')}): "
f"{sample.get('rows', 0)} row(s)"
),
)
report.bullet_section(
"SKIPPED (already ingested)",
payload.get("skipped_duplicates", []),
colors,
color_key="field",
title_color_key="muted",
limit=None,
formatter=lambda dupe: f"{dupe['pointid']} (WCLab_ID {dupe.get('wclab_id')})",
)
report.bullet_section(
"WARNINGS (loaded, but check these)",
payload.get("warnings", []),
colors,
color_key="field",
limit=None,
)
report.validation_errors_section(payload.get("validation_errors", []), colors)
report.rule(colors)
raise typer.Exit(result.exit_code)
def _describe_failed_file(record: dict) -> str:
"""Why a Drive workbook failed, however the ingest reported it.
A hard failure carries an ``error``; a data-quality abort carries only the
validation errors, and the first of those is the useful headline.
"""
detail = record.get("error")
if not detail:
errors = record.get("payload", {}).get("validation_errors") or []
if errors:
detail = errors[0]
if len(errors) > 1:
detail += f" (+{len(errors) - 1} more)"
else:
detail = "ingestion aborted"
return f"{record['name']}: {detail}"
@water_chemistry.command("sync-drive")
def water_chemistry_sync_drive(
folder_id: str = typer.Option(
None,
"--folder-id",
help="Google Drive folder id to scan. Defaults to $CHEMISTRY_DRIVE_FOLDER_ID.",
),
dry_run: bool = typer.Option(
False,
"--dry-run",
help="List new files without downloading, ingesting, or updating the manifest.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
ingest LIMS chemistry workbooks from a Google Drive folder. Run on demand
by an engineer -- this does no polling or scheduling. New or changed files
are ingested; a manifest of ingested files is kept in GCS so
already-processed files are skipped.
"""
from services.chemistry_drive import ChemistryDriveConfigError, sync_and_ingest
colors = _palette(theme)
try:
result = sync_and_ingest(folder_id=folder_id, dry_run=dry_run)
except ChemistryDriveConfigError as exc:
typer.secho(str(exc), fg=colors["issue"], bold=True, err=True)
raise typer.Exit(1) from exc
summary = result.to_payload()["summary"]
report.banner(
(
"[CHEMISTRY DRIVE SYNC] DRY RUN"
if result.dry_run
else "[CHEMISTRY DRIVE SYNC]"
),
colors,
ok=result.exit_code == 0,
)
_print_database(colors)
typer.secho(f"Folder: {result.folder_id}", fg=colors["accent"])
typer.echo()
report.summary_section(
[
("files_seen", summary["files_seen"], "accent"),
("new_files", summary["new_files"], "accent"),
("ingested", summary["ingested"], "ok"),
("skipped", summary["skipped"], "muted"),
("failed", summary["failed"], "issue" if summary["failed"] else "ok"),
],
colors,
label_width=12,
value_width=6,
divider=False,
)
if result.dry_run:
report.bullet_section(
"NEW FILES (not ingested)",
result.new_files,
colors,
color_key="field",
title_color_key="accent",
limit=None,
)
report.bullet_section(
"INGESTED",
result.ingested,
colors,
color_key="ok",
limit=None,
formatter=lambda record: (
f"{record['name']}: {record.get('rows_imported', 0)} row(s)"
),
)
report.bullet_section(
"FAILED",
result.failed,
colors,
color_key="issue",
limit=None,
formatter=_describe_failed_file,
)
report.rule(colors)
raise typer.Exit(result.exit_code)
@water_chemistry.command("manifest-status")
def water_chemistry_manifest_status(
name: str = typer.Option(
None,
"--name",
help="Only show workbooks whose file name contains this text.",
),
theme: ThemeMode = typer.Option(
ThemeMode.auto, "--theme", help="Color theme: auto, light, dark."
),
):
"""
show which databases each chemistry workbook has been ingested into. Reads
every per-database manifest in GCS and merges them for display; writes
nothing, so it is safe to run against any environment.
"""
from services.chemistry_drive import ChemistryDriveConfigError, manifest_overview
colors = _palette(theme)