-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
1556 lines (1426 loc) · 62.3 KB
/
app.py
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
#!/user/bin/env python3
# pylint: disable=trailing-whitespace
# ruff: noqa: F841, ANN101, ANN001, D415, RET505, I001, ARG004, PLR0913
# ruff: noqa: D301
"""Module: PyCriteria Command/REPL Terminal app.
Usage: Commands and REPL
-------------------------
- Multi-line level nested commands structure.
- Run - Core/BASE command AND ANCHORED command.
- Clear - SUB COMMAND, nested under Run:
to clear REPL/screen.
- Load - TOP INTENT, nested under Run
- Views - SUB COMMAND, nested under Load
Switches between sub-views of the data
- ToDo - SUB COMMAND, nested under Load
Switches between sub-views of the ToDo tasks
- Find - TOP INTENT, nested under Run
- Locate - SUB COMMAND, nested under Find
Locate a record by ID (row)
Future by column value, or row search term
- Edit - TOP INTENT, nested under Run
Core activity/action of the app for user
- Note - SUB COMMAND, under Edit: Edits a note
- Mode - Option, nested with Note: to enter an edit mode
Bundles add, update and delete under one command
- ToDo - SUB COMMAND, under Edit: Edits a ToDo field
- Exit - TOP INTENT, nested under Run
If Time, merge the Note commands into one command,
and use a flag/choice to switch action
Linting:
-------------------------
- pylint: disable=trailing-whitespace
- ruff: noqa:
I001 unsorted-imports
Import block is un-sorted or un-formatted
F841: unused-variable
Local variable {name} is assigned to but never used
ANN101 missing-type-self
Missing type annotation for {name} in method
ANN101: missing-type-self
Missing type annotation for {name} in method
RET505 superfluous-else-return
Unnecessary {branch} after return statement
- noqa: W293
Critieria:
LO2.2: Clearly separate and identify code written for the application and
the code from external sources (e.g. libraries or tutorials)
LO2.2.3: Clearly separate code from external sources
LO2.2.4: Clearly identify code from external sources
LO6: Use library software for building a graphical user interface,
or command-line interface, or web application, or mathematical software
LO6.1 Implement the use of external Python libraries
LO6.1.1 Implement the use of external Python libraries
where appropriate to provide the functionality that the project requires.
-------------------------
Standard Libraries
:imports: typing.Literal
3rd Paty Imports
:imports: rich
:imports: rich.panel
:imports: rich.table
:imports: click
:imports: click_repl
:imports: pandas
Local Imports
:imports: commands
:imports: controller
:imports: sidecar
Classes
-------------------------
:class: Controller: Controller for the Terminal App.
:class: ColumnSchema: Column Schema DataViews
:class: Headers: Views by Headers selection: READING, LOADING, VIEWS, DISPLAY
:class: RICHStyler: Rich.Style Defintions class and methods for the app.
:class: WebConsole: Console class and methods for WEB versions of the app.
:class: Inner: Inner Terminal layouts, arrangement.Deprecate? # noqa
:class: Display: Shared Mixed resposnibility with CriteriaApp, and Record
Refactor candidates.
Evoling design artefact
:class: Record: Individual Records, and Records Display/Controller/Model:
:class: Editor: C(R)UD Operations, and Editor Controller/Model:
Global Variables:,
-------------------------
:var: Logs: Logging.py - Logging.py for app.py
:var: DataControl: Controller.py - DataController for DataModel, shared, alias
:var: Webconsole: Controller.py - WebConsole for WEB versions of the app.
:var: window: app.py - Window class for Terminal Layouts, Panels, Cards.
:var: App: app.py - Key DataConrtooler/Controller.py
"""
# 1. Std Lib
from typing import Literal
import click # type: ignore
# 2. 3rd Party
from click_repl import register_repl # type: ignore
from pandas import pandas as pd # type: ignore
from rich import inspect as inspector, print as rprint # type: ignore
from rich.console import Console # type: ignore
from rich.panel import Panel # type: ignore
# 3. Local: Note the controller * intentionally imports all from the module
from controller import (Controller as Actions, DataController,
Display, Results, WebConsole,
configuration, gspread, Record, Editor,
RICHStyler as rstyle, )
from modelview import (Views, Head, ) # type: ignore
from sidecar import (AppValues as Val, ProgramUtils as utils,
CliStyles as styles, )
# Global Modules/Objects
# 1.1 controller.py
DataControl: DataController = DataController(Actions.load_wsheet())
Webconsole: WebConsole = WebConsole(configuration.Console.WIDTH,
configuration.Console.HEIGHT)
class Valid:
"""Command/Input Validation"""
def __init__(self):
"""Initialize."""
pass
# Check
@staticmethod
def index(ctx, param, value) -> int:
"""Check if value is in range.
:param ctx: click.Context - Click Context
:param param: click.Parameter - Click Parameter
:param value: str - String to sanitised
:return: int - Index value
"""
if value is None:
raise click.BadParameter(
'Try again, enter a numerical value.')
if not isinstance(value, int):
raise click.BadParameter(
'Index must be a number.')
if not 0 < value <= App.get_range:
raise click.BadParameter(
f'Index must be between 0 and {App.get_range}.')
return value
# Check
@staticmethod
def mode(ctx, param, value) -> str | None:
"""Check the mode."""
if value is not None and value.lower() in ['add', 'update', 'delete']:
mode = value.lower().capitalize()
click.secho(message=f"{mode}ing the record: .......",
fg=styles.infofg, bold=styles.infobold)
return value
else:
click.secho(message="Exiting Editing Mode. Invalid entry.",
fg=styles.invalidfg, bold=styles.invalidbold)
return None
@staticmethod
def checkstatus(state) -> str | None:
"""Check the status."""
if state.lower() in ['todo', 'wip', 'done', 'missing']:
click.echo(message=f"🆕 ToDo Status, {state} 🆕")
return state
else:
click.echo(message="Exiting Editing Mode. Try again.")
return None
@staticmethod
def checkmode(edits: str, index: int) -> str | None:
"""Check the mode."""
if edits.lower() in [App.values.Edit.ADD,
App.values.Edit.UPDATE,
App.values.Edit.DELETE,
'toggle']:
mode = edits.lower().capitalize()
click.echo(message=f"🆕 {mode}ing a Record, in row {index} 🆕")
return edits
else:
click.echo(message="Exiting Editing Mode. Try again.")
return None
@staticmethod
def checkcommand(mode: str) \
-> str | None: # noqa # Pep8 E125
"""Check the mode, translate to edit comand tyoe."""
allowed = {App.values.Edit.ADD,
App.values.Edit.UPDATE,
App.values.Edit.DELETE,
App.values.Edit.ToDo.TOGGLE}
if mode in allowed:
if mode == App.values.Edit.ADD:
return App.values.Edit.INSERT
elif mode == App.values.Edit.UPDATE:
return App.values.Edit.APPEND
elif mode == App.values.Edit.DELETE:
return App.values.Edit.CLEAR
elif mode == App.values.Edit.ToDo.TOGGLE:
return App.values.Edit.ToDo.SELECT
return None
else:
return None
@staticmethod
def isinrange(index) -> bool:
"""Check if index is in range."""
return True if 1 <= index <= App.get_range else False
class Window:
"""Window: Arrange Terminal Layouts, Panels, Cards.
Methods:
--------------------------------------------
:method: Window.sendto
:method: Window.showrecord
:method: Window.printpane
:method: Window.printpanels
:method: Window.showedited
:method: Window.showmodified
"""
def __init__(self): # noqa
"""Initialize."""
pass
@staticmethod
def sendto(value, switch: bool) -> Record | None:
"""Switch Record for dual-return statements.
:param value: Record - Individual Record to display
:param switch: bool - Switch to send to the Editor or not.
"""
return value if switch else None
@staticmethod
def showrecord(data: pd.Series | pd.DataFrame,
sendtolayout: bool = True,
command: str = '',
displayon: bool = True,
debug: bool = False) -> Record | None:
"""Display Record.
:param data: pd.Series | pd.DataFrame - Individual Record to display
:param sendtolayout: bool - Switch to send to the Editor or not.
App.values.Display.TOLAYOUT = True => Builds formatted layout.
App.values.Display.TOTERMINAL = False => Builds simple layout.
:param command: str - Command to send to the Editor.
:param displayon: bool - Switch to display or not.
:param debug: bool - Switch to debug mode or not.
:return: Record | None - Individual Record to display or None
"""
# Data is not empty
if data.empty is False:
# Individual record holds the singular record, handles displays
# Selecting different calls on the individual record yields
# different displays/outputs.
# Only displays a pd.Series, implicitly.
# Not designed for results >1, unless part of a loop.
individual = Record(series=data, source=data)
individual.editmode = command
# Debug and Inspect
if debug is True:
rprint("Debug Mode: Show Record")
inspector(individual)
# Display Show Record or Supress
if displayon:
# If sendtolayout is True, builds the layout | Not None.
if individual.card(consolecard=Webconsole.console,
sendtoterminal=sendtolayout) is not None:
# Print Panels
window.printpanels(record=individual)
else:
# Print Simple Card of all values
click.echo("Displaying Simple Card")
individual.card(consolecard=Webconsole.console)
# Forwards the individual record to the Editor.
return Window.sendto(individual, sendtolayout)
# Data is empty and exits
return None
@staticmethod
def configpanel(render, #
pstyle=None,
ht=None,
wd=None,
border=None,
fit: bool = True,
title: str = '',
sub: str = '',
padsize: str = '',
hlight: bool = True) -> Panel:
"""Configure Panel.
:return: Panel - Configured Panel
"""
def _pad(size) -> int | tuple[int] | \
tuple[int, int] | \
tuple[int, int, int, int]: # noqa E128
"""Pad the image."""
sizes = {
'small': (0, 1),
'medium': (0, 2),
'large': (0, 3)
}
return sizes.get(size, 0)
return Panel(
renderable=render,
title=title,
expand=fit,
subtitle=sub,
width=wd,
height=ht,
padding=_pad(padsize),
title_align='center', # noqa
subtitle_align='center', # noqa
style=pstyle,
border_style=border, )
@staticmethod
def printpane(panel: str, printer: Console, text: str | None = '') -> None:
"""Print Pane.
:param panel: str - Panel to print
:param printer: Console - Console to print to
:param text: str - Text to display
:return: None
"""
if panel == 'banner':
pane = window.configpanel(
render="",
title="📝 PyCriteria 📝",
sub=f"📝 You are in {text} Mode 📝",
padsize='medium',
ht=2,
pstyle=rstyle.panel(grey=11),
border='bright_white')
printer.print(pane)
elif panel == 'foot' and text is None:
pane = window.configpanel(
render="",
padsize='medium',
ht=1,
pstyle=rstyle.panel(grey=11),
border='bright_white')
printer.print(pane)
@staticmethod
def printpanels(record: Record) -> None:
"""Print Panels.
:param record: Record - Individual Record to display
:return: None
"""
# Record is the data loader for single record.
if record is not None:
# Print: the Banner at top of the Record's Display
window.printpane(panel='banner',
printer=Webconsole.console,
text=record.modedisplay())
# Switch to Rich/Terminal display
# Record builds the data views: Header, Card, Footer
header = \
record.header(
consolehead=Webconsole.console,
sendtolayout=True,
gridfit=True)
current = \
record.editable(
consoleedit=Webconsole.console,
sendtolayout=True)
footer = \
record.footer(
consolefoot=Webconsole.console,
sendtolayout=True)
# Print: the Panel as a Group of Renderables
# noinspection PyArgumentEqualDefault
record.panel(consolepane=Webconsole.console,
renderable=header,
fits=True,
sendtolayout=False)
# noinspection PyArgumentEqualDefault
record.panel(consolepane=Webconsole.console,
renderable=current,
fits=True,
align='center',
sendtolayout=False)
# noinspection PyArgumentEqualDefault
record.panel(consolepane=Webconsole.console,
renderable=footer,
fits=True,
sendtolayout=False)
# Print: the Panel as a Group of Renderables
window.printpane(panel='foot',
printer=Webconsole.console)
@staticmethod
def showedited(editeddata: pd.Series | pd.DataFrame,
sendtoeditor: bool = False,
debug: bool = False) -> Record | None:
"""Display Edited Record.
:param editeddata: pd.Series | pd.DataFrame
- Individual Record to display
:param sendtoeditor: bool - Switch to send to the Editor or not.
:param debug: bool - Switch to debug mode or not.
:return: Record | None - Individual Record to display or None
"""
if debug:
inspector(editeddata)
return None
if editeddata.empty is False:
individual = Record(source=editeddata)
if individual.card(consolecard=Webconsole.console) is not None:
window.printpanels(record=individual)
else:
individual.card(consolecard=Webconsole.console)
return individual if sendtoeditor else None
return None
@staticmethod
def showmodified(editeddata: pd.Series,
editor: Editor,
commandtype: str,
dataview: Literal['show', 'compare'] = 'show',
debug=False) -> None:
"""Display Modified Record.
:param editeddata: pd.Series - Individual Record to display
:param editor: Editor - Editor to use
:param commandtype: str
- Command type to use
:param dataview: Literal['show', 'compare'] - Data view to use
:param debug: bool - Switch to debug mode or not.
:return: None
"""
# Display single records
if Record.checksingle(editeddata):
# Was checking if Record.ismodified was truthy, if state persists
# But a record's state between transactions are not kept in state
# A new record per find/locate is created for a stateless record
# So dropped this guard, as stateful transactions are not in scope.
# State could be if time permits, if a lastmodified field is saved.
# Is saved to the remote database, but not in the local record.
# Therefore not in scope for version: 1.0.0.alpha+
click.echo(f'Command Type: {editor.command}')
click.echo(f'Edit Type: {editor.editmode}')
if editor.command == commandtype:
if debug is True:
click.echo(message="==========Displaying: "
"Changes=========\n")
# 1. Display the Edited record
if dataview == 'show': # show
window.showedited(editeddata=editeddata)
elif dataview == 'compare': # compare
window.comparedata(editeddata=editeddata,
editor=editor,
debugdisplay=False) # noqa
# [DEBUG]
if debug is True:
click.echo(message="=== [DEBUG] Saving: "
"changes made [DEBUG]==\n")
click.echo(f" Modified: {editor.lastmodified} ")
else:
click.echo(message="No changes made. Check last command?")
# Switch confirmation on a command's type
click.echo(message="Exiting: Command completed")
else:
click.echo(message="No changes made. Bulk edits not supported.")
@staticmethod
def comparedata(editeddata: pd.Series,
editor: Editor,
debug=False, debugdisplay=False) -> None:
"""Compare Old and New side by side.
:param editeddata: pd.Series - Individual Record to display
:param editor: Editor - Editor to use
:param debug: bool - Switch to debug mode or not.
:param debugdisplay: bool - Switch to debug display mode or not.
:return: None
"""
def _setrecordprops(record: Record, aeditor: Editor) -> None:
"""Set Record Properties.
:param record: Record - Record to use
:return: None
"""
record.editmode = aeditor.editmode
record.modified = aeditor.lastmodified
record.command = aeditor.command
if debug is True:
inspector(editeddata)
if editeddata.empty is False and editor.ismodified:
# 0. Create the Old and New Records, locallt
oldrecord: Record = editor.record
newrecord: Record = Record(series=editor.newresultseries)
_setrecordprops(record=newrecord, aeditor=editor)
# 1. Display the Edited recor
left = oldrecord.editable(
consoleedit=Webconsole.console,
sendtolayout=App.values.DISPLAYING,
title="Original Record")
right = newrecord.editable(
consoleedit=Webconsole.console,
sendtolayout=App.values.DISPLAYING,
title="Updated Record")
# Compare Old with New, else just show the new
if left is not None or right is not None:
window.printpane(panel="bannerfull",
printer=Webconsole.console)
header = newrecord.header(
consolehead=Webconsole.console,
sendtolayout=App.values.Display.TOLAYOUT,
gridfit=True,
debug=debugdisplay)
sidebyside = newrecord.comparegrid(
container=Webconsole.table,
left=left,
right=right,
sendtolayout=App.values.Display.TOLAYOUT,
fit=True,
debug=debugdisplay)
newrecord.panel(
consolepane=Webconsole.console,
renderable=header,
fits=True,
sendtolayout=App.values.Display.TOTERMINAL)
newrecord.panel(
consolepane=Webconsole.console,
renderable=sidebyside,
fits=True,
sendtolayout=App.values.Display.TOTERMINAL)
else:
window.showedited(editeddata=editeddata, debug=debug)
class CriteriaApp:
"""PyCriteria Terminal App.
:property: values: AppValues - App Values
Methods:
:method: get_data - get the remote data, alias for DataController
:method: display_data -
:method: update_appdata -
:method: display_view -
:method: display_todo -
:method: query_data -
:method: search_data -
:method: search_rows -
:method: rows -
:method: index -
:method: value
:method: get_results
"""
values: Val
views: Views
appdata: DataController
data: pd.DataFrame
range: int
editmode: list[str] = ['none', 'add', 'update', 'delete']
def __init__(self, applicationdata: DataController) -> None:
"""Initialize."""
self.values = Val()
self.views = Views()
self.appdata = applicationdata
self.data = applicationdata.dataframe
self.range = len(self.data)
@staticmethod
def get_data() -> pd.DataFrame:
"""Get the dataframe from the context.
:return: pd.DataFrame - Dataframe
"""
wsheet: gspread.Worksheet = Actions.load_wsheet()
dataframe: pd.DataFrame = \
DataControl.load_dataframe_wsheet(wsheet=wsheet)
return dataframe
@property
def get_range(self) -> int:
"""Get the range of the dataframe.
:param self
:return: int - Range of the dataframe
"""
self.range = len(self.data)
return self.range
# Depends on ToDo command
def command_todo(self, dataframe: pd.DataFrame,
todoview: str = 'All',
label: str = "Progress") -> None:
"""Display the dataframe by view option/choice.
:param dataframe: pd.DataFrame - Dataframe to display
:param todoview: str - View option
:param label: str - Label to display
:return: None
"""
# Select the view
def vues(choice: str) -> list[str]:
"""Select the (predefined) view -> Header. Columns
:param choice: str - View option
:return: list[str] - Columns
"""
#
headers: list[str] = []
if choice.lower() == self.views.All.lower():
headers = Head.ToDoAllView
elif choice.lower() == self.views.Simple.lower():
headers = Head.ToDoSimpleView
elif choice.lower() == self.views.Notes.lower():
headers = Head.ToDoNotesView
elif choice.lower() == self.views.Done.lower():
headers = Head.ToDoProgressView
elif choice.lower() == self.views.Grade.lower():
headers = Head.ToDoGradeView
elif choice.lower() == self.views.Review.lower():
headers = Head.ToDoReviewView
else:
headers = Head.ProjectView
return headers
# Configure the bulk ouput as Table
self.output(data=dataframe, cols=vues(todoview), title=label)
#
def command_view(self, dataframe: pd.DataFrame,
viewer: list[str] | None = None,
label: str = 'Overview') -> None:
"""Display the dataframe.
:param dataframe: pd.DataFrame - Dataframe to display
:param viewer: list[str] - List of views to display
:param label: str - Label to display
:return: None
"""
# Select the view's header
headers: list[str] = Head.OverviewViews if viewer is None else viewer
# Configure the bulk ouput as Table
self.output(data=dataframe, cols=headers, title=label)
#
@staticmethod
def output(data: pd.DataFrame,
cols: list[str],
title: str) -> None:
"""Command Output flow. Shared by common commands
:param data: pd.DataFrame - Dataframe to display
:param cols: list[str] - List of columns to display
:param title: str - Title to display
:return: None
"""
# Configure the bulk ouput as Table with headers
Webconsole.table = Webconsole.configure_table(headers=cols)
# Display the sub frame dataview
Display.display_subframe(dataframe=data,
consoleholder=Webconsole.console,
consoletable=Webconsole.table,
headerview=cols,
viewfilter=title)
# Signal from completion of command
click.echo(message='Your data is refreshed/rehydrated')
#
def update_appdata(self, context, dataframe: pd.DataFrame) -> None:
"""Update the app data.
:param context: click.Context - Click context
:param dataframe: pd.DataFrame - Dataframe to update
:return: None
"""
# Update the context
context.obj = dataframe
# Update the appdata
DataControl.dataframe = dataframe
self.appdata.dataframe = dataframe
self.data = dataframe
App: CriteriaApp = CriteriaApp(applicationdata=DataControl)
window: Window = Window()
# ########################################################################### #
# App Commands
# - Run
# - load
# - todo -s | --select: Choose a sub view
# - views -s | --select: Choose a sub view
# - find
# - locate -i -a | --index --axis
# index: input range
# axis: index search focus
# - edit
# - note -m -i -n -a | --mode --index --note --axis
# mode: editmode: add, update, delete
# index: input range
# note: input note
# axis: index search focus
# - progress -m -i -n -a | --mode --index --note --axis
# mode: editmode: toggle
# index: input range
# note: input note
# axis: index search focus
# ########################################################################### #
# 0. Run: Base Command: Anchors all Intent and Actions
# Does not to anything but command achitecture/infrastructure and --help
@click.group(name=App.values.Run.cmd, short_help='Type: --help')
@click.pass_context
def run(ctx: click.Context) -> None: # noqa
"""Level: Run. Type: about to learn to use this CLI.
\f
:param ctx: click.Context
:return: None: Produces stdout --help text
"""
# 0.1 Run: Base Command: Clear
# Clears the REPL using click.clear()
@run.command("clear", help="Cmd: Clear the screen",
short_help="Cmd: Clear the screen")
@click.pass_context
def clear(ctx: click.Context) -> None: # noqa
"""Clear the screen."""
click.echo("Screen cleared")
click.clear()
# 1. Load Data: Have the user load the data:
# READ of CRUD Ops (Create, _READ_, Update, Delete)
# Load intents/actions does the bulk data loading
# Uses App.values.x.x(.x) String values for configuration.
@run.group(name=App.values.Load.cmd, short_help='Load Mode: Todos & Views')
@click.pass_context
def load(ctx: click.Context) -> None: # noqa
"""INTENT: Load: => ACTIONS/Commands: todo, views:
=== === === === === === === === === === === === ===\n
\b
Start Typing:
- Use 'tab' to autocomplete the current menu option,
- Then 'space' to start the sub-menu.
- Then 'tab' or 'enter' to complete \n
___\n
\b
Hit 'enter' to enter the prompt sequence for option.
Can use the, e.g., `-o` on same line as command.
However the , prompt entery is preferred.\n.
===\n
\b
ACTIONS/Commands:
- todo
....'-s' selects | default: All.
- views
....'-s' selects | default: Overview \n
=== === === === === === === === === === === === ===\n
\f
a) Get the dataframe from remote
b) Check context for dataframe if is/is not present
c) Display dataframe accoridngly
:param ctx: click.Context
:return: None: Produces stdout --help text
"""
click.secho(
message="====================LOADING MODE=======================\n",
fg='magenta', bg='white', bold=True)
click.secho(
message="========Load & Show All/Bulk Records (Table)===========\n",
fg='magenta', bold=True)
click.secho(
message="==========Select Views: Show Selected Tasks============\n",
fg='magenta', bold=True)
click.secho(
message="Entering loading & reading mode for all records.",
fg='magenta', bg='white', bold=True)
click.secho(
message="Steps: \n"
" 1. Enter an load mode: \n"
" 2. Select Todo or Views task/action: \n"
" 3. For Todo: -= Tasks Zone for the Project \n"
" 3.1 Choose All: Complete list an overview. \n"
" 3.2 Choose Simple: A simple list of Todo. \n"
" 3.3 Choose Notes: A list of Notes. \n"
" 3.4 Choose Notes: A Todos that are Done. \n"
" 3.5 Choose Grade: A Todos that are by Grade. \n"
" 3.5 Choose Review........................... \n"
" ............................................ \n"
" 4. For Views: -=Review the Assignement & Criterias=- \n"
" 4.1 Choose Overview: Complete list an overview. \n"
" 4.2 Choose Project: A view of projects. data. \n"
" 4.3 Choose Criteria: A view of criteria. \n"
" 4.4 Choose ToDos: A view of ToDos. \n"
" 4.5 Choose References: An index of references. \n"
" 5. Exits mode automatically. \n",
fg='magenta', bold=styles.infobold, underline=True)
click.secho(
message="Prompts are available for each input. Hit: 'Enter'")
App.update_appdata(context=ctx, dataframe=App.get_data())
click.secho(
message="Working data is now ... rehydrated.",
blink=True)
click.secho(
message=f"You have rows 1 to {App.get_range} to work with",
bold=styles.infobold)
# 2.1 Load Data: ToDo (Sub) Views
# Uses App.values.x.x(.x) String values for configuration.
# noinspection PyUnusedFunction
@load.command(App.values.Todo.cmd,
help=App.values.Todo.help, short_help='Load Mode: Todos Views')
@click.pass_context
@click.option('-selects', 'selects',
type=click.Choice(choices=App.views.Todo,
case_sensitive=App.values.case),
default=App.values.Todo.Selects.default,
show_default=App.values.shown,
prompt=App.values.Todo.Selects.prompt,
help=App.values.Todo.Selects.help)
def todo(ctx, selects: str) -> None:
"""Load todos, and display different filters/views.
\f
:param ctx: click.Context
:param selects: str: Views options to select by choice
:return: None: Produces stdout --help text
"""
# Get Data
dataframe: pd.DataFrame = App.get_data()
# Guard Clause Checks Choice
def checkchoice(choice: str) -> str | None:
"""Guard Clause."""
if choice is not None and isinstance(choice, str):
return choice
else:
click.secho(message="Your selected option is not possible.\n "
"Try the commanď with one of these options: \n"
"Help: --help\n"
"Choices: All, Simple, Done, Grade, Review",
fg=styles.invalidfg,
bold=styles.invalidbold) # noqa
return None
# Display
try:
App.command_todo(dataframe=dataframe,
todoview=checkchoice(choice=selects))
except TypeError:
App.command_todo(dataframe=dataframe)
finally:
App.update_appdata(context=ctx, dataframe=dataframe)
# 2.2 Load Data: Views (Sub) Views - These are assignments levels views
# Uses App.values.x.x(.x) String values for configuration.
# noinspection PyUnusedFunction
@load.command(App.values.Views.cmd,
help=App.values.Views.help,
short_help='Load Mode: Selects views')
@click.option('-selects', 'selects',
type=click.Choice(choices=App.views.Load,
case_sensitive=App.values.case),
default=App.values.Views.Selects.default,
show_default=App.values.shown,
prompt=App.values.Views.Selects.prompt,
help=App.values.Views.Selects.help)
@click.pass_context
def views(ctx, selects) -> None:
"""Load Reference/Index.
\f
:param ctx: click.Context
:param selects: str: Select views options by choice options input
:return: None: Produces stdout --help text
"""
# Get Data
dataframe: pd.DataFrame = App.get_data()
# Guard Clause Checks Choice
def checks(choice: str) -> str | None:
"""Guard Clause for View Choice
:param choice: str: Choice
:return: str: Choice else a styled invalid message
"""
if choice is not None and isinstance(choice, str):
return choice
else:
click.secho(message="Your selected option is not possible.\n "
"Try the commanď with one of these options: \n"
"Help: --help\n"
"Choices: All, Project, Criteria, "
"ToDo, Reference",
fg=styles.invalidfg,
bg=styles.invalidbg) # noqa
return None
# Select the General Views
def chooseviews(data: pd.DataFrame, choice: str) -> None:
"""Select the General Views.
:param data: pd.DataFrame: Dataframe
:param choice: str: Choice
:return: None: Produces stdout
"""
if checks(choice) == App.views.Overviews:
App.command_view(dataframe=data,
viewer=Head.OverviewViews,
label="Overview") # noqa
elif checks(choice) == App.views.Project:
App.command_view(dataframe=data,
viewer=Head.ProjectView,
label="Project")
elif checks(choice) == App.views.Criteria:
App.command_view(dataframe=data,
viewer=Head.CriteriaView,
label="Criteria")
elif checks(choice) == App.views.ToDos:
App.command_view(dataframe=data,
viewer=Head.ToDoAllView,
label="Todos")
elif checks(choice) == App.views.Reference:
App.command_view(dataframe=data,
viewer=Head.ReferenceView,
label="Reference/Index")
else:
click.secho(message="No data viewable "
f"for the chosen option: {selects}",
fg=styles.warnfg,
bold=styles.warnbg)
# Display The View Choice
chooseviews(data=dataframe, choice=selects)
# Update Global Data
App.update_appdata(context=ctx, dataframe=dataframe)
# 3.0 Find: Locate: individual records from the bulk data
# Uses App.values.x.x(.x) String values for configuration.
@run.group(App.values.Find.cmd, short_help='Find Mode: Locate')
@click.pass_context
def find(ctx: click.Context) -> None: # noqa
"""INTENT: Find: => ACTIONS/Commands: locate:
=== === === === === === === === === === === === ===\n
\b
Start Typing:
- Use 'tab' to autocomplete the current menu option.
- Then 'space' to start the sub-menu.
- Then 'tab' or 'enter' complete. \n
___\n
\b
Hit 'enter' to enter the prompt sequence for option.
Can use, e.g., `-o` flag on same line as command.
However, prompt entery is preferred.\n
===\n
\b
ACTIONS/Commands:
- locate
....'-i' index (range: 1 to last) | number only
....'-a' axis (default: index) | choose