Skip to content

Views

Manages the views for the DCSP app

This is part of a Django web server app that is used to create a static site in mkdocs.

Functions:

Name Description
index

landing page for DCSP app, redirects logged members.

member_landing_page

landing page for logged in members

start_new_project

start a new project, import from git or from clean slate.

setup_documents

build up the documents for the static site.

project_build_asap

build the static site ad hoc

project_documents

main page for document editing.

view_docs

provides static site via NGINX X-Accel-Redirect

document_new

create a new document.

document_update

edit of main documents.

entry_update

create a new entry or update a preexisting one.

entry_select

select an entry file to edit.

upload_to_external_repository

git commit and push project to external repository.

std_context

provides a standard collection of values for views.

user_accessible_projects

provides a list of projects a user has access to.

placeholders

gets placeholders (used in document_update to convert placeholders to their values).

build_documents

builds the static webpages via mkdocs.

custom_400

custom 400 (bad request) page.

custom_403

custom 403 (forbidden) page.

custom_404

custom 404 (not found) page.

custom_500

custom 500 (internal server error) page.

custom_400(request, exception=None)

Custom 400 - bad request page

Custom 400 page for bad request.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def custom_400(
    request: HttpRequest, exception: Optional[Exception] = None
) -> HttpResponse:
    """Custom 400 - bad request page

    Custom 400 page for bad request.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """

    context: dict[str, Any] = {"page_title": "400 - Bad request"}

    return render(
        request, "error_handler.html", context | std_context(), status=400
    )

custom_403(request, exception=None)

Custom 403 - access forbidden page

Custom 403 page for access forbidden

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def custom_403(
    request: HttpRequest, exception: Optional[Exception] = None
) -> HttpResponse:
    """Custom 403 - access forbidden page

    Custom 403 page for access forbidden

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """

    context: dict[str, Any] = {"page_title": "403 - Forbidden access"}

    return render(
        request, "error_handler.html", context | std_context(), status=403
    )

custom_403_csrf(request, reason=None)

Custom 403 - CSRF page

Custom 403 access forbidden when CRSF triggered.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
def custom_403_csrf(request: HttpRequest, reason: Any = None) -> HttpResponse:
    """Custom 403 - CSRF page

    Custom 403 access forbidden when CRSF triggered.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    return custom_403(request)

custom_404(request, exception=None)

Custom 404 page - page not found

Custom page not found.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
def custom_404(
    request: HttpRequest, exception: Optional[Exception] = None
) -> HttpResponse:
    """Custom 404 page - page not found

    Custom page not found.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {"page_title": "404 - Page not found"}

    return render(
        request, "error_handler.html", context | std_context(), status=404
    )

custom_405(request, exception=None)

Custom 405 page - method not allowed

Custom page method not allowed

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
def custom_405(
    request: HttpRequest, exception: Optional[Exception] = None
) -> HttpResponse:
    """Custom 405 page - method not allowed

    Custom page method not allowed

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {"page_title": "405 - method not allowed"}

    return render(
        request, "error_handler.html", context | std_context(), status=405
    )

custom_500(request, exception=None)

Custom 500 page - internal server error

Description

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
def custom_500(
    request: HttpRequest, exception: Optional[Exception] = None
) -> HttpResponse:
    """Custom 500 page - internal server error

    Description

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {"page_title": "500 - Internal Server Error"}

    return render(
        request,
        "error_handler.html",
        context | std_context(),
        status=500,
    )

document_new(request, project_id, setup_step)

To create a new safety document

This will allow the user to create a new safety document, which are stored as markdown files. A new directory will be created if it does not already exist.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id int

primary key of project

required
setup_step int

