-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontroller.py
2243 lines (1965 loc) · 89.6 KB
/
controller.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: ANN101, I001, ARG002, PLR0913, ANN001, ANN102
"""Module: Controller for the Terminal App.
Usage:
-------------------------
- Controller: Controller for the Terminal App.
- DataController: Data Controller for the Terminal App.
- ColumnSchema: Column Schema DataViews
- Headers: Views by Headers selection: READING, LOADING, VIEWS, DISPLAY
- RICHStyler: Rich.Style Defintions class and methods for the app terminal.
Used on each Record
- Webconsole: Console class and methods for WEB versions of the app.
- Inner: Inner Terminal layouts, arrangement.Deprecate? # noqa
- Record: Record class for displying individual record detials.
- Editor: C(R)UD Operations, and Editor Controller/Model:
Linting:
-------------------------
- pylint: disable=trailing-whitespace
- ruff: noqa:
F841: unused-variable
Local variable {name} is assigned to but never used
ARG002: unused-method-argument
Unused method argument: {name}
ANN101: missing-type-self
Missing type annotation for {name} in method
- 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: dataclasses
3rd Paty Imports
:imports: prompt_toolkit.completion
:depreaction: Possibly deprecated by use of click_repl, due to use
of completion from prompt_toolkit.
: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: connector: connections.GoogleConnector = connections.GoogleConnector()
:var: configuration: settings.Settings = settings.Settings()
:var: console: Console = Console()
:var: stylde: Style = RICHStyleR()
"""
# 0.1 Standard Library Imports
import datetime
import typing
from typing import NoReturn, Literal
#
# 0.2.1 Third Party Modules: Compleete
import click
import gspread # type: ignore
import gspread_dataframe # type: ignore
import pandas as pd # type: ignore
import rich
#
# 0.2.2 Third Party Modules: Individual, Aliases
from gspread_dataframe import (set_with_dataframe as set_remote,
get_as_dataframe as get_gsdf, # type: ignore
)
from rich import print as rprint, box # type: ignore
from rich.console import (Console, ConsoleDimensions,
ConsoleOptions, ) # type: ignore
from rich.layout import Layout # type: ignore
from rich.panel import Panel # type: ignore
from rich.style import Style # type: ignore
from rich.table import Table # type: ignore
#
# 0.3 Local imports
import connections
import settings
from modelview import ColumnSchema, Headers
#
# 1.1: Global/Custom Variables
connector: connections.GoogleConnector = connections.GoogleConnector()
configuration: settings.Settings = settings.Settings()
console: Console = Console()
# 2. Read the data from the sheet by the controller
class Controller:
"""Controller.
Methods:
-------
:method: load_wsheet: Loads the worksheet.
:method: load_data: Loads the worksheet.
"""
@staticmethod
def load_wsheet() -> gspread.Worksheet:
"""Loads a worksheet.
:return: gspread.Worksheet:
The current worksheet to extract the data.
"""
# 1.1: Connect to the sheet
# -> Move to Instance once the data is loaded
# is tested and working on heroku
creds: gspread.Client = \
connector.connect_to_remote(
configuration.CRED_FILE)
# 1.2: Read the data from the sheet
# -> Move to Instance once the data is
# loaded is tested and working on heroku
spread: gspread.Spreadsheet = \
connector.get_source(creds,
configuration.SHEET_NAME)
# 1.3: Return the data from the sheet
# -> Move to Instance once the data is
# loaded is tested and working on
# heroku
return connector.open_sheet(spread, configuration.TAB_NAME)
@staticmethod
def delete(creds: gspread.Client) -> None:
"""Deletes/Close the client.
:param creds: gspread.Client:
:return: None
"""
# https://www.perplexity.ai/search/ac897d0d-bd38-4ebd-9a12-1e90fc172977?s=c
if not isinstance(creds, gspread.Client):
raise ValueError("Invalid: "
"'creds' is not a authorised Client")
if creds.session is not None:
try:
creds.session.close()
except Exception as e:
click.echo(f"Error closing session: {e}", err=True)
finally:
creds.session = None
try:
del creds
except Exception as e:
click.echo(f"Error deleting client: {e}", err=True)
class DataController:
"""DataController."""
# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html
###
dataframe: pd.DataFrame
wsheet: gspread.Worksheet
gsdframe: gspread_dataframe
def __init__(self, wsheet: gspread.Worksheet) -> None:
"""Initialies the DataController."""
# Load the data into a panda dataframe
self.wsheet = wsheet
self.dataframe = pd.DataFrame(wsheet.get_all_records())
self.gsdframe = get_gsdf(self.wsheet,
parse_dates=True, header=1)
# https://www.w3schools.com/python/pandas/pandas_dataframes.asp
# Use gspread_dataframe.set_with_dataframe(worksheet, dataframe,
# row=1, col=1, include_index=False, include_column_header=True,
# resize=False, allow_formulas=True, string_escaping='default')
# Sets the values of a given DataFrame, anchoring its upper-left
# corner at (row, col).
# (Default is row 1, column 1.)
# https://gspread-dataframe.readthedocs.io/en/latest/
@classmethod
def load_dataframe_wsheet(cls, wsheet: gspread.Worksheet) \
-> pd.DataFrame | None: # noqa ANN102
"""Loads the worksheet into a dataframe.
:param wsheet: gspread.Worksheet: The worksheet to load
:return: pd.DataFrame | None: The dataframe or None
"""
if wsheet.get_all_records():
dataframe: pd.DataFrame = \
pd.DataFrame(wsheet.get_all_records())
return dataframe
rprint("No data loaded from Google Sheets.")
return None
@classmethod
def send_dataframe_wsheet(cls, dataframe: pd.DataFrame,
sheet: gspread.Worksheet) -> None: # noqa ANN102
"""Sends the dataframe to the worksheet.
:param dataframe: pd.DataFrame: The dataframe to send
:param sheet: gspread.Worksheet: The worksheet to send to
:return: None
"""
if sheet.get_all_records() and dataframe.empty is False:
set_remote(worksheet=sheet, dataframe=dataframe)
class RICHStyler:
"""Rich Styler for Rich.console Style."""
style = Style()
def __init__(self) -> None:
"""Initialises the TUI Styler."""
self.style = Style()
@staticmethod
def panel(grey: int, tostring: bool = True) -> Style | str:
"""Returns the Style for the property.
:param grey: int: The grey level
https://rich.readthedocs.io/en/stable/appendix/colors.html
:param tostring: bool: Whether to return a string or Style
"""
emp: str = "bold"
co: str = "white"
bg: str = f"grey{grey}"
styled: str = f'{emp} {co} on {bg}'
return styled if tostring else RICHStyler.style.parse(styled)
@staticmethod
def label() -> Style:
"""Style the text.
:return: Style: The style
"""
emp: str = "bold"
co: str = "purple4"
bg: str = "grey93"
styled: str = f'{emp} {co} on {bg}'
return RICHStyler.style.parse(styled)
@staticmethod
def property() -> Style:
"""Returns the Style for the property.
:return: Style: The style
"""
emp: str = "bold"
co: str = "purple4"
bg: str = "grey93"
styled: str = f'{emp} {co} on {bg}'
return RICHStyler.style.parse(styled)
@staticmethod
def value() -> Style:
"""Returns the Style for the property.
:return: Style: The style
"""
emp: str = "italic"
co: str = "dark_turquoise"
bg: str = "black"
styled: str = f'{emp} {co} on {bg}'
return RICHStyler.style.parse(styled)
@staticmethod
def modified() -> Style:
"""Returns the Style for the property.
:return: Style: The style
"""
emp: str = "italic"
co: str = "deep_pink3"
bg: str = "black"
styled: str = f'{emp} {co} on {bg}'
return RICHStyler.style.parse(styled)
@staticmethod
def heading() -> Style:
"""Returns the Style for the property.
:return: Style: The style
"""
emp: str = "bold italic underline2"
co: str = "purple4"
bg: str = "grey93"
styled: str = f'{emp} {co} on {bg}'
return RICHStyler.style.parse(styled)
@staticmethod
def border(stylestr: bool = True) -> Style | str:
"""Returns the Style for the property.
:param stylestr: bool: Whether to return a string or Style
:return: Style | str: The style or style string
"""
emp: str = "bold"
bg: str = "grey93"
styled: str = f'{emp} {bg}'
return styled if stylestr else RICHStyler.style.parse(styled)
styld = RICHStyler
class WebConsole:
"""Web Console."""
console: Console
options: ConsoleOptions
table: Table
terminal: Layout
def __init__(self, width: int, height: int) -> None:
"""Initialises the web console."""
self.console = self.console_configure()
self.options = self.console_options(width, height)
self.table = Table()
self.terminal = Layout()
@staticmethod
def console_options(width: int = configuration.Console.WIDTH,
height: int = configuration.Console.HEIGHT) \
-> ConsoleOptions: # noqa # Pep8 E125
"""Configures the console.
:param width: int: The width of the console
:param height: int: The height of the console
:return: ConsoleOptions
"""
max_width: int = width
max_height: int = height
windowsize: ConsoleDimensions = ConsoleDimensions(
width=max_width, height=max_height)
nolegacy: bool = False
is_terminal: bool = True
encoding: str = configuration.ENCODE
options: ConsoleOptions = ConsoleOptions(
size=windowsize,
legacy_windows=nolegacy,
min_width=max_width,
max_width=max_width,
max_height=max_height,
encoding=encoding,
is_terminal=is_terminal)
return options
@staticmethod
def console_configure() -> Console:
"""Configures the console.
:return: Console
"""
_off: bool = False
_on: bool = True
_style: rich.style.StyleType = ""
_tabs: int = 4
_console: Console = Console(soft_wrap=_on,
style=_style,
tab_size=_tabs,
markup=_on)
return _console
@staticmethod #
def page_data(dataset: list[str]) -> None | NoReturn:
"""Displays the data.
:param dataset: list[str]: The dataset to display.
:return: None | NoReturn:
"""
with console.pager(styles=True):
rprint(dataset)
@staticmethod
def configure_table(headers: typing.Optional[list[str]]) \
-> rich.table.Table: # noqa # Pep8 E125
"""Configures Rich Console table.
:param headers: list[str]: The headers for the table.
:return: rich.table.Table
"""
consoletable: rich.table.Table = Table()
def configure_columns(headings: list[str]) -> None:
"""Configures the headers."""
if isinstance(headings, list):
for header in headings:
# Check if the header is the predefined headers by values
consoletable.add_column(header)
else:
click.echo("No Headers. Text only", err=True)
configure_columns(headings=headers)
return consoletable
class Display:
"""Displays the data."""
# The following is an AI Refactor from orginal authored code
# https://www.perplexity.ai/search/c8250a15-6f8c-4180-b277-349f9ccf83c8?s=c
@staticmethod
def display_subframe(dataframe: pd.DataFrame,
consoleholder: Console | WebConsole,
consoletable: Table,
headerview: Headers | list[str] | str,
viewfilter: Headers.ViewFilter = "Criteria") \
-> None | NoReturn: # noqa # Pep8 E125
"""Displays the data in a table."""
# AI refactor put in place these guard conditions for the headerview
if isinstance(headerview, Headers):
headers: list = getattr(headerview, viewfilter)
elif isinstance(headerview, list):
headers: list = headerview
else:
headers: list = [headerview]
filteredcolumns: pd.DataFrame = \
dataframe.loc[:, dataframe.columns.isin(values=headers)]
# for column in headerview:
for _index, row in filteredcolumns.iterrows():
consoletable.add_row(*[str(row[column])
for column in headers])
consoleholder.print(consoletable)
class Results:
"""Results.
Critical for all index and search results for rows.
:meth: getrowframe: Get a row from a dataframe
by an index or a search term.
"""
def __init__(self):
"""Initialize."""
pass
@staticmethod
def index(frame: pd.DataFrame,
index: int,
zero: bool = True) \
-> pd.DataFrame | pd.Series | None: # noqa # Pep8 E125
"""Get the row from the dataframe by index.
:param frame: pd.DataFrame - Dataframe to search
:param index: int - Index to search
:param zero: bool - Zero based index
:return: pd.DataFrame | pd.Series | None - Expect a result or None
"""
if isinstance(index, int) and index is not None:
return frame.iloc[index] if zero else frame.loc[index - 1]
return None
@staticmethod
def rows(frame: pd.DataFrame,
index: int = None,
zero: bool = True,
squeeze: bool = False) \
-> pd.DataFrame | pd.Series | None: # noqa # Pep8 E125
"""Get the rows from the dataframe.
Parameters
----------
frame: pd.DataFrame: Data to searches by rows
The dataframe to searches.
index: int: optional
The index to searches for, by default None
zero: bool: optional
Whether to searches for a zero indexed dataset, by default True
squeeze: bool: optional
Whether to squeeze the dataframe result into a pd.Series,
By default False
return pd.DataFrame | None: - Expect a result or None
"""
result: pd.DataFrame | pd.Series | None
if index:
result = Results.index(frame=frame, index=index, zero=zero) # noqa
else:
click.echo("Please provide an index "
"identifier for a team")
return None
if squeeze and isinstance(result, pd.DataFrame) and len(result) == 1:
result = result.squeeze()
return result
@staticmethod
def getrowdata(data: pd.DataFrame,
ix: int,
single: bool = False,
debug: bool = False) \
-> pd.Series | pd.DataFrame | None: # noqa # Pep8 E125
"""Get a row from a dataframe by index or searches term.
:param data: pd.DataFrame - Dataframe
:param ix: int - Index
:param single: bool - Single row
:param debug: bool - Debug
:return: pd.Series | pd.DataFrame | None - Row or rows
"""
if ix:
result = Results.rows(frame=data, index=ix,
squeeze=single)
else:
click.echo(f"No Data for row: {ix}")
return None
# To check whether the result is a Series or DataFrame,
# Use the type() function instead of isinstance(),
# which author prefers.
# https://www.perplexity.ai/search/a9842b96-f78d-4a83-a65f-de26448dc2f7?s=c
if type(result) in [pd.Series, pd.DataFrame]:
return result
click.secho("GetRowData(): Found something: undefined")
if debug is True:
rich.inspect(result)
return None
class Record:
"""A Record is a row of data to be displayed in console, by views.
:property: view: The view of the record, default is table.
:property: index: The index of the record, default is 0.
:property: z: The z index of the record, default is 0.
:property: length: The length of the record, default is 1.
:property: headers: The headers of the record, default is None.
:property: values pd.DataFrame:
The values of the record, default is None - Default: []
:property: series: The series of the record, default is None.
:property: sourceframe: The sourceframe of the record, default is None.
:property: size: The size of the record
:property: recordid: The recordid of the record.
:property: positionid: The positionid of the record.
:property: recordid: The recordid of the record.
:property: todo: The todo of the record.
:property: grade: The grade of the record.
:property: status: The status of the record.
:property: topics: The topics of the record.
:property: criteria: The criteria of the record.
:property: type: The type of the record.
:property: prefix: The prefix of the record.
:property: linked: The linked of the record, default is None.
:property: reference: The reference of the record.
:property: group: The group of the record.
:property: notes: The notes of the record, default is None.
"""
view: str = "table"
index: int = 0
z: int = 0
length: int = 1
headers: list[str] | None = []
values: list[str] | None = []
series: pd.Series | None = None
sourceframe: pd.DataFrame | None = None
size: int = 0
recordid = 0
positionid: int = int(recordid) + 1
recordid: str
todo: str
grade: str
status: str
topics: str
criteria: str
type: str
prefix: str
linked: str | None = ''
reference: str
group: str
notes: str | None = ''
lastcommand: str = ''
editedmode: str = ''
lastmodified: str | None = ''
def __init__(self,
labels: list[str] | None = None,
display: str = "table",
series: pd.Series | None = None,
source: pd.DataFrame | None = None) -> None:
"""A Record is a row of data in a table.
Usage:
- A single row of data / record.
Many record instances equals many rows of data, for display only
- For printing individual records to the console, when < 5 per view.
- For greater than 5 records, use a DataFrame and a full table view.
- Display is the view, default is table, else: column, page, panel.
- Labels, for views, as a filtered list of DataFrame's headers.
Parameters:
--------------------
:param labels: list[str]: The row headers, i.e. columns, data.
:param display: str: The view of the record, default is table.
:param series: pd.Series | None: The series of data, if any.
:param source: pd.DataFrame | None: The source of the data, if any.
"""
self.view: str = display
self.values: list[str]
self.index: int
self.length: int
self.headers: list[str] | list[pd.Index] | None = labels
self.series: pd.Series | None = series
self.sourceframe: pd.DataFrame | None = source
# Checks/loads Source, Dataframe, per instance
if isinstance(series, pd.Series):
self.loadsingle(single=series)
self.loadrecord(single=series)
elif isinstance(source, pd.DataFrame):
self.loadsingle(single=source)
@property
def editmode(self) -> str:
"""The editedmode of the record.
:return: str | None: The editedmode of the record.
"""
return self.editedmode
@editmode.setter
def editmode(self, value: str) -> None:
"""The editedmode of the record.
:param value: str: The editedmode of the record.
:return: str | None: The editedmode of the record.
"""
self.editedmode = value
@property
def modified(self) -> str | None:
"""The lastmodified of the record.
:return: str | None: The lastmodified of the record.
"""
return self.lastmodified
@modified.setter
def modified(self, value: str) -> None:
"""The lastmodified of the record.
:param value: str: The lastmodified of the record.
:return: str | None: The lastmodified of the record.
"""
self.lastmodified = value
@property
def command(self) -> str:
"""The lastcommand of the record.
:return: str | None: The lastcommand of the record.
"""
return self.lastcommand
@command.setter
def command(self, value: str) -> None:
"""The lastcommand of the record.
:param value: str: The lastcommand of the record.
:return: str | None: The lastcommand of the record.
"""
self.lastcommand = value
@staticmethod
def cmdnote(value: str) -> str | None:
"""The lastcommand of the record.
:param value: str: The lastcommand of the record.
:return: str | None: The lastcommand of the record.
"""
commands = {
'insert': 'This note is now added',
'append': 'This note is now updated',
'clear': 'This note is now deleted',
'select': 'The progress status is now reported'
}
return commands.get(value, None)
def modedisplay(self) -> str | None:
"""The Displaying Editing Command of the record."""
commands = {
'insert': 'Editing Tasks: Edit > Note: Adding',
'append': 'Editing Tasks: Edit > Note: Updating',
'clear': 'Editing Tasks: Edit > Note: Deleting',
'add': 'Editing Mode: Edit > Note: Adding',
'update': 'Editing Mode: Edit > Note: Updating',
'delete': 'Editing Mode: Edit > Note: Deleting',
'select': 'Editing Mode: Edit > Progress',
'toggle': 'Editing Mode: Edit > Progress',
'locate': 'Finding Mode: Locate > Record'
}
return commands.get(self.editmode, None)
def loadsingle(self, single: pd.DataFrame | pd.Series) -> None:
"""Loads the source of the record, if any."""
if isinstance(single, pd.DataFrame):
if Record.checksingle(single):
self.series = pd.Series(
data=single.values[Record.z],
index=single.columns)
self.values = single.values[Record.z].tolist()
self.headers = single.columns.tolist()
self.sourceframe = single
self.length = len(self.values)
self.index = single.index[Record.z]
elif isinstance(single, pd.Series) and Record.checksingle(single):
self.series: pd.Series = single
self.values = single.tolist()
self.headers: list[pd.Index] = single.axes
self.sourceframe: pd.DataFrame = \
single.to_frame(name=single.name) # noqa
self.length = single.size
self.index = single.index[Record.z]
self.size = single.size
def loadrecord(self, single: pd.Series) -> None:
"""Sets individial record properties."""
if Record.checksingle(single):
self.recordid: int = single.Position
self.type: str = single.Tier
self.prefix: str = single.TierPrefix
self.grade: str = single.Performance
self.status: str = single.DoD
self.todo: str = single.Progress
self.group: str = single.CriteriaGroup
self.topics: str = single.CriteriaTopic
self.reference: str = single.CriteriaRef
self.criteria: str = single.Criteria
self.linked: str = single.LinkedRef
self.notes: str = single.Notes
@staticmethod
def checksingle(single: pd.DataFrame | pd.Series, debug: bool = False) -> bool:
"""Checks the source of the record, if any."""
if isinstance(single, pd.DataFrame):
if single.ndim == Record.length and single.empty is False:
if debug is True:
rich.inspect(single)
return True
click.echo(message="The DataFrame must be a single row.",
err=True)
return False
if isinstance(single, pd.Series) and single.empty is False:
if debug is True:
rich.inspect(single)
return True
click.echo(message="The Series must be a single row.",
err=True)
return False
def card(self,
consolecard: Console,
source: pd.Series | None = None,
sendtoterminal: bool = False) -> Table | None:
"""Either Displays the record as a terminal card, or forwards"""
def config() -> Table:
"""Displays the record as a Inner card.
:return: Table: The record as a card.
"""
g: Table = Table.grid(expand=True)
g.add_column(header="Property",
min_width=15,
ratio=1,
vertical='top') # noqa
g.add_column(header="Value",
min_width=50,
justify="right",
ratio=2,
vertical='top') # noqa
return g
def display(table: Table, data: pd.Series | None = None) \
-> Table | None: # noqa # Pep8 E125
"""Populates the card from instance or a from external source."""
series = data if isinstance(data, pd.Series) \
else self.series
if series is not None:
for label, value in series.items():
table.add_row(str(label), str(value))
return table
return None
card: Table = display(table=config(), data=source)
return Record.switch(card,
printer=consolecard,
switch=sendtoterminal)
@staticmethod
def panel(consolepane: Console,
renderable,
fits: bool = False,
card: tuple[int, int] = (0, 0),
align: typing.Literal["left", "center", "right"] = "left",
outline: rich.box = box.SIMPLE, sendtolayout: bool = False,
debug: bool = False) \
-> Panel | None: # noqa ANN001
"""Frames the renderable as a panel."""
def config(dimensions: tuple[int, int],
styler: str,
safe: bool = False) -> Panel:
"""Frames the renderable as a panel."""
width, height = dimensions
if width == 0 and height == 0:
p: Panel = Panel(renderable=renderable,
expand=fits,
box=outline,
style=styler,
safe_box=safe,
border_style=styld.border(),
title_align=align,
highlight=True)
return p
p: Panel = Panel(renderable=renderable,
expand=fits,
width=width,
height=height,
style=styler,
box=outline,
safe_box=safe,
border_style=styld.border(),
title_align=align,
highlight=True)
return p
panel: Panel = config(dimensions=card,
styler=styld.panel(grey=23),
safe=True)
if debug is True:
rich.inspect(panel)
# Switches the flow: returns | print| to stdout
return Record.switch(panel,
printer=consolepane,
switch=sendtolayout)
def boxed(self, table, style: int = 1) -> Table: # noqa
"""Sets the table box style.
:param table: The table to be boxed.
:param style: The style of the box.
:return: The boxed table.
"""
styles = {
1: box.SIMPLE,
2: box.ROUNDED,
3: box.HEAVY_HEAD,
4: box.SIMPLE_HEAD,
5: box.HORIZONTALS,
6: box.SQUARE
}
table.box = styles.get(style, box.SIMPLE)
return table
def header(self,
consolehead: Console,
sendtolayout: bool = False,
gridfit: bool = False,
valign: str = "top",
debug: bool = False) -> Table | None:
"""Displays the header of the record."""
def config(fit: bool, vertical: str) -> Table:
"""Displays the record as a cardinal."""
g: Table = Table.grid(expand=fit)
g.show_header = True
g.add_column(header="Record",
min_width=35,
ratio=2,
vertical=vertical) # noqa
g.add_column(header="-",
min_width=15,
ratio=1,
vertical=vertical) # noqa
g.add_column(header="Grading",
min_width=35,
ratio=2,
vertical=vertical) # noqa
return g
def head(table: Table) -> Table:
"""Display the subtable for Index/Identifiers."""
h: Table = table
h.title = 'Assignment Details'
rowid: str = 'Record Name: ' + f'{self.series.name}'
grade: str = 'Grade: ' + f'{self.grade}'
position: str = 'Position ID: ' + f'{self.recordid}'
outcome: str = 'Outcome: ' + f'{self.status}: {self.todo}'
h.add_row(rowid, "", grade)
h.add_section()
h.add_row(position, "", outcome)
return h
header: Table = head(table=config(fit=gridfit, vertical=valign))
if debug is True:
rich.inspect(header)
return Record.switch(header,
printer=consolehead,
switch=sendtolayout)
def editable(self,
consoleedit: Console | None = None,
expand: bool = False,
sendtolayout: bool = False,
title: str = 'Current Data',
debug: bool = False) -> Table | None: # noqa
"""Displays the record: Use it for Current | Modified Records."""
def config(fit: bool) -> Table:
"""Displays the record as a cardinal."""
g: Table = Table.grid(expand=fit)
g.pad_edge = True
g.add_column(header="Current",
min_width=50,
ratio=1,
vertical='top') # noqa
return g
def currentdata(table: Table, t: str) -> Table:
"""Display the subtable for Index/Identifiers."""
currenttable: Table = table
if currenttable.title is None and t is not None:
currenttable.title = t
todo_label: str = 'To Do:'
todo_value = f'{self.todo} \n'
criteria_label: str = 'Criteira: ' + f'{self.topics}'
criteria_value = f'{self.criteria} \n\n'
currenttable.add_section()
notes_label: str = 'Notes: '
notes_value = 'Add a note' \
if self.notes is None else f'{self.notes} \n'
# Build rows
currenttable.add_row(todo_label,
style=styld.label())
currenttable.add_row(todo_value,
style=styld.value())
currenttable.add_row(criteria_label,
style=styld.label())
currenttable.add_row(criteria_value,
style=styld.value()) # noqa
currenttable.add_row(notes_label,
style=styld.label())
currenttable.add_row(notes_value,
style=styld.value())
return currenttable
currentdatapane: Table = \
currentdata(table=config(fit=expand), t=title) # noqa
if debug is True:
rich.inspect(currentdatapane)
return Record.switch(currentdatapane,
printer=consoleedit,
switch=sendtolayout)
def footer(self,
consolefoot: Console,
sendtolayout: bool = False,
expand: bool = True,
valign: str = 'top',
debug: bool = False) -> Table | None: