Skip to content

models

main.models ¤

Models module for main app.

Classes¤

Allocation ¤

Bases: FullTimeEquivalent

User allocated to a project for a period of time.

AnalysisCode ¤

Bases: Model

Analysis code to use during charging.

Methods:¤
__str__() ¤

String representation of the Analysis Code object.

Source code in main/models.py
96
97
98
def __str__(self) -> str:
    """String representation of the Analysis Code object."""
    return f"{self.code} - {self.description}"

Capacity ¤

Bases: Model

Proportion of working time that team members are able to work on projects.

Classes¤
Meta ¤

Meta class for the model.

Methods:¤
__str__() ¤

String representation of the Capacity object.

Source code in main/models.py
940
941
942
def __str__(self) -> str:
    """String representation of the Capacity object."""
    return f"From {self.start_date}, the capacity of {self.user} is {self.value}."

DailyRate ¤

Bases: Model

Historical record of the standard daily rate used for funding.

Rather than storing a single mutable value, each change to the standard rate is recorded as a new entry, effective from a given date. This keeps an audit trail of how the standard rate has changed over time, and lets a new rate be scheduled ahead of its effective date if needed.

This only supplies the default value proposed when a new Funding record is created (see get_current_daily_rate). Each Funding.daily_rate remains independently editable, so funding sources that use a bespoke rate (different from the standard one at that point in time) can simply have their rate set accordingly, and it won't be affected by later additions here.

Classes¤
Meta ¤

Meta class for the model.

Methods:¤
__str__() ¤

String representation of the DailyRate object.

Source code in main/models.py
632
633
634
def __str__(self) -> str:
    """String representation of the DailyRate object."""
    return f"£{self.rate:.2f} (from {self.effective_date})"

Department ¤

Bases: Model

Model to manage the departments.

You can find the faculties and potential departments in:

https://www.imperial.ac.uk/faculties-and-departments/

Methods:¤
__str__() ¤

String representation of the Department object.

Source code in main/models.py
67
68
69
def __str__(self) -> str:
    """String representation of the Department object."""
    return f"{self.name} - {self.faculty}"

FullTimeEquivalent ¤

Bases: Model

Full-time-equivalent model for user and projects.

Attributes¤
days property ¤

Convert FTE to days using the working days in a year in the settings.

Classes¤
Meta ¤

Model metadata.

Methods:¤
clean() ¤

Ensure start date comes before end date and that value 0 or positive.

Source code in main/models.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
def clean(self) -> None:
    """Ensure start date comes before end date and that value 0 or positive."""
    super().clean()
    if self.end_date <= self.start_date:
        raise ValidationError("The end date must be after the start date.")

    if self.value < 0:
        raise ValidationError(
            "The FTE value must be greater than or equal to zero."
        )
from_days(days, start_date, end_date, **kwargs) classmethod ¤

Creates an FTE object given a number of days time period.

Source code in main/models.py
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
@classmethod
def from_days(  # type: ignore[explicit-any]
    cls,
    days: float,
    start_date: date,
    end_date: date,
    **kwargs: Any,
) -> None:
    """Creates an FTE object given a number of days time period."""
    from .utils import days_to_fte

    # FTE will then be the # of days work / the (weighted) time period in days.
    # `start_date`/`end_date` are an inclusive calendar range (both days count
    # towards the period), hence the `+ timedelta(days=1)`.
    obj = cls(
        value=days_to_fte(start_date, end_date + timedelta(days=1), days),
        start_date=start_date,
        end_date=end_date,
        **kwargs,
    )
    obj.clean()
    obj.save()
trace(timerange=None) ¤

Convert the FTE to a dataframe.

If timerange is provided, those dates are used, otherwise a datetime index is created using the start and end dates of the FTE object.

Source code in main/models.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
def trace(self, timerange: pd.DatetimeIndex | None = None) -> pd.Series[float]:
    """Convert the FTE to a dataframe.

    If timerange is provided, those dates are used, otherwise a datetime index is
    created using the start and end dates of the FTE object.
    """
    if timerange is not None:
        idx = timerange.copy()
        output = pd.Series(0.0, index=idx)
        output.loc[
            pd.Timestamp(self.start_date, tz=UTC) : pd.Timestamp(
                self.end_date, tz=UTC
            )
        ] = self.value
    else:
        idx = pd.date_range(start=self.start_date, end=self.end_date, tz=UTC)
        output = pd.Series(self.value, index=idx)

    return output