the step in the setup process

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@project_access
def document_new(  # type: ignore[return]
    request: HttpRequest,
    project_id: int,
    setup_step: int,
) -> HttpResponse:
    """To create a new safety document

    This will allow the user to create a new safety document, which are stored as
    markdown files. A new directory will be created if it does not already exist.

    Args:
        request (HttpRequest): request from user
        project_id (int): primary key of project
        setup_step (int): the step in the setup process

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {}
    form: Optional[DocumentNewForm] = None
    project: Optional[ProjectBuilder] = None
    document_name_new: str = ""

    if setup_step < 2:
        return redirect(f"/setup_documents/{ project_id }")

    if request.method == "GET":
        context = {
            "page_title": "Create a new safety document",
            "project_name": Project.objects.get(id=project_id).name,
            "form": DocumentNewForm(project_id),
            "project_id": project_id,
        }
        return render(
            request,
            "document_new.html",
            context | std_context(project_id),
        )

    elif request.method == "POST":
        form = DocumentNewForm(project_id, request.POST)
        if form.is_valid():
            document_name_new = form.cleaned_data["document_name"]

            project = ProjectBuilder(project_id)

            project.document_create(document_name_new)

            messages.success(
                request,
                f"Document '{ document_name_new }' has been created",
            )

            context = {
                "page_title": "New document created",
                "project_name": Project.objects.get(id=project_id).name,
                "submitted": True,
                "project_id": project_id,
                "document_name_new": document_name_new,
            }

            return render(
                request, "document_new.html", context | std_context(project_id)
            )

        else:
            context = {
                "page_title": "Create a new safety document",
                "project_name": Project.objects.get(id=project_id).name,
                "form": form,
                "project_id": project_id,
            }

            return render(
                request,
                "document_new.html",
                context | std_context(project_id),
                status=400,
            )

document_update(request, project_id, setup_step)

Save the safety document

If no issues are found after running the markdown file through a linter the file is saved.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id int

primary key of project

required
setup_step int

the step in the setup process

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@project_access
def document_update(  # type: ignore[return]
    request: HttpRequest, project_id: int, setup_step: int
) -> HttpResponse:
    """Save the safety document

    If no issues are found after running the markdown file through a linter
    the file is saved.

    Args:
        request (HttpRequest): request from user
        project_id (int): primary key of project
        setup_step (int): the step in the setup process

    Returns:
        HttpResponse: for loading the correct webpage
    """
    form: Optional[DocumentUpdateForm] = None
    document_name_initial: str = ""
    document_name: str = ""
    document_markdown_initial: str = ""
    document_markdown: str = ""
    document_markdown_file_read: str = ""
    form_data: dict[str, str] = {}
    docs_dir: str = f"{ c.PROJECTS_FOLDER }project_{ project_id }/{ c.CLINICAL_SAFETY_FOLDER }docs/"
    file: TextIO
    context: dict[str, Any] = {}

    if setup_step < 2:
        return redirect(f"/setup_documents/{ project_id }")

    if request.method == "GET":
        form = DocumentUpdateForm(project_id)

        context = {
            "page_title_left": "Edit safety document",
            "form": form,
            "project_id": project_id,
            "placeholders": placeholders(project_id),
            "nav_top": "True",
        }

        return render(
            request,
            "document_update.html",
            context | std_context(project_id),
        )

    elif request.method == "POST":
        form = DocumentUpdateForm(project_id, data=request.POST)

        if form.is_valid():
            document_name_initial = form.cleaned_data["document_name_initial"]
            document_name = form.cleaned_data["document_name"]
            document_markdown_initial = form.cleaned_data[
                "document_markdown_initial"
            ]
            document_markdown = form.cleaned_data["document_markdown"]

            if document_name_initial != document_name:
                with open(Path(docs_dir) / document_name, "r") as file:
                    document_markdown_file_read = file.read()
                    document_markdown_file_read = (
                        document_markdown_file_read.replace("\n", "\r\n")
                    )

                form_data = {
                    "document_name": document_name,
                    "document_markdown": document_markdown_file_read,
                }

                context = {
                    "page_title_left": "Edit safety document",
                    "form": DocumentUpdateForm(
                        project_id,
                        initial=form_data,
                    ),
                    "project_id": project_id,
                    "placeholders": placeholders(project_id),
                    "nav_top": "True",
                }

                return render(
                    request,
                    "document_update.html",
                    context | std_context(project_id),
                )

            elif document_markdown_initial != document_markdown:
                with open(Path(docs_dir) / document_name, "w") as file:
                    file.write(document_markdown)

                project_timestamp(project_id)

                form_data = {
                    "document_name": document_name,
                    "document_markdown": document_markdown,
                }

                messages.success(
                    request,
                    f"Mark down file '{ document_name }' has been successfully saved",
                )

                context = {
                    "page_title_left": "Edit safety document",
                    "form": DocumentUpdateForm(
                        project_id,
                        initial=form_data,
                    ),
                    "project_id": project_id,
                    "placeholders": placeholders(project_id),
                    "nav_top": "True",
                }
                return render(
                    request,
                    "document_update.html",
                    context | std_context(project_id),
                )
            else:
                messages.success(
                    request,
                    "As no changes have been made, no save has been made",
                )
                context = {
                    "page_title_left": "Edit safety document",
                    "form": form,
                    "project_id": project_id,
                    "placeholders": placeholders(project_id),
                    "nav_top": "True",
                }
                return render(
                    request,
                    "document_update.html",
                    context | std_context(project_id),
                )

        else:
            context = {
                "page_title_left": "Edit safety document",
                "form": form,
                "project_id": project_id,
                "placeholders": placeholders(project_id),
                "nav_top": "True",
            }
            return render(
                request,
                "document_update.html",
                context | std_context(project_id),
                status=400,
            )

document_update_named(request, project_id, setup_step, document_name)

Select a specific document to edit

Uses the url to select a specific document to edit.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id int

primary key of project

required
setup_step int

the step in the setup process

required
document_name str

name of the document to edit

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@project_access
def document_update_named(  # type: ignore[return]
    request: HttpRequest, project_id: int, setup_step: int, document_name: str
) -> HttpResponse:
    """Select a specific document to edit

    Uses the url to select a specific document to edit.

    Args:
        request (HttpRequest): request from user
        project_id (int): primary key of project
        setup_step (int): the step in the setup process
        document_name (str): name of the document to edit

    Returns:
        HttpResponse: for loading the correct webpage
    """
    form: Optional[DocumentUpdateForm] = None
    context: dict[str, Any] = {}

    if not request.method == "GET":
        return custom_405(request)

    if setup_step < 2:
        return redirect(f"/setup_documents/{ project_id }")

    if request.method == "GET":
        try:
            form = DocumentUpdateForm(project_id, document_name)
        except FileNotFoundError:
            return custom_404(request)

        context = {
            "page_title_left": "Edit safety document",
            "form": form,
            "project_id": project_id,
            "placeholders": placeholders(project_id),
            "nav_top": "True",
        }

        return render(
            request,
            "document_update.html",
            context | std_context(project_id),
        )

entry_select(request, project_id, setup_step, entry_type)

Displays entries that can be edited

For the given entry type, displays the entries that can be edited.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id int

primary key of the project

required
setup_step int

the step in the setup process

required
entry_type str

type of entry (eg hazard, incident)

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
@project_access
def entry_select(
    request: HttpRequest,
    project_id: int,
    setup_step: int,
    entry_type: str,
) -> HttpResponse:
    """Displays entries that can be edited

    For the given entry type, displays the entries that can be edited.

    Args:
        request (HttpRequest): request from user
        project_id (int): primary key of the project
        setup_step (int): the step in the setup process
        entry_type (str): type of entry (eg hazard, incident)

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {}
    project: ProjectBuilder = ProjectBuilder(int(project_id))
    entries: list[str] = []

    if setup_step < 2:
        return redirect(f"/setup_documents/{ project_id }")

    if request.method != "GET":
        return custom_405(request)

    if not project.entry_type_exists(entry_type):
        return custom_404(request)

    entries = project.entries_all_get(entry_type)

    context = {
        "page_title": f"Select { kebab_to_sentense(entry_type) } to edit",
        "project_name": Project.objects.get(id=project_id).name,
        "project_id": project_id,
        "entries": entries,
        "entry_type": entry_type,
        "project_side_bars": True,
    }
    return render(
        request, "entry_select.html", context | std_context(project_id)
    )

