class searchAdConfirmMoney(db.Model, BaseModelMixin): __tablename__ = 'searchad_bra_client_order_confirm_money' id = db.Column(db.Integer, primary_key=True) client_order_id = db.Column( db.Integer, db.ForeignKey('searchAd_bra_client_order.id')) # 客户合同 client_order = db.relationship( 'searchAdClientOrder', backref=db.backref('searchad_confirm_client_order', lazy='dynamic')) order_id = db.Column( db.Integer, db.ForeignKey('searchAd_bra_order.id')) # 客户合同 order = db.relationship( 'searchAdOrder', backref=db.backref('searchad_confirm_order', lazy='dynamic')) money = db.Column(db.Float()) rebate = db.Column(db.Float()) year = db.Column(db.Integer) Q = db.Column(db.String(2)) create_time = db.Column(db.DateTime) __mapper_args__ = {'order_by': year.desc()} def __init__(self, client_order, year, Q, order, money=0.0, rebate=0.0, create_time=None): self.client_order = client_order self.order = order self.money = money self.rebate = rebate self.year = year self.Q = Q self.create_time = create_time or datetime.date.today() @property def time(self): return str(self.year) + str(self.Q)
class searchAdClientOrderBill(db.Model, BaseModelMixin, CommentMixin): __tablename__ = 'searchad_bra_client_order_bill' id = db.Column(db.Integer, primary_key=True) company = db.Column(db.String(100)) client_id = db.Column(db.Integer, db.ForeignKey('searchAd_client.id')) client = db.relationship('searchAdClient', backref=db.backref('searchad_bra_client_bill', lazy='dynamic')) medium_id = db.Column(db.Integer, db.ForeignKey('searchAd_medium.id')) medium = db.relationship('searchAdMedium', backref=db.backref('searchad_bra_medium_bill', lazy='dynamic')) resource_type = db.Column(db.Integer) # 推广形式 money = db.Column(db.Float(), default=0.0) rebate_money = db.Column(db.Float(), default=0.0) start = db.Column(db.Date) end = db.Column(db.Date) def __init__(self, company, client, medium, resource_type, money, rebate_money, start=None, end=None): self.company = company self.client = client self.medium = medium self.resource_type = resource_type self.money = money or 0.0 self.rebate_money = rebate_money or 0.0 self.start = start or datetime.date.today() self.end = end or datetime.date.today() @property def resource_type_cn(self): return BILL_RESOURCE_TYPE_CN.get(self.resource_type)
class Measurement(db.Model): __tablename__ = 'measurements' id = db.Column(db.Integer, primary_key=True, autoincrement=True) rank = db.Column(db.Integer) mass = db.Column(db.Float(asdecimal=True)) mass_unit = db.Column(db.String()) time = db.Column(db.Float(asdecimal=True)) time_unit =db.Column(db.String()) distance = db.Column(db.Float(asdecimal=True)) distance_unit = db.Column(db.String()) volume = db.Column(db.Float(asdecimal=True)) volume_unit = db.Column(db.String()) def format(self): return { 'id': self.id, 'rank': self.rank, 'mass': self.mass, 'mass_unit': self.mass_unit, 'time': self.time, 'time_unit': self.time_unit, 'distance': self.distance, 'distance_unit': self.distance_unit, 'volume': self.volume, 'volume_unit': self.volume_unit }
class Ornament(db.Model): __tablename__ = 'ornament' id = db.Column(db.String(128), unique=True, primary_key=True, default=lambda: uuid.uuid4().hex) name = db.Column(db.String(128)) weight = db.Column(db.Float()) wastage = db.Column(db.Float()) making_charge = db.Column(db.Float()) category_id = db.Column(db.String(128)) def __init__(self, name, weight, wastage, making_charge, category_id): self.name = name self.weight = weight self.wastage = wastage self.making_charge = making_charge self.category_id = category_id @staticmethod def add_stock(name, weight, wastage, making_charge, category_id): ornament = Ornament(name=name, weight=weight, wastage=wastage, making_charge=making_charge, category_id=category_id) db.session.add(ornament) db.session.commit() @staticmethod def get_all_ornaments(): ornaments = Ornament.query.all() return ornaments @staticmethod def get_ornament_by_id(_id): ornaments = Ornament.query.get(_id) return ornaments @staticmethod def modify_ornament(_id, name, weight, wastage, making_charge, category_id): ornament = Ornament.query.get(_id) ornament.name = name ornament.weight = weight ornament.wastage = wastage ornament.making_charge = making_charge ornament.category_id = category_id db.session.commit() @staticmethod def delete_ornament(_id): ornament = Ornament.query.get(_id) db.session.delete(ornament) db.session.commit()
class PetModel(db.Model): __tablename__ = 'pet' id: int = db.Column(db.Integer, primary_key=True) name: str = db.Column(db.String(100), nullable=False) species: str = db.Column(db.String(100), nullable=False) breed: str = db.Column(db.String(100), nullable=False) size: float = db.Column(db.Float(), nullable=False) weight: float = db.Column(db.Float(), nullable=False) status: str = db.Column(db.String(), nullable=False, default='ativo') proposal_id = db.Column(db.Integer, db.ForeignKey('proposal.id', ondelete='CASCADE', onupdate='CASCADE')) insured_id = db.Column(db.Integer, db.ForeignKey('insured.id', ondelete='CASCADE', onupdate='CASCADE')) created_date = db.Column(db.Date) @staticmethod def get_by_id(id_pet): return PetModel.query.filter_by(id=id_pet).first() @staticmethod def get_by_email(name): return PetModel.query.filter_by(name=name).first() @staticmethod def get_by_species(species): return db.session.query(PetModel).filter_by(species=species).all() @staticmethod def get_by_breed(breed): return db.session.query(PetModel).filter_by(breed=breed).all() @staticmethod def get_by_proposal(proposal_id): return db.session.query(PetModel).filter_by(proposal_id=proposal_id).first() @staticmethod def get_by_insured(insured_id): return db.session.query(PetModel).filter_by(insured_id=insured_id).first() @staticmethod def list_all(): return PetModel.query.order_by(PetModel.insured_id).all() def save(self): db.session.merge(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit()
class searchAdBackInvoiceRebate(db.Model, BaseModelMixin): __tablename__ = 'searchAd_bra_client_order_back_invoice_rebate' id = db.Column(db.Integer, primary_key=True) client_order_id = db.Column( db.Integer, db.ForeignKey('searchAd_bra_client_order.id')) # 客户合同 client_order = db.relationship( 'searchAdClientOrder', backref=db.backref('backinvoicerebates', lazy='dynamic')) num = db.Column(db.String(100)) # 发票号 money = db.Column(db.Float()) back_time = db.Column(db.DateTime) create_time = db.Column(db.DateTime) __mapper_args__ = {'order_by': create_time.desc()} def __init__(self, client_order, num='', money=0.0, create_time=None, back_time=None): self.client_order = client_order self.num = num self.money = money self.create_time = create_time or datetime.date.today() self.back_time = back_time or datetime.date.today() @property def back_time_cn(self): return self.back_time.strftime(DATE_FORMAT) @property def create_time_cn(self): return self.create_time.strftime(DATE_FORMAT)
class searchAdBackMoney(db.Model, BaseModelMixin): __tablename__ = 'searchAd_bra_client_order_back_money' id = db.Column(db.Integer, primary_key=True) client_order_id = db.Column( db.Integer, db.ForeignKey('searchAd_bra_client_order.id')) # 客户合同 client_order = db.relationship( 'searchAdClientOrder', backref=db.backref('backmoneys', lazy='dynamic')) money = db.Column(db.Float()) back_time = db.Column(db.DateTime) create_time = db.Column(db.DateTime) __mapper_args__ = {'order_by': create_time.desc()} def __init__(self, client_order, money=0.0, create_time=None, back_time=None): self.client_order = client_order self.money = money self.create_time = create_time or datetime.date.today() self.back_time = back_time or datetime.date.today() @property def back_time_cn(self): return self.back_time.strftime(DATE_FORMAT) @property def create_time_cn(self): return self.create_time.strftime(DATE_FORMAT) @property def real_back_money_diff_time(self): return (self.back_time.date() - self.client_order.reminde_date).days
class searchAdClientOrderExecutiveReport(db.Model, BaseModelMixin): __tablename__ = 'searchAd_bra_client_order_executive_report' id = db.Column(db.Integer, primary_key=True) client_order_id = db.Column( db.Integer, db.ForeignKey('searchAd_bra_client_order.id')) # 客户合同 client_order = db.relationship( 'searchAdClientOrder', backref=db.backref('executive_reports', lazy='dynamic')) money = db.Column(db.Float()) month_day = db.Column(db.DateTime) days = db.Column(db.Integer) create_time = db.Column(db.DateTime) # 合同文件打包 order_json = db.Column(db.Text(), default=json.dumps({})) status = db.Column(db.Integer, index=True) contract_status = db.Column(db.Integer, index=True) __table_args__ = (db.UniqueConstraint( 'client_order_id', 'month_day', name='_searchAd_client_order_month_day'),) __mapper_args__ = {'order_by': create_time.desc()} def __init__(self, client_order, money=0, month_day=None, days=0, create_time=None): self.client_order = client_order self.money = money self.month_day = month_day or datetime.date.today() self.days = days self.create_time = create_time or datetime.date.today() # 合同文件打包 self.status = client_order.status self.contract_status = client_order.contract_status # 获取相应合同字段 dict_order = {} dict_order['client_name'] = client_order.client.name dict_order['agent_name'] = client_order.agent.name dict_order['contract'] = client_order.contract dict_order['campaign'] = client_order.campaign dict_order['industry_cn'] = client_order.client.industry_cn dict_order['locations'] = client_order.locations dict_order['sales'] = [ {'id': k.id, 'name': k.name, 'location': k.team.location}for k in client_order.direct_sales] dict_order['salers_ids'] = [k['id'] for k in dict_order['sales']] dict_order['get_saler_leaders'] = [ k.id for k in client_order.get_saler_leaders()] dict_order['resource_type_cn'] = client_order.resource_type_cn dict_order['operater_users'] = [ {'id': k.id, 'name': k.name}for k in client_order.operater_users] dict_order['client_start'] = client_order.client_start.strftime( '%Y-%m-%d') dict_order['client_end'] = client_order.client_end.strftime('%Y-%m-%d') self.order_json = json.dumps(dict_order) @property def month_cn(self): return self.month_day.strftime('%Y-%m') + u'月'
class Item(db.Model): id = db.Column(db.Integer, primary_key=True) merchant_id = db.Column(db.Integer, db.ForeignKey('merchant.id', ondelete='CASCADE'), nullable=False) item_name = db.Column(db.String(50), nullable=False) item_price = db.Column(db.Float(50), nullable=False) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) # relationship rulesItem = db.relationship("RulesItem", backref="item", lazy=True) Item = db.relationship("TransactionDetail", backref="item", lazy=True) def __repr__(self): return "<Merchant %r>" % self.id
class TransactionDetail(db.Model): id = db.Column(db.Integer, primary_key=True) transaction_id = db.Column(db.Integer, db.ForeignKey('transactions.id', ondelete='CASCADE'), nullable=False) item_id = db.Column(db.Integer, db.ForeignKey('item.id', ondelete='CASCADE'), nullable=False) quantity = db.Column(db.Integer, default=1) subTotal = db.Column(db.Float(50)) status = db.Column(db.Boolean, default=1) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) def __repr__(self): return "<TransactionDetail %r>" % self.id
class searchAdClientOrder(db.Model, BaseModelMixin, CommentMixin, AttachmentMixin): __tablename__ = 'searchAd_bra_client_order' id = db.Column(db.Integer, primary_key=True) framework_order_id = db.Column( db.Integer, server_default='0', nullable=False) # 客户合同甲方 agent_id = db.Column( db.Integer, db.ForeignKey('searchAd_agent.id')) # 客户合同甲方 agent = db.relationship( 'searchAdAgent', backref=db.backref('client_orders', lazy='dynamic')) client_id = db.Column(db.Integer, db.ForeignKey('searchAd_client.id')) # 客户 client = db.relationship( 'searchAdClient', backref=db.backref('client_orders', lazy='dynamic')) campaign = db.Column(db.String(100)) # 活动名称 contract = db.Column(db.String(100)) # 客户合同号 money = db.Column(db.Float()) # 客户合同金额 contract_type = db.Column(db.Integer) # 合同类型: 标准,非标准 client_start = db.Column(db.Date) client_end = db.Column(db.Date) client_start_year = db.Column(db.Integer, index=True) client_end_year = db.Column(db.Integer, index=True) reminde_date = db.Column(db.Date) # 最迟回款日期 resource_type = db.Column(db.Integer) # 推广形式 sale_type = db.Column(db.Integer) # 资源形式 direct_sales = db.relationship('User', secondary=direct_sales) agent_sales = db.relationship('User', secondary=agent_sales) medium_orders = db.relationship( 'searchAdOrder', secondary=table_medium_orders) contract_status = db.Column(db.Integer) # 合同审批状态 status = db.Column(db.Integer) creator_id = db.Column(db.Integer, db.ForeignKey('user.id')) creator = db.relationship( 'User', backref=db.backref('searchAd_created_client_orders', lazy='dynamic')) create_time = db.Column(db.DateTime) finish_time = db.Column(db.DateTime) # 合同归档时间 back_money_status = db.Column(db.Integer) self_agent_rebate = db.Column(db.String(20)) # 单笔返点 contract_generate = True media_apply = True kind = "searchAd-client-order" __mapper_args__ = {'order_by': contract.desc()} def __init__(self, agent, client, campaign, medium_orders=None, status=STATUS_ON, back_money_status=BACK_MONEY_STATUS_NOW, self_agent_rebate='0-0', contract="", money=0, contract_type=CONTRACT_TYPE_NORMAL, sale_type=SALE_TYPE_AGENT, client_start=None, client_end=None, reminde_date=None, resource_type=RESOURCE_TYPE_AD, direct_sales=None, agent_sales=None, framework_order_id=0, creator=None, create_time=None, contract_status=CONTRACT_STATUS_NEW): self.agent = agent self.client = client self.campaign = campaign self.medium_orders = medium_orders or [] self.contract = contract self.money = money self.contract_type = contract_type self.sale_type = sale_type self.client_start = client_start or datetime.date.today() self.client_end = client_end or datetime.date.today() self.client_start_year = int(self.client_start.year) self.client_end_year = int(self.client_end.year) self.reminde_date = reminde_date or datetime.date.today() self.resource_type = resource_type self.direct_sales = direct_sales or [] self.agent_sales = agent_sales or [] self.creator = creator self.status = status self.create_time = create_time or datetime.datetime.now() self.contract_status = contract_status self.back_money_status = back_money_status self.framework_order_id = framework_order_id self.self_agent_rebate = self_agent_rebate @classmethod def get_all(cls): """查看所有没删除订单""" return [o for o in cls.query.all() if o.status in [STATUS_ON, None] and o.contract_status not in [7, 8, 9]] @classmethod def all(cls): return cls.get_all() @classmethod def delete_all(cls): return [o for o in cls.query.all() if o.status == STATUS_DEL] @property def name(self): return u"%s-%s" % (self.client.name, self.campaign) @property def mediums(self): return [x.medium for x in self.medium_orders] @property def agents(self): return [self.agent] @property def mediums_money2(self): return sum([x.medium_money2 or 0 for x in self.medium_orders]) def medium_rebate_money(self, year, month, type='profit'): rebate_money = 0 if self.client_start.year == int(year) and self.client_start.month == int(month): for medium_order in self.medium_orders: rebate = medium_order.medium.rebate_by_year( self.client_start.year) if type == 'profit': rebate_money += medium_order.medium_money2 * rebate / 100 else: rebate_money += medium_order.medium_money2 * \ (1 - rebate / 100) return rebate_money @property def agent_rebate(self): return self.agent.inad_rebate_by_year(self.client_start.year) def rebate_agent_by_month(self, year, month): rebate = self.agent.inad_rebate_by_year(year) ex_money = self.executive_report(g.user, year, [month], 'normal')[0] return round(ex_money * rebate / 100, 2) def rebate_money(self, year, month, type='profit'): rebate_money = 0 if self.client_start.year == int(year) and self.client_start.month == int(month): rebate = self.agent.inad_rebate_by_year(self.client_start.year) if type == 'profit': rebate_money += self.money * (1 - rebate / 100) else: rebate_money += self.money * rebate / 100 return rebate_money def sum_rebate_medium_by_month(self, year, month): return sum([k.rebate_medium_by_month(year, month) for k in self.medium_orders]) def sum_medium_money_by_month(self, year, month, type): return sum([k.get_executive_report_medium_money_by_month(year, month, 'normal')[type] for k in self.medium_orders]) def profit_money(self, year, month): return self.sum_medium_money_by_month(year, month, 'sale_money') - self.sum_medium_money_by_month(year, month, 'medium_money2') @property def mediums_rebate_money(self): return sum([medium_order.get_medium_rebate_money() for medium_order in self.medium_orders]) def get_medium_rebate_money(self, medium): for medium_order in self.medium_orders: if medium_order.medium == medium: return medium_order.get_medium_rebate_money() return 0.0 @property def agent_money(self): inad_rebate = self.agent.inad_rebate_by_year(year=self.start_date.year) return round(float(inad_rebate) * self.money / 100, 2) @property def agents_rebate_money(self): return self.agent_money @property def mediums_invoice_sum(self): return sum([k.money for k in searchAdMediumInvoice.query.filter_by(client_order_id=self.id)]) @property def agents_invoice_sum(self): # 一个ClientOrder实例只有一个agent return sum([k.money for k in searchAdAgentInvoice.query.filter_by(client_order_id=self.id)]) @property def mediums_invoice_apply_sum(self): invoices = searchAdMediumInvoice.query.filter_by( client_order_id=self.id) return sum([k.money for k in searchAdMediumInvoicePay.all() if k.pay_status == 3 and k.medium_invoice in invoices]) @property def agents_invoice_apply_sum(self): invoices = searchAdAgentInvoice.query.filter_by(client_order_id=self.id) return sum([k.money for k in searchAdAgentInvoicePay.all() if k.pay_status == 3 and k.agent_invoice in invoices]) @property def mediums_invoice_pass_sum(self): invoices = searchAdMediumInvoice.query.filter_by( client_order_id=self.id) return sum([k.money for k in searchAdMediumInvoicePay.all() if k.pay_status == 0 and k.medium_invoice in invoices]) @property def agent_invoice_pass_sum(self): money = 0.0 invoices = searchAdAgentInvoice.query.filter_by(client_order_id=self.id) for invoice in invoices: for invoice_pay in searchAdAgentInvoicePay.query.filter_by(pay_status=0, agent_invoice=invoice): money += invoice_pay.money return money @property def agents_invoice_pass_sum(self): return self.agent_invoice_pass_sum def get_invoice_by_status(self, type): return [invoice for invoice in self.invoices if invoice.invoice_status == type] def get_medium_rebate_invoice_by_status(self, invoice_status): return [medium_rebate_invoice for medium_rebate_invoice in self.mediumrebateinvoices if medium_rebate_invoice.invoice_status == invoice_status] def get_medium_invoice_pay_by_status(self, type): return [k for k in searchAdMediumInvoicePay.all() if k.pay_status == int(type) and k.medium_invoice in self.mediuminvoices] def get_agent_invoice_pay_by_status(self, type): return [k for k in searchAdAgentInvoicePay.all() if isinstance(k.pay_status, int) and k.agent_invoice in self.agentinvoices] def get_medium_rebate_invoice_pass_money(self): return sum([invoice.money for invoice in searchAdMediumRebateInvoice.query.filter_by(client_order_id=self.id, invoice_status=0)]) @property def medium_ids(self): return [x.medium.id for x in self.medium_orders] @property def outsources(self): return [o for mo in self.medium_orders for o in mo.outsources] def get_outsources_by_status(self, outsource_status): return [o for o in self.outsources if o.status == outsource_status] def get_outsource_status_cn(self, status): from models.outsource import OUTSOURCE_STATUS_CN return OUTSOURCE_STATUS_CN[status] @property def outsources_sum(self): return sum([o.pay_num or 0 for o in self.outsources if o.status != 0]) if self.outsources else 0 def apply_outsources(self): return [o for o in self.outsources if o.status != 0] @property def outsources_paied_sum(self): return sum([o.pay_num for o in self.outsources if o.status == 4]) if self.outsources else 0 @property def outsources_percent(self): if self.money: return "%.2f" % (self.outsources_sum * 100 / float(self.money)) if self.money else "0" else: return "%.2f" % (self.outsources_sum * 100 / 1) @property def invoice_apply_sum(self): return sum([k.money for k in searchAdInvoice.query.filter_by(client_order_id=self.id) if k.invoice_status == 3]) @property def mediums_rebate_invoice_apply_sum(self): return sum([invoice.money for invoice in searchAdMediumRebateInvoice.query.filter_by(client_order_id=self.id) if invoice.invoice_status == 3]) def get_medium_rebate_invoice_apply_sum(self, medium): return sum([invoice.money for invoice in searchAdMediumRebateInvoice.query.filter_by(client_order_id=self.id, invoice_status=3, medium=medium)]) @property def invoice_pass_sum(self): return sum([k.money for k in searchAdInvoice.query.filter_by(client_order_id=self.id) if k.invoice_status == 0]) @property def mediums_rebate_invoice_pass_sum(self): return sum([invoice.money for invoice in searchAdMediumRebateInvoice.query.filter_by(client_order_id=self.id) if invoice.invoice_status == 0]) def get_medium_rebate_invoice_pass_sum(self, medium): return sum([invoice.money for invoice in searchAdMediumRebateInvoice.query.filter_by(client_order_id=self.id, invoice_status=0, medium=medium)]) @property def invoice_percent(self): return "%.1f" % (self.invoice_pass_sum * 100 / float(self.money)) if self.money else "0" @property def locations(self): return list(set([u.location for u in self.direct_sales + self.agent_sales])) @property def locations_cn(self): return ",".join([TEAM_LOCATION_CN[l] for l in self.locations]) @property def contract_type_cn(self): return CONTRACT_TYPE_CN[self.contract_type] @property def resource_type_cn(self): return AD_PROMOTION_TYPE_CN.get(self.resource_type) @property def sale_type_cn(self): return SALE_TYPE_CN.get(self.sale_type) @property def direct_sales_names(self): return ",".join([u.name for u in self.direct_sales]) @property def agent_sales_names(self): return ",".join([u.name for u in self.agent_sales]) @property def operater_names(self): if self.medium_orders: return ",".join([u.name for u in self.medium_orders[0].operaters]) else: return '' @property def operater_ids(self): if self.medium_orders: return ",".join([str(u.id) for u in self.medium_orders[0].operaters]) else: return '' @property def operater_users(self): if self.medium_orders: return [u for u in self.medium_orders[0].operaters] else: return [] @property def leaders(self): return list(set([l for u in self.direct_sales + self.agent_sales for l in u.user_leaders])) def can_admin(self, user): """是否可以修改该订单""" admin_users = self.direct_sales + self.agent_sales + [self.creator] return user.is_searchad_leader() or user.is_contract() or user.is_searchad_leader() or user in admin_users or user.is_super_leader() def can_action(self, user, action): """是否拥有leader操作""" if action in ITEM_STATUS_LEADER_ACTIONS: return user.is_admin() or user.is_leader() else: return self.can_admin(user) def can_edit_status(self): return [CONTRACT_STATUS_NEW, CONTRACT_STATUS_APPLYCONTRACT, CONTRACT_STATUS_APPLYPASS, CONTRACT_STATUS_APPLYREJECT, CONTRACT_STATUS_MEDIA] def have_owner(self, user): """是否可以查看该订单""" owner = self.direct_sales + self.agent_sales +\ [self.creator] + self.operater_users return user.is_admin() or user in owner def order_agent_owner(self, user): """是否可以查看该订单""" owner = self.agent_sales return user in owner def order_direct_owner(self, user): """是否可以查看该订单""" owner = self.direct_sales return user in owner @classmethod def get_order_by_user(cls, user): """一个用户可以查看的所有订单""" return [o for o in cls.all() if o.have_owner(user) and o.status in [STATUS_ON, None]] def path(self): return self.info_path() @property def search_info(self): return (self.client.name + self.agent.name + self.campaign + self.contract + "".join([mo.medium.name + mo.medium_contract for mo in self.medium_orders])) @property def search_invoice_info(self): search_info = self.search_info search_info += ''.join( [k.invoice_num for k in searchAdInvoice.query.filter_by(client_order=self)]) search_info += ''.join( [k.invoice_num for k in searchAdMediumRebateInvoice.query.filter_by(client_order=self)]) search_info += ''.join( [k.invoice_num for k in searchAdMediumInvoice.query.filter_by(client_order=self)]) search_info += ''.join( [k.invoice_num for k in searchAdAgentInvoice.query.filter_by(client_order=self)]) return search_info @property def email_info(self): return u""" 类型:效果业务订单 客户订单: 客户: %s 代理/直客: %s Campaign: %s 金额: %s 销售: %s 媒体订单: %s""" % (self.client.name, self.agent.name, self.campaign, self.money, self.direct_sales_names, "\n".join([o.email_info for o in self.medium_orders])) @property def outsource_info(self): return u""" 客户订单总额: %s 元 外包应付总金额: %s 元 外包占比: %s %%""" % (self.money, self.outsources_sum, self.outsources_percent) @property def start_date(self): return self.client_start @property def end_date(self): return self.client_end @property def create_time_cn(self): return self.create_time.strftime(DATE_FORMAT) @property def start_date_cn(self): return self.start_date.strftime(DATE_FORMAT) @property def end_date_cn(self): return self.end_date.strftime(DATE_FORMAT) @property def reminde_date_cn(self): return self.reminde_date.strftime(DATE_FORMAT) @property def contract_status_cn(self): return CONTRACT_STATUS_CN[self.contract_status] def attachment_path(self): return url_for('files.searchAd_client_order_files', order_id=self.id) def info_path(self): return url_for("searchAd_order.order_info", order_id=self.id, tab_id=1) def contract_path(self): return url_for("searchAd_order.client_order_contract", order_id=self.id) def saler_invoice_path(self): return url_for("searchAd_saler_client_order_invoice.index", order_id=self.id) def finance_invoice_path(self): return url_for("searchAd_finance_client_order_invoice.info", order_id=self.id) def attach_status_confirm_path(self, attachment): return url_for('searchAd_order.client_attach_status', order_id=self.id, attachment_id=attachment.id, status=ATTACHMENT_STATUS_PASSED) def attach_status_reject_path(self, attachment): return url_for('searchAd_order.client_attach_status', order_id=self.id, attachment_id=attachment.id, status=ATTACHMENT_STATUS_REJECT) def saler_medium_invoice_path(self): return url_for("searchAd_saler_client_order_medium_invoice.index", order_id=self.id) def finance_medium_invoice_path(self): return url_for("finance_client_order_medium_pay.info", order_id=self.id) def saler_agent_invoice_path(self): return url_for("searchAd_saler_client_order_agent_invoice.index", order_id=self.id) def finance_agent_invoice_path(self): return url_for("finance_client_order_agent_pay.info", order_id=self.id) def saler_medium_rebate_invoice_path(self): return url_for("searchAd_saler_client_order_medium_rebate_invoice.index", order_id=self.id) @classmethod def contract_exist(cls, contract): is_exist = cls.query.filter_by(contract=contract).count() > 0 return is_exist def get_default_contract(self): return contract_generator(self.agent.current_framework, self.id) def delete(self): self.delete_comments() self.delete_attachments() for mo in self.medium_orders: mo.delete() db.session.delete(self) db.session.commit() @property def back_moneys(self): return sum([k.money for k in self.backmoneys] + [k.money for k in self.back_invoice_rebate_list]) @property def client_back_moneys(self): return sum([k.money for k in self.backmoneys]) @property def back_money_status_cn(self): if self.back_money_status == 0: return BACK_MONEY_STATUS_CN[BACK_MONEY_STATUS_END] else: return BACK_MONEY_STATUS_CN[self.back_money_status or 1] @property def back_money_percent(self): if self.back_money_status == 0: return 100 else: return int(float(self.back_moneys) / self.money * 100) if self.money else 0 @property def back_money_list(self): return self.backmoneys @property def back_invoice_rebate_list(self): return self.backinvoicerebates @property def back_invoice_rebate_money(self): return sum([k.money for k in self.backinvoicerebates]) @property def jiafang_name(self): return self.agent.name def outsource_operater_info_path(self): return url_for("outsource.client_orders") def outsource_info_path(self): return url_for("outsource.client_outsources", order_id=self.id) def outsource_distribute_email_info(self, title): body = u""" Dear %s: %s 【客户订单项目详情】 甲方: %s 项目: %s 客户: %s 合同号: %s 时间: %s : %s 金额: %s 【项目相关人员】 直客销售: %s 渠道销售: %s 运营: %s 附注: 致趣订单管理系统链接地址: %s by %s\n """ % (self.operater_names, title, self.agent.name, self.campaign, self.client.name, self.contract, self.start_date_cn, self.end_date_cn, self.money, self.direct_sales_names, self.agent_sales_names, self.operater_names, mail.app.config['DOMAIN'] + self.outsource_info_path(), g.user.name) return body def outsource_email_info(self, to_user, title, o_info, url, msg): body = u""" %s 【客户订单项目详情】 甲方: %s 项目: %s 客户: %s 合同号: %s 时间: %s : %s 金额: %s 外包占比: %s %% 【外包组成】 %s 【项目相关人员】 直客销售: %s 渠道销售: %s 运营: %s 留言: %s 附注: 致趣订单管理系统链接地址: %s by %s\n """ % (title, self.jiafang_name, self.campaign, self.client.name, self.contract, self.start_date_cn, self.end_date_cn, self.money, self.outsources_percent, o_info, self.direct_sales_names, self.agent_sales_names, self.operater_names, msg, url, g.user.name) return body def pre_month_money(self): if self.money: pre_money = float(self.money) / \ ((self.client_end - self.client_start).days + 1) else: pre_money = 0 pre_month_days = get_monthes_pre_days(datetime.datetime.strptime(self.start_date_cn, '%Y-%m-%d'), datetime.datetime.strptime(self.end_date_cn, '%Y-%m-%d')) pre_month_money_data = [] for k in pre_month_days: pre_month_money_data.append( {'money': '%.2f' % (pre_money * k['days']), 'month': k['month'], 'days': k['days']}) return pre_month_money_data def is_executive_report(self): return searchAdClientOrderExecutiveReport.query.filter_by(client_order=self).count() > 0 def executive_report(self, user, now_year, monthes, sale_type): if sale_type == 'agent': count = len(self.agent_sales) else: count = len(self.direct_sales) if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) if sale_type == 'normal': count = 1 pre_reports = searchAdClientOrderExecutiveReport.query.filter_by( client_order=self) moneys = [] for j in monthes: try: pre_report = pre_reports.filter_by( month_day=datetime.datetime(int(now_year), int(j), 1).date()).first() except: pre_report = None try: pre_money = pre_report.money except: pre_money = 0 try: moneys.append(round(pre_money / count, 2)) except: moneys.append(0) return moneys def get_executive_report_medium_money_by_month(self, year, month, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] else: count = len(self.direct_sales) user = self.direct_sales[0] if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) if sale_type == 'normal': count = 1 from .order import searchAdMediumOrderExecutiveReport day_month = datetime.datetime.strptime(year + '-' + month, '%Y-%m') executive_reports = searchAdMediumOrderExecutiveReport.query.filter_by( client_order=self, month_day=day_month) if executive_reports: medium_money = sum([k.medium_money for k in executive_reports]) medium_money2 = sum([k.medium_money2 for k in executive_reports]) sale_money = sum([k.sale_money for k in executive_reports]) return {'medium_money': medium_money / count, 'medium_money2': medium_money2 / count, 'sale_money': sale_money / count} else: return {'medium_money': 0, 'medium_money2': 0, 'sale_money': 0} def get_saler_leaders(self): leaders = [] for user in self.agent_sales + self.direct_sales: leaders += user.team_leaders return leaders def insert_reject_time(self): client_order_reject = searchAdClientOrderReject.query.filter_by( client_order=self, reject_time=datetime.date.today()).first() if client_order_reject: client_order_reject.reject_time = datetime.date.today() else: searchAdClientOrderReject.add( client_order=self, reject_time=datetime.date.today()) def zhixing_money(self, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] else: count = len(self.direct_sales) user = self.direct_sales[0] if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) return self.money / count def zhixing_medium_money2(self, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] else: count = len(self.direct_sales) user = self.direct_sales[0] if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) return self.mediums_money2 / count @property def order_path(self): return url_for('searchAd_order.order_info', order_id=self.id, tab_id=1) def can_edit_contract_time(self, now_date=None): if not now_date: now_date = datetime.date.today() if self.client_start.month > now_date.month: return True else: return False @property def framework_order(self): try: framework = searchAdFrameworkOrder.get(self.framework_order_id) return {'id': framework.id, 'name': framework.name} except: return {'id': 0, 'name': u'无框架'} @property def finish_time_cn(self): try: return self.finish_time.date() except: return '' @property def self_agent_rebate_value(self): if self.self_agent_rebate: p_self_agent_rebate = self.self_agent_rebate.split('-') else: p_self_agent_rebate = ['0', '0.0'] return {'status': p_self_agent_rebate[0], 'value': p_self_agent_rebate[1]}
class searchAdOrder(db.Model, BaseModelMixin, CommentMixin, AttachmentMixin): __tablename__ = 'searchAd_bra_order' id = db.Column(db.Integer, primary_key=True) campaign = db.Column(db.String(100)) # 活动名称 medium_id = db.Column(db.Integer, db.ForeignKey('searchAd_medium.id')) # 投放媒体 medium = db.relationship('searchAdMedium', backref=db.backref('orders', lazy='dynamic')) channel_type = db.Column(db.Integer) # 推广类型 order_type = db.Column(db.Integer) # 订单类型: CPM client_orders = db.relationship('searchAdClientOrder', secondary=table_medium_orders) medium_contract = db.Column(db.String(100)) # 媒体合同号 medium_money = db.Column(db.Float()) # 无效字段 medium_money2 = db.Column(db.Float()) # 给媒体/供应商下单金额 sale_money = db.Column(db.Float()) # 客户下单金额 medium_CPM = db.Column(db.Integer) # 实际CPM sale_CPM = db.Column(db.Integer) # 下单CPM discount = db.Column(db.Integer) # 折扣类型 medium_start = db.Column(db.Date) medium_end = db.Column(db.Date) operaters = db.relationship('User', secondary=operater_users) designers = db.relationship('User', secondary=designer_users) planers = db.relationship('User', secondary=planer_users) creator_id = db.Column(db.Integer, db.ForeignKey('user.id')) creator = db.relationship('User', backref=db.backref('searchAd_created_orders', lazy='dynamic')) create_time = db.Column(db.DateTime) contract_generate = True kind = "searchAd-medium-order" def __init__(self, campaign, medium, order_type=ORDER_TYPE_NORMAL, channel_type=0, medium_contract="", medium_money=0, sale_money=0, medium_money2=0, medium_CPM=0, sale_CPM=0, discount=DISCOUNT_ADD, medium_start=None, medium_end=None, operaters=None, designers=None, planers=None, creator=None, create_time=None): self.campaign = campaign self.medium = medium self.order_type = order_type self.channel_type = channel_type self.medium_contract = medium_contract self.medium_money = medium_money self.medium_money2 = medium_money2 self.sale_money = sale_money self.medium_CPM = medium_CPM self.sale_CPM = sale_CPM self.discount = discount self.medium_start = medium_start or datetime.date.today() self.medium_end = medium_end or datetime.date.today() self.operaters = operaters or [] self.designers = designers or [] self.planers = planers or [] self.creator = creator self.create_time = create_time or datetime.datetime.now() def __repr__(self): return '<Order %s>' % (self.id) @property def sale_ECPM(self): return (self.medium_money2 / float(self.sale_CPM)) if (self.medium_money2 and self.sale_CPM) else 0 @property def money_rate(self): """利润率""" if (self.sale_money and self.medium_money): return (self.sale_money - self.medium_money) / float( self.sale_money) else: return 0 @property def name(self): return self.medium.name @property def client_order(self): return searchAdClientOrder.get(self.client_orders[0].id) @property def operater_names(self): return ",".join([u.name for u in self.operaters]) @property def designers_names(self): return ",".join([u.name for u in self.designers]) @property def planers_names(self): return ",".join([u.name for u in self.planers]) @property def contract_status(self): return self.client_order.contract_status @property def contract(self): return self.client_order.contract @property def status(self): return self.client_order.status @property def order_type_cn(self): return ORDER_TYPE_CN[self.order_type] @property def channel_type_cn(self): return CHANNEL_TYPE_CN[self.channel_type] @property def email_info(self): return u""" 投放媒体: %s 售卖金额: %s (元) 媒体金额: %s (元) 预估CPM: %s 预估ECPM: %.1f 媒体金额/预估CPM 执行: %s """ % (self.medium.name, self.sale_money or 0, self.medium_money2 or 0, self.sale_CPM or 0, self.sale_ECPM, self.operater_names) @property def direct_sales(self): direct_sales = [] for k in self.client_orders: direct_sales += k.direct_sales return direct_sales @property def agent_sales(self): agent_sales = [] for k in self.client_orders: agent_sales += k.agent_sales return agent_sales def can_admin(self, user): """是否可以修改该订单""" admin_users = self.operaters + [self.creator] return user.is_searchad_leader() or user.is_media( ) or self.client_order.can_admin(user) or user in admin_users def can_action(self, user, action): """是否拥有leader操作""" if action in ITEM_STATUS_LEADER_ACTIONS: return any([user.is_admin(), user.is_leader()]) else: return self.can_admin(user) def have_owner(self, user): """是否可以查看该订单""" owner = self.operaters + self.designers + self.planers + [self.creator] return user.is_admin( ) or user in owner or self.client_order.have_owner(user) def path(self): return url_for('schedule.order_detail', order_id=self.id, step=0) def edit_path(self): return url_for('searchAd_order.medium_order', mo_id=self.id) def attachment_path(self): return url_for('files.searchAd_medium_order_files', order_id=self.id) def info_path(self): return self.client_order.order_path def attach_status_confirm_path(self, attachment): return url_for('searchAd_order.medium_attach_status', order_id=self.id, attachment_id=attachment.id, status=ATTACHMENT_STATUS_PASSED) def attach_status_reject_path(self, attachment): return url_for('searchAd_order.medium_attach_status', order_id=self.id, attachment_id=attachment.id, status=ATTACHMENT_STATUS_REJECT) @classmethod def contract_exist(cls, contract): is_exist = cls.query.filter_by(medium_contract=contract).count() > 0 return is_exist def get_default_contract(self): return contract_generator(self.medium.current_framework, self.id) @property def start_date(self): return self.medium_start @property def start_date_cn(self): return self.start_date.strftime(DATE_FORMAT) @property def end_date(self): return self.medium_end @property def end_date_cn(self): return self.end_date.strftime(DATE_FORMAT) """订单项相关""" @classmethod def all_per_order(cls): """ 所有预下单的订单 """ return [o for o in cls.all() if len(o.pre_items)] @property def pre_items(self): """预下单的订单项""" sorted_items = sorted(self.items, lambda x, y: x.create_time > y.create_time) return filter( lambda x: x.item_status in [ITEM_STATUS_PRE, ITEM_STATUS_PRE_PASS, ITEM_STATUS_ORDER_APPLY], sorted_items) def items_by_status(self, status): """某个状态的订单项""" sorted_items = sorted(self.items, lambda x, y: x.create_time > y.create_time) return filter(lambda x: x.item_status == status, sorted_items) def items_status_num(self, num): return len(self.items_by_status(num)) def items_info_by_status(self, status): """某个状态的订单项的格式化信息""" items = self.items_by_status(status) ret = items_info_by_items(items) ret['status_cn'] = ITEM_STATUS_CN[status] return ret def items_info_all(self): """全部订单项的格式化信息""" ret = items_info_by_items(self.items) ret['status_cn'] = u"全部" return ret def items_info(self): items_info = [self.items_info_by_status(x) for x in ITEM_STATUS_CN] items_info.append(self.items_info_all()) return items_info def occupy_num_by_date_position(self, date, position): return sum([ i.schedule_sum_by_date(date) for i in self.items if i.item_status in OCCUPY_RESOURCE_STATUS and i.position == position ]) @property def items_status(self): """所有订单项的状态""" return list(set([i.item_status for i in self.items])) @property def items_status_cn(self): """只关心预下单状态和已下单状态""" items_status_cn = [] if (ITEM_STATUS_PRE in self.items_status or ITEM_STATUS_PRE_PASS in self.items_status or ITEM_STATUS_ORDER_APPLY in self.items_status): items_status_cn.append(u'预下单') if ITEM_STATUS_ORDER in self.items_status: items_status_cn.append(u'已下单') return items_status_cn def status_cn_by_status(self, status): return ITEM_STATUS_CN[status] def special_sale_in_position(self, position): special_sale_items = [ i for i in self.items if i.position == position and i.special_sale ] return len(special_sale_items) def delete(self): self.delete_comments() self.delete_attachments() # for ao in self.associated_douban_orders: # ao.delete() db.session.delete(self) db.session.commit() @property def excel_table(self): items_info = self.items_info_all() excel_table = [] temp_row = [] data_start_row = 2 data_start_col = 4 # 表头 for header_cn in HEADER_BEFORE_DATE: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, header_cn, StyleTypes.header, 1, 0)) for m, m_len in items_info['months'].items(): temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, str(m) + u"月", StyleTypes.header, 0, m_len - 1)) for i in range(0, m_len - 1): temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) for header_cn in HEADER_AFTER_DATE: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, header_cn, StyleTypes.header, 1, 0)) excel_table.append(temp_row) # 第一行写完 temp_row = [] for i in range(0, len(HEADER_BEFORE_DATE)): temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) for d in items_info['dates']: if d.isoweekday() in [6, 7]: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, d.day, StyleTypes.base_weekend)) else: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, d.day, StyleTypes.base)) for i in range(0, len(HEADER_AFTER_DATE)): temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) excel_table.append(temp_row) # 第二行写完 # 填表 temp_row = [] for v, sale_type_cn, sale_type_items in items_info['items']: if not len(sale_type_items): break if sale_type_cn == u"配送": item_type = StyleTypes.gift item_weekend_type = StyleTypes.gift_weekend else: item_type = StyleTypes.base item_weekend_type = StyleTypes.base_weekend temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, sale_type_cn, item_type, len(sale_type_items) - 1, 0)) index = 1 for item in sale_type_items: if index != 1: temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, ITEM_STATUS_CN[item.item_status], item_type)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, item.position.name, item_type)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, item.position.standard_cn, item_type)) for i in range(0, len(items_info['dates'])): d = items_info['dates'][i] if d.isoweekday() in [6, 7]: if item.schedule_by_date(d): temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, item.schedule_by_date(d).num, item_weekend_type)) else: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, " ", item_weekend_type)) else: if item.schedule_by_date(d): temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, item.schedule_by_date(d).num, item_type)) else: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, " ", item_type)) formula = 'SUM(%s:%s)' % ( Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, data_start_col), Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, len(temp_row) - 1)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, item_type)) # 总预订量 temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, item.position.price, item_type)) # 刊例单价 formula = '%s*%s' % ( Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, len(temp_row) - 2), Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, len(temp_row) - 1)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, item_type)) # 刊例总价 if sale_type_cn == u"配送": temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, float(DISCOUNT_GIFT) / 100, StyleTypes.gift_discount)) elif sale_type_cn == u"补量": temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, float(DISCOUNT_ADD) / 100, StyleTypes.discount)) else: temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_NUM, float(self.discount) / 100, StyleTypes.discount)) formula = '%s*%s' % ( Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, len(temp_row) - 2), Utils.rowcol_to_cell(data_start_row + len(excel_table) - 2, len(temp_row) - 1)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, item_type)) # 净价 excel_table.append(temp_row) index += 1 temp_row = [] # totle temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, "total", StyleTypes.base, 0, 3)) temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) temp_row.append(ExcelCellItem(EXCEL_DATA_TYPE_MERGE)) for i in range(0, len(items_info['dates']) + 1): formula = 'SUM(%s:%s)' % ( Utils.rowcol_to_cell(data_start_row, data_start_col + i), Utils.rowcol_to_cell(len(excel_table) - 1, data_start_col + i)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, StyleTypes.base)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, "/", StyleTypes.base)) formula = 'SUM(%s:%s)' % ( Utils.rowcol_to_cell(data_start_row, len(temp_row)), Utils.rowcol_to_cell(len(excel_table) - 1, len(temp_row))) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, StyleTypes.base)) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_STR, "/", StyleTypes.base)) formula = 'SUM(%s:%s)' % ( Utils.rowcol_to_cell(data_start_row, len(temp_row)), Utils.rowcol_to_cell(len(excel_table) - 1, len(temp_row))) temp_row.append( ExcelCellItem(EXCEL_DATA_TYPE_FORMULA, formula, StyleTypes.base)) excel_table.append(temp_row) return excel_table def pre_month_medium_orders_money(self): if self.medium_money2: pre_medium_money2 = float(self.medium_money2) / \ ((self.medium_end - self.medium_start).days + 1) else: pre_medium_money2 = 0 if self.sale_money: pre_sale_money = float(self.sale_money) / \ ((self.medium_end - self.medium_start).days + 1) else: pre_sale_money = 0 pre_month_days = get_monthes_pre_days( datetime.datetime.strptime(self.start_date_cn, '%Y-%m-%d'), datetime.datetime.strptime(self.end_date_cn, '%Y-%m-%d')) pre_month_money_data = [] for k in pre_month_days: pre_month_money_data.append({ 'medium_money': 0, 'medium_money2': '%.2f' % (pre_medium_money2 * k['days']), 'sale_money': '%.2f' % (pre_sale_money * k['days']), 'month': k['month'], 'days': k['days'] }) return pre_month_money_data def pre_month_medium_saler_money(self): if self.sale_money: pre_money = float(self.sale_money) / \ ((self.medium_end - self.medium_start).days + 1) else: pre_money = 0 pre_month_days = get_monthes_pre_days( datetime.datetime.strptime(self.start_date_cn, '%Y-%m-%d'), datetime.datetime.strptime(self.end_date_cn, '%Y-%m-%d')) pre_month_money_data = [] for k in pre_month_days: pre_month_money_data.append({ 'money': '%.2f' % (pre_money * k['days']), 'month': k['month'], 'days': k['days'] }) return pre_month_money_data @property def medium_rebate(self): return self.medium.rebate_by_year(self.medium_start.year) def medium_rebate_by_year(self, date): return self.medium.rebate_by_year(date.year) def rebate_medium_by_month(self, year, month): rebate = self.medium.rebate_by_year(year) ex_monety = self.get_executive_report_medium_money_by_month( year, month, 'normal')['medium_money2'] return round(ex_monety * rebate / 100, 2) def get_executive_report_medium_money_by_month(self, year, month, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] elif sale_type == 'normal': count = 1 else: count = len(self.direct_sales) user = self.direct_sales[0] if sale_type != 'normal' and user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) day_month = datetime.datetime.strptime( str(year) + '-' + str(month), '%Y-%m') executive_report = searchAdMediumOrderExecutiveReport.query.filter_by( order=self, month_day=day_month).first() if executive_report: return { 'medium_money': 0, 'medium_money2': round(executive_report.medium_money2 / count, 2), 'sale_money': round(executive_report.sale_money / count, 2) } else: return {'medium_money': 0, 'medium_money2': 0, 'sale_money': 0} def zhixing_medium_money2(self, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] else: count = len(self.direct_sales) user = self.direct_sales[0] if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) if self.medium_money2: return self.medium_money2 / count return 0 def get_medium_rebate_money(self): rebate = self.medium.rebate_by_year(year=self.start_date.year) return round(1.0 * rebate * self.medium_money2 / 100, 2) @property def associated_douban_contract(self): if self.associated_douban_orders.count() > 0: return self.associated_douban_orders[0].contract return self.medium_contract @property def associated_douban_order(self): if self.associated_douban_orders.count(): return self.associated_douban_orders[0] else: return {} def associated_douban_orders_pro_month_money(self, year, month, sale_type): if sale_type == 'agent': count = len(self.agent_sales) user = self.agent_sales[0] else: count = len(self.direct_sales) user = self.direct_sales[0] if user.team.location == 3: count = len(set(self.agent_sales + self.direct_sales)) if self.associated_douban_orders.count(): pre_money = float(self.associated_douban_orders[0].money) / \ ((self.medium_end - self.medium_start).days + 1) pre_month_days = get_monthes_pre_days( datetime.datetime.strptime(self.start_date_cn, '%Y-%m-%d'), datetime.datetime.strptime(self.end_date_cn, '%Y-%m-%d')) pre_month_money_data = 0 search_pro_month = datetime.datetime.strptime( year + '-' + month, "%Y-%m") for k in pre_month_days: if k['month'] == search_pro_month: pre_month_money_data = round(pre_money * k['days'], 2) break return pre_month_money_data / count return 0