Funding ¤

Bases: Model

Funding associated with a project.

Attributes¤
effort property ¤

Provide the effort in days, calculated based on the budget and daily rate.

Returns:

Type Description
float

The total number of days of effort provided by the funding.

effort_left property ¤

Provide the effort left in days.

Returns:

Type Description
float

The number of days worth of effort left.

funding_left property ¤

Provide the funding left in currency.

Funding left is calculated based on 'Confirmed' monthly charges.

Returns:

Type Description
float

The amount of funding left.

project_code property ¤

Provide the project code, containing the cost centre and activity code.

Returns:

Type Description
str

The designated project code.

Classes¤
Meta ¤

Meta class for the model.

Methods:¤
__str__() ¤

String representation of the Funding object.

Source code in main/models.py
750
751
752
def __str__(self) -> str:
    """String representation of the Funding object."""
    return f"{self.project} - £{self.budget:.2f} - {self.project_code}"
clean() ¤

Perform validation of the Funding instance.

Raises:

Type Description
ValidationError

If active, confirmed, or projects in maintenance have incomplete funding sources.

ValidationError

If an internal funding source has the a non-null funding body, cost centre, activity or analysis code.

ValidationError

If the activity code is not of the correct format.

Source code in main/models.py
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
def clean(self) -> None:
    """Perform validation of the Funding instance.

    Raises:
        ValidationError: If active, confirmed, or projects in maintenance have
            incomplete funding sources.
        ValidationError: If an internal funding source has the a non-null funding
            body, cost centre, activity or analysis code.
        ValidationError: If the activity code is not of the correct format.
    """
    try:
        project = self.project
    except ObjectDoesNotExist:
        project = None

    if (
        project
        and project.status in ("Active", "Confirmed", "Maintenance")
        and not self.is_complete()
    ):
        raise ValidationError(
            "Funding of Active, Confirmed, and Maintenance projects must "
            "be complete."
        )

    allowed_characters = ["P", "F", "G", "I"]
    if self.activity and (
        len(self.activity) != 6
        or not self.activity.isalnum()
        or self.activity[0] not in allowed_characters
    ):
        raise ValidationError(
            "Activity code must be 6 alphanumeric characters starting with P, F, "
            "G or I."
        )

    if not self.is_valid_internal():
        raise ValidationError(
            "Internally funded projects cannot have a funding body, cost centre,"
            " activity or analysis code."
        )
is_complete() ¤

Checks if funding record is complete.

This is only relevant to funding where source is external.

Source code in main/models.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def is_complete(self) -> bool:
    """Checks if funding record is complete.

    This is only relevant to funding where source is external.
    """
    if self.source == "Internal":
        return True

    return bool(
        self.funding_body
        and self.cost_centre
        and self.activity
        and self.analysis_code
        and self.expiry_date
    )
is_valid_internal() ¤

Checks an internal funding source has the relevant null fields.

Source code in main/models.py
812
813
814
815
816
817
818
819
def is_valid_internal(self) -> bool:
    """Checks an internal funding source has the relevant null fields."""
    if self.source == "Internal" and (
        self.funding_body or self.cost_centre or self.activity or self.analysis_code
    ):
        return False
    else:
        return True
monthly_pro_rata_charge(date) ¤

Calculate the charge per month if the project has Pro-rata charging.

Calculates the number of months between project start and end date regardless of the day of the month so the monthly charge will be the same regardless of the number of days in the month.

The last month of the project is not charged, so the charge applies from the month of the start date until the month before the end date, to ensure that no charges are made outside of the project period. For example, if a project starts on 15th January and ends on 10th April, the charge will apply for January, February and March, but not April.

Parameters:

Name Type Description Default
date date

The date for which to calculate the monthly charge, used to check if the project has started and hasn't ended yet.

required

Returns:

Type Description
float | None