entry_update(request, project_id, setup_step, entry_type, id_new)

Create or update an entry

Creates a new entry (for example a hazard or incident) or updates a pre- existing one.

Parameters:

Name Type Description Default
request HttpRequest

request user.

required
project_id int

the primary key of the project.

required
setup_step int

the step in the setup process.

required
entry_type str

type of entry (eg hazard, incident).

required
id_new str

an entry file number or "new" to create a new entry.

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the webpage.

Source code in app/dcsp/app/views.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
@project_access
def entry_update(  # type: ignore[return]
    request: HttpRequest,
    project_id: int,
    setup_step: int,
    entry_type: str,
    id_new: str,
) -> HttpResponse:
    """Create or update an entry

    Creates a new entry (for example a hazard or incident) or updates a pre-
    existing one.

    Args:
        request (HttpRequest): request user.
        project_id (int): the primary key of the project.
        setup_step (int): the step in the setup process.
        entry_type (str): type of entry (eg hazard, incident).
        id_new (str): an entry file number or "new" to create a new entry.

    Returns:
        HttpResponse: for loading the webpage.
    """
    project: ProjectBuilder = ProjectBuilder(project_id)
    context: dict[str, Any] = {"project_id": project_id}
    form_initial: dict[str, str] = {}
    form: EntryUpdateForm
    entry_update_outcome: bool = False
    page_title: str = ""

    if setup_step < 2:
        return redirect(f"/setup_documents/{ project_id }")

    if id_new != "new":
        if not id_new.isdigit() or not project.entry_exists(
            entry_type, int(id_new)
        ):
            return custom_404(request)

    if not project.entry_type_exists(entry_type):
        return custom_404(request)

    if request.method == "GET":
        if id_new == "new":
            context = {
                "page_title": f"Create new { kebab_to_sentense(entry_type) }",
                "project_name": Project.objects.get(id=project_id).name,
                "project_id": project_id,
                "form": EntryUpdateForm(project_id, entry_type),
                "entry_type": entry_type,
                "id_new": id_new,
                "project_side_bars": True,
            }
            return render(
                request,
                "entry_update.html",
                context | std_context(project_id),
            )

        else:
            form_initial = project.form_initial(entry_type, int(id_new))
            context = {
                "page_title": f"Update { kebab_to_sentense(entry_type) }",
                "project_name": Project.objects.get(id=project_id).name,
                "project_id": project_id,
                "form": EntryUpdateForm(
                    project_id,
                    entry_type,
                    initial=form_initial,
                ),
                "entry_type": entry_type,
                "id_new": id_new,
                "project_side_bars": True,
            }
            return render(
                request,
                "entry_update.html",
                context | std_context(project_id),
            )

    elif request.method == "POST":
        form = EntryUpdateForm(project_id, entry_type, request.POST)
        if form.is_valid():
            project_timestamp(project_id)

            entry_update_outcome = project.entry_update(
                form.cleaned_data,
                entry_type,
                id_new,
            )

            context = {
                "page_title": f"{ kebab_to_sentense(entry_type) } saved",
                "project_name": Project.objects.get(id=project_id).name,
                "project_id": project_id,
                "entry_update_outcome": entry_update_outcome,
                "entry_type": entry_type,
                "id_new": id_new,
                "project_side_bars": True,
            }
            return render(
                request,
                "entry_saved.html",
                context | std_context(project_id),
            )

        else:
            if id_new == "new":
                page_title = f"Create new { kebab_to_sentense(entry_type) }"
            else:
                page_title = f"Update { kebab_to_sentense(entry_type) }"

            context = {
                "page_title": page_title,
                "project_name": Project.objects.get(id=project_id).name,
                "form": form,
                "project_id": project_id,
                "entry_type": entry_type,
                "id_new": id_new,
                "project_side_bars": True,
            }
            return render(
                request,
                "entry_update.html",
                context | std_context(project_id),
            )

