feat(rates): record hourly rate history

This commit is contained in:
2026-05-26 12:15:27 +03:30
parent e42e0612aa
commit af9facce7e
4 changed files with 229 additions and 5 deletions

View File

@@ -1,6 +1,34 @@
from django.utils import timezone
from apps.workspaces.models import WorkspaceUserRate
from apps.workspaces.models import HourlyRateHistory, WorkspaceUserRate
def record_workspace_rate_history(*, workspace, user_id, hourly_rate, currency, effective_from=None):
currency = currency.upper()
effective_from = effective_from or timezone.now()
latest = (
HourlyRateHistory.objects.filter(
workspace=workspace,
user_id=user_id,
scope=HourlyRateHistory.Scope.WORKSPACE,
project__isnull=True,
is_deleted=False,
)
.order_by("-effective_from", "-created_at")
.first()
)
if latest and latest.hourly_rate == hourly_rate and latest.currency == currency:
return latest
return HourlyRateHistory.objects.create(
workspace=workspace,
user_id=user_id,
project=None,
scope=HourlyRateHistory.Scope.WORKSPACE,
hourly_rate=hourly_rate,
currency=currency,
effective_from=effective_from,
is_active=True,
)
def upsert_workspace_user_rate(workspace, user_id, hourly_rate, currency="USD"):
@@ -11,6 +39,7 @@ def upsert_workspace_user_rate(workspace, user_id, hourly_rate, currency="USD"):
is_deleted=False,
).first()
effective_from = timezone.now()
if rate:
update_fields = []
if rate.hourly_rate != hourly_rate:
@@ -25,16 +54,31 @@ def upsert_workspace_user_rate(workspace, user_id, hourly_rate, currency="USD"):
if update_fields:
update_fields.append("updated_at")
rate.save(update_fields=update_fields)
record_workspace_rate_history(
workspace=workspace,
user_id=user_id,
hourly_rate=rate.hourly_rate,
currency=rate.currency,
effective_from=effective_from,
)
return rate
return WorkspaceUserRate.objects.create(
rate = WorkspaceUserRate.objects.create(
workspace=workspace,
user_id=user_id,
hourly_rate=hourly_rate,
currency=currency,
effective_from=timezone.now(),
effective_from=effective_from,
is_active=True,
)
record_workspace_rate_history(
workspace=workspace,
user_id=user_id,
hourly_rate=rate.hourly_rate,
currency=rate.currency,
effective_from=rate.effective_from,
)
return rate
def update_workspace_user_rate(rate_instance, **kwargs):
@@ -50,5 +94,12 @@ def update_workspace_user_rate(rate_instance, **kwargs):
if update_fields:
update_fields.append("updated_at")
rate_instance.save(update_fields=update_fields)
if {"hourly_rate", "currency", "is_active"} & set(update_fields):
record_workspace_rate_history(
workspace=rate_instance.workspace,
user_id=rate_instance.user_id,
hourly_rate=rate_instance.hourly_rate,
currency=rate_instance.currency,
)
return rate_instance