The monthly charge amount, or None if the project doesn't have Pro-rata

float | None

charging or the date is outside the project period.

Source code in main/models.py
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
def monthly_pro_rata_charge(self, date: date) -> float | None:
    """Calculate the charge per month if the project has Pro-rata charging.

    Calculates the number of months between project start and end date regardless
    of the day of the month so the monthly charge will be the same regardless
    of the number of days in the month.

    The last month of the project is not charged, so the charge applies from the
    month of the start date until the month before the end date, to ensure that no
    charges are made outside of the project period. For example, if a project
    starts on 15th January and ends on 10th April, the charge will apply for
    January, February and March, but not April.

    Args:
        date: The date for which to calculate the monthly charge, used to check if
            the project has started and hasn't ended yet.

    Returns:
        The monthly charge amount, or None if the project doesn't have Pro-rata
        charging or the date is outside the project period.
    """
    if self.project.start_date is None or self.project.end_date is None:
        return None

    pstart = self.project.start_date.replace(day=1)
    pend = self.project.end_date.replace(day=1)
    if (
        self.project.charging == "Pro-rata"
        and self.project.start_date
        and self.project.end_date
        and pstart <= date < pend
    ):
        months = (
            self.project.end_date.year - self.project.start_date.year
        ) * 12 + (self.project.end_date.month - self.project.start_date.month)
        return float(self.budget / months)
    return None

MonthlyCharge ¤

Bases: Model

Monthly charge for a specific project, account and analysis code.

Methods:¤
__str__() ¤

String representation of the MonthlyCharge object.

Source code in main/models.py
1002
1003
1004
def __str__(self) -> str:
    """String representation of the MonthlyCharge object."""
    return self.description
clean() ¤

Ensure the charge has valid funding attached and description if Manual.

Source code in main/models.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def clean(self) -> None:
    """Ensure the charge has valid funding attached and description if Manual."""
    super().clean()
    if not self.funding.expiry_date:
        raise ValidationError("Funding source must have an expiry date.")

    if (
        self.date > self.funding.expiry_date
        or self.funding.funding_left < 0  # After deducting charge amount
    ):
        raise ValidationError(
            "Monthly charge must not exceed the funding date or amount."
        )

    if self.project.charging == "Manual":
        if not self.description:
            raise ValidationError(
                "Line description needed for manual charging method."
            )
    else:
        self.description = (
            f"RSE Project {self.project} ({self.funding.project_code}): "
            f"{self.date.month}/{self.date.year} [rcs-manager@imperial.ac.uk]"
        )

Project ¤

Bases: Warning, Model

Software project details.

Attributes¤
days_left property ¤

Provide the days worth of effort left.

Returns:

Type Description
tuple[float, float] | None

The number of days and percentage worth of effort left, or None if there is

tuple[float, float] | None

no funding information.

percent_effort_left property ¤

Provide the percentage of effort left.

Returns:

Type Description
float | None

The percentage of effort left, or None if there is no funding information.

total_effort property ¤

Provide the total days worth of effort available.

For projects in Maintenance status, the total effort is the one associated to the maintenance phase. For projects in Active status, the total effort is the sum of the days associated to all non-maintenance phases (this deliberately excludes a maintenance phase that may already have been set up in preparation for a future transition to Maintenance status). If an Active project has no phases defined yet, funding is used instead: this preserves the prior behaviour for projects that don't use the phases feature, and avoids a circular dependency when creating the very first phase for a project (since total_effort may be used to seed the initial phase created for a project). For all other statuses, the total effort is derived from the funding sources, as before.

Returns:

Type Description
float | None

The total number of days effort, or None if there is no relevant

float | None

information (funding or phases, depending on status) to derive it from.

total_funding_left property ¤

Provide the total funding left after deducting confirmed charges.

In maintenance mode or if the project is finished, this is not relevant, despite having a funding source. For all other statuses, if there's funding information, it should be calculated out of it.

Returns:

Type Description
float | None

The total monetary amount of funding left, or none if there is no funding

float | None

information.

total_working_days property ¤

Provide the total number of working days given the funding.

Returns:

Type Description
float | None

