56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
|
from django.db.models import Avg
|
||
|
from django.utils import timezone
|
||
|
|
||
|
from graph.models import Transaction, MonthlyTransaction
|
||
|
from market.models import Product
|
||
|
|
||
|
|
||
|
def create_transaction(post):
|
||
|
transaction = Transaction.objects.create(
|
||
|
product=post.product, price=post.price
|
||
|
)
|
||
|
return transaction
|
||
|
|
||
|
|
||
|
def get_average_price(transactions):
|
||
|
average = transactions.aggregate(Avg("price"))["price__avg"] or 0
|
||
|
return round(average, -2)
|
||
|
|
||
|
|
||
|
def create_monthly_transaction():
|
||
|
year = timezone.now().year
|
||
|
month = timezone.now().month
|
||
|
products = Product.objects.all()
|
||
|
for product in products:
|
||
|
if MonthlyTransaction.objects.filter(
|
||
|
product=product, year=year, month=month
|
||
|
).exists():
|
||
|
continue
|
||
|
transactions = Transaction.objects.filter(product=product)
|
||
|
if transactions:
|
||
|
price = get_average_price(transactions)
|
||
|
MonthlyTransaction.objects.create(
|
||
|
product=product,
|
||
|
year=year,
|
||
|
month=month,
|
||
|
price=price,
|
||
|
)
|
||
|
|
||
|
|
||
|
def create_monthly_transaction_by_product(product):
|
||
|
year = timezone.now().year
|
||
|
month = timezone.now().month
|
||
|
if MonthlyTransaction.objects.filter(
|
||
|
product=product, year=year, month=month
|
||
|
).exists():
|
||
|
return
|
||
|
transactions = Transaction.objects.filter(product=product)
|
||
|
if transactions:
|
||
|
price = get_average_price(transactions)
|
||
|
MonthlyTransaction.objects.create(
|
||
|
product=product,
|
||
|
year=year,
|
||
|
month=month,
|
||
|
price=price,
|
||
|
)
|