#coding=utf-8
import imp
import os
import sys
import traceback
import datetime

import django
from django.utils import timezone
from django.db import transaction
from django.db.models import Sum

def agent_order_expire_remind():
    classes = ClassCommodity.objects.filter()

    for c in classes:
        order = Order.objects.filter(student__classes=c.classes, status=Order.FINISH).aggregate(amount=Sum('total_amount'))
        c.price = order['amount']
        c.save()

def setup_django_env(path):
    sys.path.insert(0, path)

    f, filename, desc = imp.find_module('settings', [path])
    imp.load_module('settings', f, filename, desc)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    sys.path.append(os.path.abspath(os.path.join(path, os.path.pardir)))

if __name__ == '__main__':
    dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
    setup_django_env(dirname+'/../bookshop_admin')
    django.setup()

    from apps.order.models import Order,Classes,ClassCommodity

    try:
        print('start=======',timezone.now())
        with transaction.atomic():
            agent_order_expire_remind()
        print('end========', timezone.now())
    except Exception as e:
        traceback.print_exc()