Number of working days given the funding available.

weeks_to_deadline property ¤

Provide the number of weeks left until project deadline.

Only relevant for projects in Active, Confirmed, and Maintenance statuses.

Returns:

Type Description
tuple[float, float] | None

The number of weeks left or None if the project is Tentative or Not done.

Methods:¤
__str__() ¤

String representation of the Project object.

Source code in main/models.py
209
210
211
def __str__(self) -> str:
    """String representation of the Project object."""
    return self.name
check_and_notify_status() ¤

Check the project status and notify accordingly.

Source code in main/models.py
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
def check_and_notify_status(self) -> None:
    """Check the project status and notify accordingly."""
    from .tasks import notify_left_threshold

    check = False

    assert self.lead and hasattr(self.lead, "email")

    for threshold in sorted(EFFORT_LEFT_THRESHOLD):
        if self.percent_effort_left is None or self.percent_effort_left > threshold:
            continue

        if str(threshold) in self.notifications_effort:
            # Already notified for this threshold in the past
            break

        notify_left_threshold(
            email=self.lead.email,
            lead=self.lead.get_full_name(),
            project_name=self.name,
            threshold_type="effort",
            threshold=threshold,
            value=self.days_left[0] if self.days_left else 0,
        )
        self.notifications_effort[str(threshold)] = (
            timezone.now().date().isoformat()
        )
        check = True
        break

    for threshold in sorted(WEEKS_LEFT_THRESHOLD):
        if self.weeks_to_deadline is None or self.weeks_to_deadline[1] > threshold:
            continue

        if str(threshold) in self.notifications_weeks:
            # Already notified for this threshold in the past
            break

        notify_left_threshold(
            email=self.lead.email,
            lead=self.lead.get_full_name(),
            project_name=self.name,
            threshold_type="weeks",
            threshold=threshold,
            value=self.weeks_to_deadline[0] if self.weeks_to_deadline else 0,
        )
        self.notifications_weeks[str(threshold)] = timezone.now().date().isoformat()
        check = True
        break

    if check:
        self.save(update_fields=["notifications_effort", "notifications_weeks"])
clean() ¤

Ensure all fields have a value unless status is 'Tentative' or 'Not done'.

It also checks that, if present, the end date is after the start date. In addition, a project that was not yet 'Active' or 'Maintenance', but wants to, cannot have warnings; the project must start clean

Source code in main/models.py
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
def clean(self) -> None:
    """Ensure all fields have a value unless status is 'Tentative' or 'Not done'.

    It also checks that, if present, the end date is after the start date.
    In addition, a project that was not yet 'Active' or 'Maintenance', but wants to,
    cannot have warnings; the project must start clean
    """
    if self.status == "Tentative" or self.status == "Not done":
        return super().clean()

    if not self.start_date or not self.end_date or not self.lead:
        raise ValidationError(
            "All fields are mandatory except if Project status is 'Tentative' or "
            "'Not done'."
        )

    if self.end_date <= self.start_date:
        raise ValidationError("The end date must be after the start date.")

    # No more checks if the project status is not set to become
    # 'Active', 'Confirmed', or 'Maintenance'
    if self.status not in ("Active", "Confirmed", "Maintenance"):
        return

    if self.pk is None:
        raise ValidationError(
            "Projects cannot be created directly in Active, Confirmed, or "
            "Maintenance statuses."
        )
    else:
        was_active = Project.objects.filter(
            pk=self.pk, status__in=("Active", "Confirmed", "Maintenance")
        ).exists()
        if not was_active and self.has_warnings:
            message = (
                "A project cannot be made Active, Confirmed, or Maintenance if "
                "there are warnings:"
            )
            raise ValidationError([message, *self.warnings])

    # Check that a project has two phases and one maintenance phase if it is set
    # to Maintenance status.
    if self.status == "Maintenance" and (
        not self.phases.filter(is_maintenance=True).exists()
        or self.phases.count() < 2
    ):
        raise ValidationError(
            "Projects cannot be set to Maintenance status unless there "
            "is exactly one maintenance phase and at least 2 phases."
        )
fte(timerange=None, include_excess=True) ¤

