ciclos

ref: responsive

src/types/order.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from . import db
from datetime import datetime as dt
from .order_product import OrderProduct
from .product import Product
from sqlalchemy.sql import func
import sqlalchemy as sa
import sqlalchemy_utils as sau
from enum import Enum

class OrderStatus(Enum):
    draft = 'draft'
    confirmed = 'confirmed'

class Order(db.Model):
    __tablename__ = 'orders'
  
    id = db.Column(db.Integer, primary_key = True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable = False)
    cycle_id = db.Column(db.Integer, db.ForeignKey('cycles.id'), nullable = False)
    status = db.Column(sau.ChoiceType(OrderStatus, impl = sa.String()), server_default = 'draft')

    created_at = db.Column(db.DateTime, default = dt.utcnow)
    updated_at = db.Column(db.DateTime, default = dt.utcnow)

    order_products = db.relationship('OrderProduct', backref="order", lazy = True, cascade="save-update, merge, delete")

    def __init__(self, user_id, cycle_id):
        self.user_id = user_id
        self.cycle_id = cycle_id

    @classmethod
    def create_for(class_object, user, cycle):
        return class_object(user.id, cycle.id).create()

    def create(self):
        db.session.add(self)
        db.session.commit()

    def add_products(self, product_ids):
        # Delete the current products for this order
        for product in self.order_products:
            db.session.delete(product)
            db.session.commit()

        # Create the new entries
        for product_id in product_ids:
            OrderProduct(self.id, product_id, 1).create()

    def reopen(self):
        self.status = OrderStatus.draft
        db.session.commit()

    def confirm(self):
        self.status = OrderStatus.confirmed
        db.session.commit()

    def cancel(self):
        db.session.delete(self)

        db.session.commit()

    def selected_product_ids(self):
        return list(map(lambda entry: entry.product_id, self.order_products))

    def products(self):
        return list(map(lambda entry_id: Product.query.get(entry_id), self.selected_product_ids()))
    
    def total(self):
        prices = list(map(lambda product: product.price_on(self.cycle), self.products()))

        return sum(prices, 0)

    def to_json(self):
        return {
            "id": self.id,
            "user_id": self.user_id,
            "cycle_id": self.cycle_id,
            "products": self.selected_product_ids()
        }