index(request)

Landing page for DCSP app

Landing page for DCSP app

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def index(request: HttpRequest) -> HttpResponse:
    """Landing page for DCSP app

    Landing page for DCSP app

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {
        "page_title": "Welcome to the Digital Clinical Safety Platform",
        "NON_EXISTENT_VARIABLE": "NON_EXISTENT_VARIABLE",
    }

    if request.method != "GET":
        return custom_405(request)

    if request.user.is_authenticated:
        return redirect("/member")

    return render(request, "index.html", context | std_context())

member_landing_page(request)

Landing page for members

If no documents related to user, will help user set this up. If user has access to documents, these will be displayed here.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@login_required
def member_landing_page(request: HttpRequest) -> HttpResponse:
    """Landing page for members

    If no documents related to user, will help user set this up. If user has
    access to documents, these will be displayed here.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    projects: list[dict[str, Any]] = []
    viewed_documents: bool = False
    context: dict[str, Any] = {}

    if request.method != "GET":
        return custom_405(request)

    projects = user_accessible_projects(request)

    viewed_documents = any(
        record.get("doc_last_accessed") is not None for record in projects
    )

    context = {
        "page_title": "Safety documents",
        "available_projects": projects,
        "viewed_documents": viewed_documents,
    }

    return render(request, "member_landing_page.html", context | std_context())

placeholders(project_id)

Provides placeholders in serialised form

This is used in the documents edit page, where markdown is converted to html and placeholders are converted into their corresponding values.

Parameters:

Name Type Description Default
project_id str

placeholders in a serialised form.

required

Returns:

Name Type Description
str str

placeholders in serialised form, with empty values replaced with "[key undefined]"

Source code in app/dcsp/app/views.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
def placeholders(project_id: int) -> str:
    """Provides placeholders in serialised form

    This is used in the documents edit page, where markdown is converted to
    html and placeholders are converted into their corresponding values.

    Args:
        project_id (str): placeholders in a serialised form.

    Returns:
        str: placeholders in serialised form, with empty values replaced with
             "[key undefined]"
    """
    project_builder: Optional[ProjectBuilder] = None
    placeholders: dict[str, str] = {}
    key: str = ""
    value: str = ""

    if not isinstance(project_id, int):
        return ""

    if not Project.objects.filter(id=project_id).exists():
        return ""

    project_builder = ProjectBuilder(int(project_id))
    placeholders = project_builder.get_placeholders()
    for key, value in placeholders.items():
        if value == "":
            placeholders[key] = f"[{ key } undefined]"

    return json.dumps(placeholders)

project_build_asap(request, project_id, _)

Ad hoc build of the static site

This function allows the user to build the static site ad hoc. This is useful if the user has made changes to the documents and wants to see the changes immediately.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id int

primary key of project

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the webpage

Source code in app/dcsp/app/views.py
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
@project_access
def project_build_asap(  # type: ignore[return]
    request: HttpRequest,
    project_id: int,
    _: int,
) -> HttpResponse:
    """Ad hoc build of the static site

    This function allows the user to build the static site ad hoc. This is
    useful if the user has made changes to the documents and wants to see the
    changes immediately.

    Args:
        request (HttpRequest): request from user
        project_id (int): primary key of project

    Returns:
        HttpResponse: for loading the webpage
    """
    context: dict[str, Any] = {}
    build_output: str = ""
    mkdocs_control: MkdocsControl = MkdocsControl(project_id)

    if request.method == "GET":
        context = {
            "page_title": "Build documents",
            "project_id": project_id,
            "project_name": Project.objects.get(id=project_id).name,
            "project_side_bars": True,
        }

        return render(
            request,
            "project_build_asap.html",
            context | std_context(project_id),
        )
    elif request.method == "POST":
        build_output = mkdocs_control.build_documents(force=True)

        context = {
            "page_title": "Build documents",
            "project_id": project_id,
            "build_output": build_output,
            "project_name": Project.objects.get(id=project_id).name,
            "project_side_bars": True,
        }

        return render(
            request,
            "project_build_asap.html",
            context | std_context(project_id),
        )

project_documents(request, project_id, _)

Shows the project main page

This provides an overview of the project and the documents that are part of it.

Parameters:

Name Type Description Default
request HttpRequest