Calculate the FTE trace for the project over a given timerange.

This is calculated by summing the trace of all the phases of the project, which are assumed to be sequential and non-overlapping.

Parameters:

Name Type Description Default
timerange DatetimeIndex | None

The timerange to calculate the FTE trace over.

None
include_excess bool

If result should be corrected for unused FTE. If false, the original, expected fte evolution is returned.

True

Returns:

Type Description
Series

A pandas Series with the FTE trace over the timerange, or a trace of 0 if

Series

there are no phases.

Source code in main/models.py
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
def fte(  # type: ignore[explicit-any]
    self, timerange: pd.DatetimeIndex | None = None, include_excess: bool = True
) -> pd.Series:
    """Calculate the FTE trace for the project over a given timerange.

    This is calculated by summing the trace of all the phases of the project,
    which are assumed to be sequential and non-overlapping.

    Args:
        timerange: The timerange to calculate the FTE trace over.
        include_excess: If result should be corrected for unused FTE. If false, the
            original, expected fte evolution is returned.

    Returns:
        A pandas Series with the FTE trace over the timerange, or a trace of 0 if
        there are no phases.
    """
    assert self.start_date is not None
    assert self.end_date is not None

    timerange = (
        timerange
        if timerange is not None
        else pd.date_range(start=self.start_date, end=self.end_date, tz=UTC)
    )
    if self.phases.exists():
        return cast(  # type: ignore[explicit-any]
            pd.Series, sum(phase.trace(timerange) for phase in self.phases.all())
        ) + (self._excess_fte(timerange) if include_excess else 0)
    return pd.Series(0.0, index=timerange)
maintenance_phase() ¤

Provide the phase flagged as the maintenance phase of the project, if any.

This is not restricted to projects currently in Maintenance status: an Active project may already have a phase flagged in preparation for a future transition to Maintenance.

Returns:

Type Description
ProjectPhase | None

The maintenance phase, or None if there is no maintenance phase.

Source code in main/models.py
451
452
453
454
455
456
457
458
459
460
461
def maintenance_phase(self) -> ProjectPhase | None:
    """Provide the phase flagged as the maintenance phase of the project, if any.

    This is not restricted to projects currently in Maintenance status: an Active
    project may already have a phase flagged in preparation for a future
    transition to Maintenance.

    Returns:
        The maintenance phase, or None if there is no maintenance phase.
    """
    return self.phases.filter(is_maintenance=True).first()

ProjectPhase ¤

Bases: FullTimeEquivalent

Phases associated with a project.

Attributes¤
expected_days_left property ¤

Expected number of days left in the phase.

If the days were to be used homogeneously over the phase length, this function calculates how many days of effort are left from today. In phases that have not started (today < start date), the days left will be the total number of days, and phases that are gone (today > end date) the total number of days will be zero.

Methods:¤
__str__() ¤

String representation of the ProjectPhase object.

Source code in main/models.py
1198
1199
1200
def __str__(self) -> str:
    """String representation of the ProjectPhase object."""
    return f"{self.project.name} - {self.start_date} -> {self.end_date}"
check_only_one_maintenance_phase(siblings=None) ¤

Ensure only one maintenance phase exists for the project.

Parameters:

Name Type Description Default
siblings Iterable[ProjectPhase] | None

See check_overlapping_phases.

None
Source code in main/models.py
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
def check_only_one_maintenance_phase(
    self, siblings: Iterable[ProjectPhase] | None = None
) -> None:
    """Ensure only one maintenance phase exists for the project.

    Args:
        siblings: See `check_overlapping_phases`.
    """
    if not self.is_maintenance:
        return

    if siblings is None:
        existing_maintenance = ProjectPhase.objects.filter(
            project=self.project, is_maintenance=True
        )
        if self.pk:
            existing_maintenance = existing_maintenance.exclude(pk=self.pk)
        has_other_maintenance = existing_maintenance.exists()
    else:
        has_other_maintenance = any(
            sibling.is_maintenance for sibling in siblings if sibling is not self
        )

    if has_other_maintenance:
        raise ValidationError("Only one maintenance phase is allowed per project.")
