Files
qlockify-backend-deployment/apps/workspaces/services/rates.py

106 lines
3.4 KiB
Python

from django.utils import timezone
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"):
currency = currency.upper()
rate = WorkspaceUserRate.objects.filter(
workspace=workspace,
user_id=user_id,
is_deleted=False,
).first()
effective_from = timezone.now()
if rate:
update_fields = []
if rate.hourly_rate != hourly_rate:
rate.hourly_rate = hourly_rate
update_fields.append("hourly_rate")
if rate.currency != currency:
rate.currency = currency
update_fields.append("currency")
if not rate.is_active:
rate.is_active = True
update_fields.append("is_active")
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
rate = WorkspaceUserRate.objects.create(
workspace=workspace,
user_id=user_id,
hourly_rate=hourly_rate,
currency=currency,
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):
if "currency" in kwargs and kwargs["currency"]:
kwargs["currency"] = kwargs["currency"].upper()
update_fields = []
for field, value in kwargs.items():
if hasattr(rate_instance, field) and getattr(rate_instance, field) != value:
setattr(rate_instance, field, value)
update_fields.append(field)
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