90 lines
3.1 KiB
Python
90 lines
3.1 KiB
Python
from apps.product.models import QuotaDistribution, OrganizationQuotaStats
|
|
|
|
|
|
class QuotaStatsService:
|
|
@staticmethod
|
|
def apply_distribution(distribution: QuotaDistribution):
|
|
quota = distribution.quota
|
|
|
|
# origin org
|
|
assigner = distribution.assigner_organization
|
|
# destination org
|
|
assigned = distribution.assigned_organization
|
|
print(assigned)
|
|
# ================ origin ================
|
|
assigner_stat, _ = OrganizationQuotaStats.objects.get_or_create(
|
|
organization=assigner,
|
|
quota=quota,
|
|
stat_type='distribution'
|
|
)
|
|
|
|
assigner_stat.remaining_amount -= distribution.weight
|
|
assigner_stat.total_distributed += distribution.weight
|
|
assigner_stat.save()
|
|
|
|
# ============== destination ================
|
|
assigned_stat, _ = OrganizationQuotaStats.objects.get_or_create(
|
|
organization=assigned,
|
|
quota=quota,
|
|
stat_type='distribution'
|
|
)
|
|
|
|
assigned_stat.total_amount += distribution.weight
|
|
assigned_stat.remaining_amount += distribution.weight
|
|
assigned_stat.distributions.add(distribution)
|
|
assigned_stat.save()
|
|
|
|
@staticmethod
|
|
def update_distribution(distribution: QuotaDistribution, old_weight: int):
|
|
diff = distribution.weight - old_weight
|
|
if diff == 0:
|
|
return
|
|
|
|
quota = distribution.quota
|
|
|
|
assigner = distribution.assigner_organization
|
|
assigned = distribution.assigned_organization
|
|
|
|
assigner_stat = OrganizationQuotaStats.objects.get(
|
|
organization=assigner,
|
|
quota=quota
|
|
)
|
|
assigned_stat = OrganizationQuotaStats.objects.get(
|
|
organization=assigned,
|
|
quota=quota
|
|
)
|
|
if assigner_stat.stat_type == 'distribution':
|
|
# if diff > 0 it is added to destination
|
|
assigner_stat.remaining_amount -= diff
|
|
print("distributed : ", assigner_stat.total_distributed)
|
|
assigner_stat.total_distributed += diff
|
|
print(assigner_stat.total_distributed, diff)
|
|
assigner_stat.save()
|
|
|
|
assigned_stat.total_amount += diff
|
|
assigned_stat.remaining_amount += diff
|
|
assigned_stat.save()
|
|
|
|
@staticmethod
|
|
def delete_distribution(distribution: QuotaDistribution):
|
|
quota = distribution.quota
|
|
|
|
# origin
|
|
assigner_stat = OrganizationQuotaStats.objects.get(
|
|
organization=distribution.assigner_organization,
|
|
quota=quota
|
|
)
|
|
assigner_stat.remaining_amount += distribution.weight
|
|
assigner_stat.total_distributed -= distribution.weight
|
|
assigner_stat.save()
|
|
|
|
# destination
|
|
assigned_stat = OrganizationQuotaStats.objects.get(
|
|
organization=distribution.assigned_organization,
|
|
quota=quota
|
|
)
|
|
assigned_stat.total_amount -= distribution.weight
|
|
assigned_stat.remaining_amount -= distribution.weight
|
|
assigned_stat.distributions.remove(distribution)
|
|
assigned_stat.save()
|