check_overlapping_phases(siblings=None) ¤

Check the phase doesn't overlap with another phase (by 1 day).

Parameters:

Name Type Description Default
siblings Iterable[ProjectPhase] | None

The other phases of the same project to check against. If not given (the default), the project's other phases are fetched from the database, which is the correct behaviour when validating a single phase on its own (e.g. from the admin, the API, or a direct save()/full_clean() call). An explicit list can be passed instead to validate against phases that have not been persisted yet, e.g. when several phases belonging to the same project are being created or edited together (see ProjectPhaseInlineFormSet, in forms.py).

None
Source code in main/models.py
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
def check_overlapping_phases(
    self, siblings: Iterable[ProjectPhase] | None = None
) -> None:
    """Check the phase doesn't overlap with another phase (by 1 day).

    Args:
        siblings: The other phases of the same project to check against. If
            not given (the default), the project's other phases are fetched
            from the database, which is the correct behaviour when
            validating a single phase on its own (e.g. from the admin, the
            API, or a direct `save()`/`full_clean()` call). An explicit list
            can be passed instead to validate against phases that have not
            been persisted yet, e.g. when several phases belonging to the
            same project are being created or edited together (see
            `ProjectPhaseInlineFormSet`, in `forms.py`).
    """
    if siblings is None:
        siblings = ProjectPhase.objects.filter(project=self.project)
        if self.pk:
            siblings = siblings.exclude(pk=self.pk)

    # check start within Phases_starts ≤ Phase_new_start ≤ Phases_ends, or
    # end within Phases_starts ≤ Phase_new_end ≤ Phases_ends
    conflict = next(
        (
            sibling
            for sibling in siblings
            if sibling is not self
            and (
                sibling.start_date <= self.start_date <= sibling.end_date
                or sibling.start_date <= self.end_date <= sibling.end_date
            )
        ),
        None,
    )

    if conflict is not None:
        raise ValidationError(
            "Phase period must not overlap with other phase periods for the same "
            f"project: {conflict.start_date} -> "
            f"{conflict.end_date} vs. {self.start_date} -> {self.end_date}"
        )
check_phase_alignment(siblings=None) ¤

Ensures phases are aligned but separated by 1 day.

Parameters:

Name Type Description Default
siblings Iterable[ProjectPhase] | None

See check_overlapping_phases.

None
Source code in main/models.py
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
def check_phase_alignment(
    self, siblings: Iterable[ProjectPhase] | None = None
) -> None:
    """Ensures phases are aligned but separated by 1 day.

    Args:
        siblings: See `check_overlapping_phases`.
    """
    if siblings is None:
        siblings = ProjectPhase.objects.filter(project=self.project)

    touching = any(
        sibling.start_date == self.end_date + timedelta(days=1)
        or sibling.end_date == self.start_date - timedelta(days=1)
        for sibling in siblings
    )

    if not (
        touching
        or self.start_date == self.project.start_date
        or self.end_date == self.project.end_date
    ):
        raise ValidationError(
            "Phase period must align with the start or end of a project or phase."
        )
check_phase_in_project() ¤

Ensure the start phase dates are within the project dates.

Source code in main/models.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
def check_phase_in_project(self) -> None:
    """Ensure the start phase dates are within the project dates."""
    if self.project.start_date is None or self.project.end_date is None:
        raise ValidationError(
            "Phases cannot be added until the project has a start and end date."
        )
    if (
        self.project.start_date > self.start_date
        or self.project.end_date < self.end_date
    ):
        raise ValidationError(
            "Phase period must be within the project period: "
            f"{self.project.start_date} -> {self.project.end_date}"
        )
clean() ¤

Ensures that phase dates are sensible.

Ensures start is before the end date (from FTE clean). Ensures phase within project period. Ensures the phase isn't covered by any other phases. Ensures at least phase start or end date aligns with other phases or project dates.

The sibling-dependent checks (overlap, alignment, single maintenance phase) are skipped here if _validated_by_formset has been set on this instance: in that case, ProjectPhaseInlineFormSet.clean() (see forms.py) performs them itself, once, against the complete in-memory set of phases being submitted together, rather than one at a time against the database.