request from user.

required
project_id int

primary key of project.

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage.

Source code in app/dcsp/app/views.py
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
@project_access
def project_documents(
    request: HttpRequest,
    project_id: int,
    _: int,
) -> HttpResponse:
    """Shows the project main page

    This provides an overview of the project and the documents that are part of
    it.

    Args:
        request (HttpRequest): request from user.
        project_id (int): primary key of project.

    Returns:
        HttpResponse: for loading the correct webpage.
    """
    project: Optional[Project] = None
    members: QuerySet[User] = User.objects.none()
    groups: QuerySet[ProjectGroup] = ProjectGroup.objects.none()
    context: dict[str, Any] = {}

    if request.method != "GET":
        return custom_405(request)

    project = Project.objects.get(id=project_id)
    members = project.member.all()
    groups = ProjectGroup.objects.filter(project_access=project)

    context = {
        "page_title": "--- Placeholder ---",
        "page_title": project.name,
        "project": project,
        "members": members,
        "groups": groups,
        "project_id": project_id,
        "project_name": project.name,
        "project_side_bars": True,
    }
    return render(
        request,
        "project_documents.html",
        context | std_context(project_id),
    )

setup_documents(request, project_id, setup_step)

Setup the safety documents prior to building them

After the project has been initialised via 'start_new_project' above, this method setups the safety documents, enabling safety documents to then be built. The state of the installation is stored in an setup.ini file as 'setup_step'.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@project_access
def setup_documents(  # type: ignore[return]
    request: HttpRequest,
    project_id: int,
    setup_step: int,
) -> HttpResponse:
    """Setup the safety documents prior to building them

    After the project has been initialised via 'start_new_project' above, this
    method setups the safety documents, enabling safety documents to then be
    built. The state of the installation is stored in an setup.ini file as
    'setup_step'.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    project_builder: ProjectBuilder = ProjectBuilder(project_id)
    context: dict[str, Any] = {}
    template_choice: str = ""
    form: TemplateSelectForm | PlaceholdersForm

    if setup_step == 1:
        if request.method == "GET":
            context = {
                "page_title": "Select Template",
                "form": TemplateSelectForm(project_id),
                "project_id": project_id,
            }

            return render(
                request,
                "setup_documents_template_select.html",
                context | std_context(project_id),
            )

        elif request.method == "POST":
            form = TemplateSelectForm(project_id, request.POST)
            if form.is_valid():
                project_builder.configuration_set("setup_step", 2)
                template_choice = form.cleaned_data["template_choice"]
                project_builder.copy_master_template(template_choice)

                messages.success(
                    request,
                    f"{ template_choice } template initiated",
                )

                context = {
                    "page_title": "Edit placeholders",
                    "form": PlaceholdersForm(project_id),
                    "project_id": project_id,
                    "project_side_bars": True,
                }

                return render(
                    request,
                    "setup_documents_placeholders_show.html",
                    context | std_context(project_id),
                )
            else:
                context = {
                    "page_title": "Select Template",
                    "form": form,
                    "project_id": project_id,
                }

                return render(
                    request,
                    "setup_documents_template_select.html",
                    context | std_context(project_id),
                    status=400,
                )

    elif setup_step >= 2:
        if request.method == "GET":
            context = {
                "page_title": "Edit placeholders",
                "form": PlaceholdersForm(project_id),
                "project_id": project_id,
                "project_name": Project.objects.get(id=project_id).name,
                "project_side_bars": True,
            }

            return render(
                request,
                "setup_documents_placeholders_show.html",
                context | std_context(project_id),
            )

        elif request.method == "POST":
            form = PlaceholdersForm(project_id, request.POST)
            if form.is_valid():
                project_builder.configuration_set("setup_step", 3)

                project_builder.save_placeholders_from_form(form)

                project_timestamp(project_id)

                context = {
                    "page_title": "Documents published",
                    "project_id": project_id,
                    "project_name": Project.objects.get(id=project_id).name,
                    "project_side_bars": True,
                }

                return render(
                    request,
                    "setup_documents_placeholders_saved.html",
                    context | std_context(project_id),
                )
            else:
                context = {
                    "page_title": "Edit placeholders",
                    "form": form,
                    "project_id": project_id,
                    "project_name": Project.objects.get(id=project_id).name,
                    "project_side_bars": True,
                }

                return render(
                    request,
                    "setup_documents_placeholders_show.html",
                    context | std_context(project_id),
                    status=400,
                )

start_new_project(request)

Setup a new project

Create a project by importing an external git repository or starting from a blank slate. A clinical safety document folder will be added if not already present.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
@login_required
def start_new_project(  # type: ignore[return]
    request: HttpRequest,
) -> HttpResponse:
    """Setup a new project

    Create a project by importing an external git repository or starting from a
    blank slate. A clinical safety document folder will be added if not already
    present.

    Args:
        request (HttpRequest): request from user

    Returns:
        HttpResponse: for loading the correct webpage
    """
    context: dict[str, Any] = {}
    form: ProjectSetupInitialForm | ProjectSetupStepTwoForm
    setup_choice: str = ""
    external_repo_url: str = ""
    setup_step: int = 0
    inputs: dict[str, str] = {}
    project_builder: ProjectBuilder
    project_id: str = ""

    if not (request.method == "POST" or request.method == "GET"):
        return custom_405(request)

    if request.method == "GET":
        setup_step = 1
        request.session.pop("repository_type", None)
        request.session["project_setup_step"] = setup_step
        request.session["inputs"] = {}

        context = {
            "page_title": "Setup a new project",
            "setup_step": setup_step,
            "form": ProjectSetupInitialForm(),
        }

        return render(
            request, "start_new_project.html", context | std_context()
        )

    elif request.method == "POST":
        setup_step = request.session.get("project_setup_step", None)
        if setup_step == None:
            return redirect("/start_new_project")
        if setup_step == 1:
            form = ProjectSetupInitialForm(request.POST)
            if form.is_valid():
                setup_step = 2
                request.session["project_setup_step"] = setup_step
                request.session[
                    "project_setup_1_form_data"
                ] = form.cleaned_data
                setup_choice = form.cleaned_data["setup_choice"]

                if setup_choice == "import":
                    external_repo_url = form.cleaned_data[
                        "external_repository_url_import"
                    ]

                    if "github.com/" in external_repo_url:
                        request.session["inputs"]["repository_type"] = "github"
                    elif "gitlab.com/" in external_repo_url:
                        request.session["inputs"]["repository_type"] = "gitlab"
                    elif "gitbucket" in external_repo_url:
                        request.session["inputs"][
                            "repository_type"
                        ] = "gitbucket"
                    else:
                        request.session["inputs"]["repository_type"] = "other"

                # start_anew just jumps straight to the next step
                context = {
                    "page_title": "Setup a new project",
                    "setup_choice": snake_to_sentense(setup_choice),
                    "form": ProjectSetupStepTwoForm(),
                    "setup_step": setup_step,
                }

                return render(
                    request,
                    "start_new_project.html",
                    context | std_context(),
                )

            else:
                context = {
                    "page_title": "Setup a new project",
                    "form": form,
                    "setup_step": setup_step,
                }

                return render(
                    request,
                    "start_new_project.html",
                    context | std_context(),
                    status=400,
                )

        elif setup_step == 2:
            form = ProjectSetupStepTwoForm(request.POST)
            if form.is_valid():
                setup_choice = request.session["project_setup_1_form_data"][
                    "setup_choice"
                ]
                if setup_choice != "start_anew" and setup_choice != "import":
                    return custom_500(request)

                setup_step = 3
                request.session["project_setup_step"] = setup_step
                request.session[
                    "project_setup_2_form_data"
                ] = form.cleaned_data

                inputs = request.session["project_setup_1_form_data"].copy()
                inputs.update(request.session["project_setup_2_form_data"])
                setup_choice = request.session["project_setup_1_form_data"][
                    "setup_choice"
                ]

                request.session["inputs"].update(inputs)

                context = {
                    "page_title": "Setup a new project",
                    "setup_choice": snake_to_sentense(setup_choice),
                    "inputs_GUI": start_new_project_step_2_input_GUI(inputs),
                    "setup_step": setup_step,
                    "CLINICAL_SAFETY_FOLDER": c.CLINICAL_SAFETY_FOLDER,
                }

                return render(
                    request, "start_new_project.html", context | std_context()
                )
            else:
                context = {"form": form, "setup_step": setup_step}

                return render(
                    request,
                    "start_new_project.html",
                    context | std_context(),
                    status=400,
                )

        elif setup_step == 3:
            setup_step = 4
            request.session["project_setup_step"] = setup_step

            project_builder = ProjectBuilder()
            try:
                project_builder.new_build(request)
            except (
                ValueError,
                KeyError,
                RepositoryAccessException,
                NotImplementedError,
                FileExistsError,
            ) as e:
                messages.error(
                    request,
                    f"There was an error with the data you supplied: '{ e }'. Please correct these errors.",
                )

                context = {
                    "page_title": "Error with data supplied",
                    "setup_step": setup_step,
                    "restart_button": "yes",
                }

                return render(
                    request,
                    "start_new_project.html",
                    context | std_context(),
                    status=400,
                )

            inputs = request.session["inputs"]

            messages.success(
                request,
                f"You have successfully created the project titled '{inputs['project_name']}'.",
            )

            project_id = request.session["project_id"]

            request.session.pop("project_id")

            context = {
                "page_title": "Complete",
                "setup_step": setup_step,
                "project_id": project_id,
            }

            return render(
                request, "start_new_project.html", context | std_context()
            )

        elif setup_step == 4:
            return redirect("/start_new_project")

start_new_project_step_2_input_GUI(inputs)

Converts the inputs into a more user friendly format

Takes the user inputs from the previous submissions and prepares them for displaying in the GUI.

Parameters:

Name Type Description Default
inputs dict[str, str]

inputs from the previous submissions.

required

Returns:

Type Description
dict[str, str]

dict[str, str]: inputs in a GUI friendly format.

Source code in app/dcsp/app/views.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
def start_new_project_step_2_input_GUI(
    inputs: dict[str, str]
) -> dict[str, str]:
    """Converts the inputs into a more user friendly format

    Takes the user inputs from the previous submissions and prepares them for
    displaying in the GUI.

    Args:
        inputs (dict[str, str]): inputs from the previous submissions.

    Returns:
        dict[str, str]: inputs in a GUI friendly format.
    """
    key: str = ""
    value: str = ""
    inputs_GUI: dict[str, str] = {}
    groups_list: list[str] = []
    members_list: QuerySet[Any] = User.objects.none()
    members_list_fullnames: list[str] = []

    for key, value in inputs.items():
        key = key.replace("import", "")
        key = key.replace("start_anew", "")
        key = snake_to_sentense(key)

        if key == "Setup choice":
            inputs_GUI[key] = snake_to_sentense(value)

        elif key == "Groups":
            groups_list = [
                name
                for name in ProjectGroup.objects.filter(
                    id__in=value
                ).values_list("name", flat=True)
                if name is not None
            ]
            inputs_GUI[key] = ", ".join(groups_list)
            if inputs_GUI[key] == "":
                inputs_GUI[key] = "<i>none selected</i>"

        elif key == "Members":
            members_list = User.objects.filter(id__in=value).values(
                "id", "first_name", "last_name"
            )
            members_list_fullnames = [
                f"{member['first_name']} {member['last_name']}"
                for member in members_list
            ]
            inputs_GUI[key] = ", ".join(members_list_fullnames)
            if inputs_GUI[key] == "":
                inputs_GUI[key] = "<i>none selected</i>"
        elif key == "Access":
            inputs_GUI[key] = ViewAccess.get_label(value)

        elif any(keyword in key for keyword in ["password", "token"]):
            key = key.replace("password token", "password / token")
            inputs_GUI[key] = "***"

        else:
            inputs_GUI[key] = value

    return inputs_GUI

std_context(project_id=0)

Provides standard context for the rendered view

Provides a standard collection of values that can be used in page renderings.

Parameters:

Name Type Description Default
project_id int

primary key of project.

0

Returns:

Type Description
dict[str, Any]

dict[str,Any]: context that is comment across the different views

Source code in app/dcsp/app/views.py
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
def std_context(project_id: int = 0) -> dict[str, Any]:
    """Provides standard context for the rendered view

    Provides a standard collection of values that can be used in page renderings.

    Args:
        project_id (int): primary key of project.

    Returns:
        dict[str,Any]: context that is comment across the different views
    """
    project: Optional[ProjectBuilder] = None
    entry_templates: list[str] = []
    std_context_dict: dict[str, Any] = {}
    project_setup_step: int = 0

    if not isinstance(project_id, int):
        raise ValueError("project_id must be an integer")

    if project_id > 0:
        project = ProjectBuilder(project_id)
        entry_templates = project.entry_template_names()
        project_setup_step = project.configuration_get()["setup_step"]

    std_context_dict = {
        "entry_templates": entry_templates,
        "project_setup_step": project_setup_step,
    }

    return std_context_dict

under_construction(request, message)

Under construction page

This page is displayed when a page is under construction.

Parameters:

Name Type Description Default
request HttpRequest

request from user.

required
message str

message to display.

required

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage.

Source code in app/dcsp/app/views.py
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
def under_construction(
    request: HttpRequest,
    message: str,
) -> HttpResponse:
    """Under construction page

    This page is displayed when a page is under construction.

    Args:
        request (HttpRequest): request from user.
        message (str): message to display.

    Returns:
        HttpResponse: for loading the correct webpage.
    """
    context: dict[str, Any] = {
        "page_title": " Under contruction",
        "message": message,
    }

    return render(request, "under_construction.html", context | std_context())

user_accessible_projects(request)

Finds all documents that the user has access to

Provides a list of all documents that the user has access to. This includes documents that the user owns, documents that the user is a member of, and documents that the user has access to through a project group.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required

Returns:

Type Description
list[dict[str, Any]]

list[None | dict[str, Any]]: a list of documents

Source code in app/dcsp/app/views.py
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
def user_accessible_projects(
    request: HttpRequest,
) -> list[dict[str, Any]]:
    """Finds all documents that the user has access to

    Provides a list of all documents that the user has access to. This includes
    documents that the user owns, documents that the user is a member of, and
    documents that the user has access to through a project group.

    Args:
        request (HttpRequest): request from user

    Returns:
        list[None | dict[str, Any]]: a list of documents
    """
    user_id: int = (
        int(str(request.user.id)) if request.user.id is not None else 0
    )
    documents_owner: QuerySet[Any] = Project.objects.none()
    documents_member: QuerySet[Any] = Project.objects.none()
    project_group: QuerySet[Any] = ProjectGroup.objects.none()
    record: Any = {}
    documents_combined: list[dict[str, Any]] = []
    documents_sorted: list[dict[str, Any]] = []
    i: int = 0

    documents_owner = Project.objects.values(
        doc_id=F("id"),
        project_name=F("name"),
        doc_last_accessed=F("userprojectattribute__last_accessed"),
    ).filter(owner=user_id)

    documents_member = Project.objects.values(
        doc_id=F("id"),
        project_name=F("name"),
        doc_last_accessed=F("userprojectattribute__last_accessed"),
    ).filter(member=user_id)

    project_group = (
        ProjectGroup.objects.values(
            doc_id=F("project_access__id"),
            project_name=F("project_access__name"),
            doc_last_accessed=F(
                "project_access__userprojectattribute__last_accessed"
            ),
        )
        .filter(member=user_id)
        .order_by(
            "project_access__name",
            "project_access__id",
        )
        .distinct("project_access__name")
    )

    if documents_owner:
        for record in list(documents_owner):
            documents_combined.append(record)

    if documents_member:
        for record in documents_member:
            documents_combined.append(record)

    if project_group:
        for record in project_group:
            documents_combined.append(record)

    documents_combined = list(
        {tuple(sorted(d.items())): d for d in documents_combined}.values()
    )

    for i in range(len(documents_combined)):
        if documents_combined[i]["doc_last_accessed"] != None:
            documents_combined[i]["doc_last_accessed"] = documents_combined[i][
                "doc_last_accessed"
            ].replace(tzinfo=None)

    documents_sorted = sorted(
        documents_combined,
        key=lambda x: (
            x["doc_last_accessed"] or datetime.min,
            x["doc_id"],
        ),
        reverse=True,
    )

    documents_sorted = [
        item
        for item in documents_sorted
        if item
        != {
            "doc_id": None,
            "project_name": None,
            "doc_last_accessed": None,
        }
    ]

    """if documents_sorted == [{}]:
        documents_sorted = []"""

    return documents_sorted

view_docs(request, project_id, doc_path='')

Delivers controlled access to static site material

Delivers controlled access to static site pages. It uses the NGINX X-Accel-Redirect. Depending on if the project's documents have private, member or public access, the user will be able to view the documents. Hence, access to the static pages are also dependent on if the user is authenticated.

Parameters:

Name Type Description Default
request HttpRequest

request from user

required
project_id str

primary key of project

required
doc_path str

path to the document

''

Returns:

Name Type Description
HttpResponse HttpResponse

for loading the correct webpage

Source code in app/dcsp/app/views.py
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
def view_docs(
    request: HttpRequest,
    project_id: str,
    doc_path: str = "",
) -> HttpResponse:
    """Delivers controlled access to static site material

    Delivers controlled access to static site pages. It uses the NGINX
    X-Accel-Redirect. Depending on if the project's documents have private,
    member or public access, the user will be able to view the documents.
    Hence, access to the static pages are also dependent on if the user is
    authenticated.

    Args:
        request (HttpRequest): request from user
        project_id (str): primary key of project
        doc_path (str): path to the document

    Returns:
        HttpResponse: for loading the correct webpage
    """
    project_id_int: int
    accessible_projects: list[dict[str, str]] = []
    internal_path: str = ""
    mkdocs_control: Optional[MkdocsControl] = None
    file: Optional[TextIO] = None
    document_content = ""
    context: dict[str, Any] = {}
    content_type: str = "invalid"
    file_extension: str = ""
    key: str = ""
    value: str = ""
    response: Optional[HttpResponse] = None

    if project_id.isdigit():
        project_id_int = int(project_id)
    else:
        return custom_404(request)

    if not Project.objects.filter(id=project_id_int).exists():
        messages.error(request, f"'Project { project_id }' does not exist")
        return custom_404(request)

    project = Project.objects.get(id=project_id)

    if project.access == ViewAccess.MEMBERS:
        if not request.user.is_authenticated:
            messages.error(
                request,
                f"You do not have access to 'project { project_id }'. "
                "This is a members only project.",
            )
            return custom_403(request)

    elif project.access == ViewAccess.PRIVATE:
        accessible_projects = user_accessible_projects(request)
        if not any(
            doc for doc in accessible_projects if doc["doc_id"] == project_id
        ):
            messages.error(
                request, f"You do not have access to 'project { project_id }'."
            )
            return custom_403(request)

    internal_path = str(
        Path(c.DOCUMENTATION_PAGES) / f"project_{project_id}" / doc_path
    )

    file_extension = Path(internal_path).suffix[1:]

    if file_extension == "html":
        mkdocs_control = MkdocsControl(project_id)
        mkdocs_control.build_documents()

    if not Path(internal_path).is_file():
        messages.error(request, f"File '{ doc_path }' does not exist.")
        return custom_404(request)

    if file_extension == "html":
        file = open(internal_path, "r")
        document_content = file.read()
        context = {
            "document_content": document_content,
            "project_id": project_id,
        }
        return render(
            request,
            "document_serve.html",
            context | std_context(project_id_int),
        )
    else:
        for key, value in c.MIME_TYPES.items():
            if file_extension == key:
                content_type = value
                break

        response = HttpResponse(content_type=content_type)
        response["X-Accel-Redirect"] = internal_path
        return response