Source code in main/models.py
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
def clean(self) -> None:
    """Ensures that phase dates are sensible.

    Ensures start is before the end date (from FTE clean).
    Ensures phase within project period.
    Ensures the phase isn't covered by any other phases.
    Ensures at least phase start or end date aligns with other phases or project
        dates.

    The sibling-dependent checks (overlap, alignment, single maintenance
    phase) are skipped here if `_validated_by_formset` has been set on this
    instance: in that case, `ProjectPhaseInlineFormSet.clean()` (see
    `forms.py`) performs them itself, once, against the complete in-memory
    set of phases being submitted together, rather than one at a time
    against the database.
    """
    super().clean()

    try:
        self.project
    except ObjectDoesNotExist:
        # Nothing else can be checked without a project to check against.
        # Django's own required-field validation will already flag the
        # missing `project` field separately (e.g. when this is used as a
        # standalone form, or when the inline Project/Phase form
        # redisplays phase rows after the Project itself failed
        # validation, before either has been saved).
        return

    self.check_phase_in_project()

    if getattr(self, "_validated_by_formset", False):
        return

    self.check_overlapping_phases()
    self.check_phase_alignment()
    self.check_only_one_maintenance_phase()
save(**kwargs) ¤

Saves the object to the database.

This overwrites models.Model.save() to keep the days constant if the start or end date changes, modifying the FTE value. Except if value has also changed in the same modification.

Source code in main/models.py
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
def save(self, **kwargs: Any) -> None:  # type: ignore[explicit-any]
    """Saves the object to the database.

    This overwrites models.Model.save() to keep the days constant if the start or
    end date changes, modifying the FTE value. Except if `value` has also changed in
    the same modification.
    """
    from .utils import days_to_fte

    update_fields = kwargs.get("update_fields", {})

    # If value has changed, then we don't do anything extra
    if "value" in update_fields:
        pass

    # If dates change, we update the value so the days remain constant
    elif "start_date" in update_fields or "end_date" in update_fields:
        # get old date (from DB)
        old_days = ProjectPhase.objects.get(pk=self.pk).days
        # update the value keeping the days constant by updating FTE value
        # `end_date` is inclusive, hence the `+ timedelta(days=1)`.
        self.value = days_to_fte(
            self.start_date, self.end_date + timedelta(days=1), old_days
        )
        kwargs["update_fields"] = {"value"}.union(update_fields)

    super().save(**kwargs)

TimeEntry ¤

Bases: Model

Time entry for a user.

Methods:¤
__str__() ¤

String representation of the Time Entry object.

Source code in main/models.py
1083
1084
1085
def __str__(self) -> str:
    """String representation of the Time Entry object."""
    return f"{self.user} - {self.project} - {self.start_time} to {self.end_time}"

User ¤

Bases: AbstractUser

Custom user model.

Methods:¤
__str__() ¤

Full name of the user.

Source code in main/models.py
30
31
32
def __str__(self) -> str:
    """Full name of the user."""
    return f"{self.first_name} {self.last_name}"

Functions:¤

get_current_daily_rate() ¤

Provide the currently applicable standard daily rate.

Used as the default value for new Funding records. Existing records are unaffected by later changes to the standard rate, since daily_rate is stored on each Funding individually rather than looked up live.

Returns:

Type Description
float

The rate of the most recent DailyRate whose effective_date is not

float

in the future, or FALLBACK_DAILY_RATE if none exists yet.

Source code in main/models.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def get_current_daily_rate() -> float:
    """Provide the currently applicable standard daily rate.

    Used as the default value for new `Funding` records. Existing records are
    unaffected by later changes to the standard rate, since `daily_rate` is
    stored on each `Funding` individually rather than looked up live.

    Returns:
        The rate of the most recent `DailyRate` whose `effective_date` is not
        in the future, or `FALLBACK_DAILY_RATE` if none exists yet.
    """
    current = (
        DailyRate.objects.filter(effective_date__lte=timezone.now().date())
        .order_by("-effective_date", "-pk")
        .first()
    )
    return float(current.rate) if current is not None else FALLBACK_DAILY_RATE