def save(bag): contr = {} bag['type'] = 'Invoice' if bag.get('id'): invoice = g.tran.query(db.Invoice).filter_by(_deleted='infinity', _id=bag['id']).first() if invoice: contract = { 'type': bag['type'], 'rev': bag['rev'], 'status': bag['status'], 'contract_id': bag['contract_id'], 'advert_id': bag['advert_id'], 'advert_lot_id': bag['advert_lot_id'], 'application_id': bag['application_id'], 'purchaser_company_id': bag['purchaser_company_id'], 'supplier_company_id': bag['supplier_company_id'], 'dirsection_id': bag['dirsection_id'], 'quantity': bag['quantity'], 'unit_price': bag['unit_price'], 'total': bag['total'], 'created_date': bag['created_date'], 'updated_date': bag['updated_date'], 'comment': bag['comment'], 'data': bag['data'] } contr = controller.call(controller_name='data.put', bag=contract) else: contr = controller.call(controller_name='data.put', bag=bag) return {'doc': contr}
def publish(bag): bag_advert = bag['advert'] result = None advert = g.tran.query(db.Advert) \ .filter_by(_deleted='infinity', _id=bag_advert['_id'], status='Draft') \ .first() if not advert: raise CbsException(GENERIC_ERROR, u'Объявление не найдено') Force_status_list = [ 'ENSURE_SECURITY_KR', 'EARLY_ELECTIONS', 'LOCALIZE_FORCE_MAJEURE', 'THREE_PERCENT_SERVICE' ] dirprocumenet = g.tran.query(db.DirProcurement) \ .filter_by(_deleted='infinity').filter(db.DirProcurement.code.in_(Force_status_list), db.DirProcurement._id == advert.dirprocurement_id) \ .first() if not dirprocumenet: result = controller.call(controller_name='announce.put', bag=bag_advert) advert = orm_to_json(advert) advert['type'] = 'Advert' advert['code'] = result.get('orderNumber', get_code()) if result else get_code() advert['published_date'] = datetime.datetime.now() advert['update_date'] = datetime.datetime.now() advert['status'] = 'Published' controller.call(controller_name='data.put', bag=advert) return
def update_statuses(bag): companies = g.tran.query(db.Companies).filter_by(_deleted='infinity') \ .filter(and_(db.Companies.end_date < func.now(), db.Companies.company_status == 'confirmed')).all() for company in companies: company.company_status = 'expired' controller.call(controller_name='data.put', bag=company)
def save_dict(bag): degrees = g.tran.query( db.Academicdegree).filter_by(_deleted='infinity').all() actiontypes = g.tran.query( db.Actiontype).filter_by(_deleted='infinity').all() attestation_departments = g.tran.query( db.Attestation_department).filter_by(_deleted='infinity').all() documenttypes = g.tran.query( db.Documenttype).filter_by(_deleted='infinity').all() users = g.tran.query(db.User).all() for item in bag['data']: item['type'] = 'Userdegree' item['action_date'] = datetime.strptime(item['action_date'], '%d.%m.%Y') for documenttype in documenttypes: if item['document_type'] == documenttype.name_ru: item['documenttype_id'] = documenttype._id for degree in degrees: if item['degree'] == degree.name_ru: item['academicdegree_id'] = degree._id for actiontype in actiontypes: if item['action_type'] == actiontype.name_ru: item['actiontype_id'] = actiontype._id for attestation_department in attestation_departments: if item['attestation_department'] == attestation_department.name_ru: item['attestation_department_id'] = attestation_department._id for user in users: if item['user_id'] == user.id: item['user_id'] = user.id controller.call(controller_name='data.put', bag=item) return
def update(bag): company = g.tran.query(db.Companies).filter_by(_deleted='infinity', _id=bag['id']).first() if company: company = orm_to_json(company) company['type'] = 'Companies' company['short_name'] = bag.get('short_name', '') controller.call(controller_name='data.put', bag=company)
def commit(self, bag): pg_db = PostgresDatabase() bag['type'] = 'Document' bag['document_status'] = 'committed' _id, _rev = pg_db.store(bag) amount = 0 for product in bag['data']['products']: operation_data = { "branch_id": bag['branch_id'], "document_id": _id, "product_id": product['product_id'], "unit_id": product['unit_id'], "quantity": product['quantity'], "currency_id": bag['data']['currency_id'], "purpose_id": bag['data'].get('purpose_id', None), "quote_unit_price": product['quote_unit_price'], "total_cost": product['total_cost'], "additional_cost": product.get('additional_cost', 0), "delivery_date": bag['data'].get('delivery_date', None), "is_due": bag['data'].get('is_due', False), "due_date": bag['data'].get('due_date', None), "is_advance": bag['data'].get('is_advance', None), "employee_id": bag['data'].get('employee_id', None), "contractor_id": bag['data'].get('contractor_id', None), "comment": u'{}\n{}'.format(bag['title'], bag.get('short_desc', u'')) } controller.call('operation.put', operation_data) amount += product['total_cost'] + product.get('additional_cost', 0) payment_data = { "branch_id": bag['branch_id'], "document_id": _id, "amount": amount, "currency_id": bag['data']['currency_id'], "payment_date": datetime.now(), "payment_direction": 'we_give_them' if 'is_due' in bag['data'] and bag['data'][ 'is_due'] is True else 'they_to_us', "archive": False, "payment_type": 'debt' if 'is_due' in bag['data'] and bag['data']['is_due'] is True else 'cash', "data": { "comment": u'{}\n{}'.format(bag['title'], bag.get('short_desc', u'')) } } if 'is_advance' in bag['data'] and bag['data']['is_advance'] == True: payment_data['payment_direction'] = 'they_to_us' payment_data['payment_type'] = 'repayment' payment_data['data']['employee_id'] = bag['data']['employee_id'] else: payment_data['data']['contractor_id'] = bag['data']['contractor_id'] controller.call('accounting.put', payment_data) return {"id": _id, "rev": _rev}
def save(bag): bag["user_id"] = g.user.id document = g.tran.query(db.Documents)\ .filter_by(_deleted='infinity')\ .filter(db.Documents.theme_id == bag["theme_id"]).first() bag["document_id"] = document._id bag["status"] = 'new' controller.call(controller_name='data.put', bag=bag) return
def update(bag): remark = g.tran.query(db.DisRemarks).filter_by(_deleted='infinity')\ .filter(db.DisRemarks.dissov_id == bag["dissov_id"], db.DisRemarks.document_id == bag["document_id"], db.DisRemarks.disapp_status == bag["status"], db.DisRemarks.status == 'new').first() if remark: raise CbsException(GENERIC_ERROR, u'Не исправлено замечание') controller.call(controller_name='data.put', bag=bag)
def save(bag): if bag.get('company_type'): role_supplier = g.tran.query(db.Roles).filter_by(_deleted='infinity') \ .filter(db.Roles.data['code'].astext.cast(TEXT) == bag['company_type']).first() role_supplier = orm_to_json(role_supplier) else: role_supplier = g.tran.query(db.Roles).filter_by(_deleted='infinity') \ .filter(db.Roles.data['code'].astext.cast(TEXT) == 'supplier').first() role_supplier = orm_to_json(role_supplier) bag_company = bag['main_info'] bag_company['type'] = 'Companies' bag_company['user_id'] = g.user.id if 'roles_id' not in bag_company: bag_company['roles_id'] = [] bag_company['roles_id'].append(role_supplier['_id']) bag_company['role'] = 0 bag_company["company_status"] = bag_company["company_status"] if "company_status" in bag_company else 'waiting' bag_company["company_type"] = role_supplier['data']['code'] company = controller.call(controller_name='data.put', bag=bag_company) bag_bank = bag['bank_info'] bag_bank['company_id'] = company['id'] bag_bank['type'] = 'Companybank' bank = controller.call(controller_name='data.put', bag=bag_bank) bag_employee = {} if 'roles_id' not in bag_employee: bag_employee['roles_id'] = [] if bag.get('company_type') and bag['company_type'] == 'purchaser': role = g.tran.query(db.Roles._id).filter_by(_deleted='infinity') \ .filter(db.Roles.data['code'].astext.cast(TEXT) == 'purhead').first() else: role = g.tran.query(db.Roles._id).filter_by(_deleted='infinity') \ .filter(db.Roles.data['code'].astext.cast(TEXT) == 'head').first() bag_employee['user_id'] = g.user.id bag_employee['roles_id'] = role bag_employee['company_id'] = company['id'] bag_employee['head'] = True entity.add({CRUD: db.Companyemployees, BOBJECT: bag_employee}) bag_prequal = bag['prequal_info'] bag_prequal['company_id'] = company['id'] bag_prequal['type'] = 'Companyqualification' # bag_prequal['data'] = {} if 'certificates' in bag_prequal: bag_prequal['data']['certificates'] = bag_prequal['certificates'] if 'supplies' in bag_prequal: bag_prequal['data']['supplies'] = bag_prequal['supplies'] if 'experiences' in bag_prequal: bag_prequal['data']['experiences'] = bag_prequal['experiences'] if 'finances' in bag_prequal: bag_prequal['data']['finances'] = bag_prequal['finances'] prequal = controller.call(controller_name='data.put', bag=bag_prequal) return
def sup_submit(bag): # check_otp(g.user.phone, bag['otpcode']) contract = g.tran.query(db.Contract) \ .filter_by(id=bag['id']) \ .filter(and_(db.Contract.status == 'Pending', db.Contract.supplier_company_id == g.company._id)) \ .first() if not contract: raise CbsException(GENERIC_ERROR, u'Не найден договор') contract.date_sup_submit = datetime.datetime.now() contract.status = 'Active' sql = g.tran.query(db.Advert_lot, db.Application) \ .outerjoin(db.Application, and_(db.Advert_lot._id == db.Application.advert_lot_id, db.Application._deleted == INFINITY)) \ .filter(db.Advert_lot.advert_id == contract.advert_id, db.Advert_lot._deleted == INFINITY) for lot, appl in sql.all(): if appl: appl.lot_id = lot.lot_id appl.product_id = lot.product_id g.tran.add(appl) if bag.get('comment'): contract.comment.append({ "pur_company": g.company._id, "comment": bag['comment'], "date": datetime.datetime.now() }) advert = g.tran.query(db.Advert).filter_by(_deleted='infinity').filter( db.Advert._id == contract.advert_id).first() Force_status_list = [ 'ENSURE_SECURITY_KR', 'EARLY_ELECTIONS', 'LOCALIZE_FORCE_MAJEURE', 'THREE_PERCENT_SERVICE' ] dirprocumenet = g.tran.query(db.DirProcurement)\ .filter_by(_deleted='infinity').filter(and_(db.DirProcurement.code.in_(Force_status_list), db.DirProcurement._id == advert.dirprocurement_id))\ .first() if dirprocumenet: controller.call(controller_name='announce.sendContract', bag={ 'contract': contract, 'code': dirprocumenet.code }) else: controller.call(controller_name='announce.sendAnnounce', bag={ 'advert_id': contract.advert_id, 'contract_code': contract.code }) entity.add({CRUD: db.Contract, BOBJECT: orm_to_json(contract)}) return
def update_status(bag, status_list, new_status): company = g.tran.query(db.Companies).filter_by(_deleted='infinity', _id=bag['id']).first() if company and company.company_status in status_list: company = orm_to_json(company) company['type'] = 'Companies' company['company_status'] = new_status if new_status == 'rejected': company['reason'] = bag.get('reason') controller.call(controller_name='data.put', bag=company)
def save(bag): dircategory = g.tran.query( db.DirCategory).filter_by(id=bag['product']['dircategory_id']).first() bag['product']['status'] = 0 bag['product']['type'] = 'Product' if '_id' in bag['product']: bag['product']['_id'] = bag['product']['_id'] bag['product']['code'] = bag['product']['code'] else: stt = g.redis.incr(dircategory.code) bag['product']['code'] = dircategory.code + '-' + str(stt).zfill(3) bag['product']['barcode'] = bag['product']['barcode'] bag['product']['local'] = bag['product']['local'] bag['product']['image'] = bag['product']['image'] bag['product']['images'] = bag['product']['images'] product = controller.call(controller_name='data.put', bag=bag['product']) for prop in bag['props']: spec_item = { 'type': 'ProductSpec', 'product_id': product['id'], 'specification_id': prop['specification_id'], 'specification_property_id': prop['id'], 'specification_property_value_id': prop['value'], } if 'prodspec_id' in prop: spec_item['_id'] = prop['prodspec_id'] spec_item['_rev'] = prop['prodspec_rev'] spec_p = controller.call(controller_name='data.put', bag=spec_item) for dict in bag['dictionaries']: dict_item = { 'type': 'ProductDict', 'product_id': product['id'], 'dirname': dict['dirname'], 'dictionary_id': dict['dictionary_id'], } if 'proddict_id' in dict: dict_item['_id'] = dict['proddict_id'] dict_item['_rev'] = dict['proddict_rev'] dict_p = controller.call(controller_name='data.put', bag=dict_item) return {'resultList': u'Данные успешно сохранены'}
def rollback(self, bag): pg_db = PostgresDatabase() document = orm_to_json(g.tran.query(db.Document).filter_by(_deleted='infinity', _id=bag[ID]).one()) document['type'] = 'Document' document['document_status'] = 'canceled' _id, _rev = pg_db.store(document) for payment in g.tran.query(db.Payments).filter_by(_deleted='infinity', document_id=_id).all(): payment = orm_to_json(payment) payment['payment_status'] = 'canceled' controller.call('accounting.put', payment) for operation in g.tran.query(db.Operations).filter_by(_deleted='infinity', document_id=_id).all(): operation = orm_to_json(operation) operation['operation_status'] = 'canceled' controller.call('operation.put', operation)
def save_spec(bag): userdegrees = g.tran.query( db.Userdegree).filter_by(_deleted='infinity').all() specialities = g.tran.query( db.Specialty).filter_by(_deleted='infinity').all() for item in bag['data']: item['type'] = 'Degreespeciality' item['type'] = 'Degreespeciality' for userdegree in userdegrees: if item['document_code'] == userdegree.document_code: item['userdegree_id'] = userdegree._id for spec in specialities: if item['code'] == spec.code: item['specialty_id'] = spec._id controller.call(controller_name='data.put', bag=item) return
def activate(bag): if '_id' in bag: new = g.tran.query(db.New).filter_by(_deleted='infinity', _id=bag['_id']).first() new = orm_to_json(new) if 'active' in bag: new['type'] = 'New' new['is_active'] = bag['active'] return controller.call(controller_name='data.put', bag=new)
def save(bag): for user in bag["composition"]: if user["role"] == u"Ученый секретарь": bag["secretary"] = user["user_id"] elif user["role"] == u"Зам. председателя": bag["vicechairman"] = user["user_id"] elif user["role"] == u"Председатель": bag["chairman"] = user["user_id"] statusds = g.tran.query(db.Statusds).filter_by(_deleted="infinity").all() for status in statusds: if status.name_ru == u"Активный": bag["statusds_id"] = status._id dissov = controller.call(controller_name="data.put", bag=bag) item = {} for _user in bag["composition"]: item["abstract"] = {} item["work"] = {} item["type"] = 'Dcomposition' item["dissov_id"] = dissov["id"] item["user_id"] = _user["user_id"] item["abstract"] = _user["abstract"] item["role"] = _user["role"] item["work"] = _user["work"] item["data"] = bag.get("data") controller.call(controller_name="data.put", bag=item) prog = {} for _user in bag["programs"]: prog["type"] = 'Dspecialty' prog["dissov_id"] = dissov["id"] prog["academicdegree_id"] = _user["academicdegree"][ "academicdegree_id"] for bran in _user["branchesofscience"]: prog["branchesofscience_id"] = bran["branchesofscience_id"] for spec in _user["specialty"]: prog["specialty_id"] = spec["specialty_id"] prog["data"] = bag.get("data") controller.call(controller_name="data.put", bag=prog) # secretary = g.tran.query(db.User).filter(db.User.id == bag["secretary"]).one() # data = { # 'email': secretary.email, # 'name': secretary.first_name + '' + secretary.last_name # } # send_email(data) return
def update_deadline(bag): bag_advert = bag['advert'] advert = g.tran.query(db.Advert) \ .filter_by(_deleted='infinity', _id=bag_advert['_id'], status='Published') \ .first() if not advert: raise CbsException(GENERIC_ERROR, u'Объявление не найдено') advert = orm_to_json(advert) advert['type'] = 'Advert' advert['deadline'] = bag_advert['deadline'] advert['update_date'] = datetime.datetime.now() controller.call(controller_name='data.put', bag=advert) return
def save(bag): date = datetime.now() if not (bag.get('unit_price') and float(bag.get('unit_price')) > 0): raise CbsException(GENERIC_ERROR, u'Цена не может быть равной нулю или меньше нуля!') if bag.get('date_end') and datetime.strptime(bag['date_end'][:10], '%Y-%m-%d') < date: raise CbsException(GENERIC_ERROR, u'Пожалуйста, исправьте срок истечения даты стоимости продукта!') bag['unit_price'] = float(bag['unit_price']) bag["company_id"] = g.company._id if not bag.get('date_end'): bag["date_end"] = datetime.now() + datetime.timedelta(days=10) if bag.get('_id'): cp = g.tran.query(db.Company_product) \ .filter_by(_deleted='infinity', _id=bag['_id'], company_id=g.company._id).first() if cp: data = { "type": 'Company_product', "date_update": datetime.now(), "date_add": cp.date_add, "unit_price": bag['unit_price'], "data": bag['data'] if bag.get('data') else cp.data, "product_id": cp.product_id, "company_id": cp.company_id, "status": 'active', "date_end": bag['date_end'], "_id": cp._id, "_rev": cp._rev } else: raise CbsException(GENERIC_ERROR, u'Не найден продукт с таким id') return controller.call(controller_name='data.put', bag=data) else: bag["date_add"] = datetime.now() bag["date_update"] = datetime.now() company_product = g.tran.query(db.Company_product) \ .filter_by(_deleted='infinity', product_id=bag['product_id'], company_id=g.company._id).all() if company_product: raise CbsException(GENERIC_ERROR, u'У вас уже есть этот продукт в каталоге!') return controller.call(controller_name='data.put', bag=bag)
def get_rate(p_currency='KGS', date=None): if p_currency == 'KGS': return 1 else: try: sql = g.tran.query(db.CurrencyRate).with_for_update(read=False, of=db.CurrencyRate)\ .filter_by(_deleted='infinity').filter(db.CurrencyRate.currency == p_currency) if date is not None: # date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ') sql = sql.filter( db.CurrencyRate.currency_date.cast(ABSTIME) == date.strftime("%Y%m%d")) else: sql = sql.filter( db.CurrencyRate.currency_date.cast(ABSTIME) == func.current_date().strftime("%Y%m%d")) rate = sql.one() cur = float(rate.rate) except NoResultFound: date = datetime.now() # if date < date.today(): # raise CbsException(GENERIC_ERROR, u'Курс {0} не найден на дату: {1}'.format(p_currency, str(date))) cur = get_currency_nbkr(p_currency) if not cur: raise CbsException( GENERIC_ERROR, u'Курс {0} не найден на дату : {1}'.format( p_currency, str(date))) cr = { 'currency': p_currency, 'rate': cur, 'currency_date': datetime.now().date().strftime('%Y-%m-%d %H:%M:%S'), 'type': 'CurrencyRate' } controller.call(controller_name='data.put', bag=cr) return round(cur, 4)
def status_check(bag): advert = bag['advert'] advert['type'] = bag['type'] if advert['status'] in ['Published']: print advert['_id'] dirprocurement = g.tran.query(db.DirProcurement)\ .filter_by(_deleted='infinity', _id=advert['dirprocurement_id']).first() dirprocurement = orm_to_json(dirprocurement) if 'code' in dirprocurement['data'] and dirprocurement['data'][ 'code'] == 'Simplified': reason = 'Не состоялась в связи с отсутствием не менее двух участников' else: reason = 'Не состоялась в связи с отсутствием участников' advert_lots = g.tran.query(db.Advert_lot)\ .filter_by(_deleted='infinity', advert_id=advert['_id']).all() advert_lots = orm_to_json(advert_lots) for advert_lot in advert_lots: application_count = g.tran.query(db.Application)\ .filter_by(_deleted='infinity', advert_lot_id=advert_lot['_id'], status='Published').count() if dirprocurement['count'] > application_count: advert_lot['type'] = 'Advert_lot' advert_lot['status'] = 'Canceled' advert_lot['reason'] = reason protocol = { 'advert_lot_id': advert_lot['_id'], 'title': 'Операция отмены', 'description': advert_lot['reason'], } pr = entity.add({CRUD: db.Protocol, BOBJECT: protocol}) advert_lot_res = controller.call(controller_name='data.put', bag=advert_lot) advert['status'] = 'Evaluation' advert_res = controller.call(controller_name='data.put', bag=advert)
def check(bag): company = g.tran.query(db.Companies).filter_by(_deleted='infinity', _id=bag['id']).first() if company: company = orm_to_json(company) role = g.tran.query(db.Roles).filter_by(_deleted='infinity').filter(db.Roles._id.in_(bag['roles_id'])).first() if role and role.code == 'purchaser': item = {} emprole = g.tran.query(db.Roles._id).filter_by(_deleted='infinity') \ .filter(db.Roles.data['code'].astext.cast(TEXT) == 'purhead').first() employee = g.tran.query(db.Companyemployees).filter(db.Companyemployees.company_id == bag['id']).first() item['company_id'] = company['_id'] item['user_id'] = company['user_id'] item['roles_id'] = emprole item['head'] = True item['data'] = employee.data item['id'] = employee.id entity.add({CRUD: db.Companyemployees, BOBJECT: item}) company['type'] = 'Companies' company['company_status'] = bag['company_status'] company['roles_id'] = bag['roles_id'] company['end_date'] = (datetime.date.today() + datetime.timedelta(6 * 365 / 12)).isoformat() controller.call(controller_name='data.put', bag=company)
def wrapper_function(bag): if service_name: bag.update(call(service_name, bag)) elif controller_name: bag.update(controller.call(controller_name, bag)) if not output: return fn(bag) res = fn(bag) if res is dict: bag.update(res) ret = {} for k in output: ret[k] = bag[k] return ret
def save(bag): country = g.tran.query(db.Countries.name).filter_by(_deleted='infinity')\ .filter(db.Countries._id == bag['country_id']).first() country = orm_to_json(country) dateperiod = parse(bag['date']) month = str(dateperiod.month) years = str(dateperiod.year) day = str(dateperiod.day) period_querter = years + '-' + month + '-' + day stt = g.redis.incr("APOSTILLE") bag['number'] = str(stt).zfill(5) bag['barcode'] = (''.join(choice(digits) for i in range(12))) bag['qrcode'] = "Номер:{0}\nДата проставления апостиля: {1}\nСтрана, в которой будет предъявлен документ:{2}"\ .format(bag['number'], period_querter, country or "") temp_result = controller.call(controller_name='data.put', bag=bag) return {'resultList': temp_result}
def update_lot(bag): try: curr_lot = g.tran.query(db.Advert_lot) \ .filter_by(_deleted='infinity', _id=bag['lot_id'], advert_id=bag['announce_id']).one() if bag.get('reason', ''): lot = orm_to_json(curr_lot) lot['type'] = 'Advert_lot' lot['reason'] = bag['reason'] lot['status'] = 'Canceled' advert_lot = controller.call(controller_name='data.put', bag=lot) else: lot_applications = g.tran.query(db.Application) \ .filter(and_(db.Application.advert_lot_id == curr_lot._id, db.Application._deleted == INFINITY)) \ .order_by(db.Application.total, db.Application._created).all() for appl in lot_applications: appls = [ ap for ap in bag['applications'] if appl._id == ap['_id'] ] curr_lot = appls[0] if curr_lot['selected']: break if not curr_lot['reason']: raise CbsException( GENERIC_ERROR, u'Введите причину для отмены закупки данной позиции') appl.reason = curr_lot['reason'] g.tran.add(appl) g.tran.flush() except NoResultFound: raise CbsException(GENERIC_ERROR, u'Позиция в объявлении не найдены')
def save(bag): bag["user_id"] = g.user.id bag["status"] = u"Новый " controller.call(controller_name='data.put', bag=bag) return
def update(bag): try: curr_advert = g.tran.query(db.Advert) \ .filter_by(_deleted='infinity', _id=bag['id']) \ .filter(db.Advert.status.in_(['Evaluation', 'Published'])).one() advert = orm_to_json(curr_advert) advert['type'] = 'Advert' if bag.get('reason', ''): advert['status'] = 'Canceled' advert['reason'] = bag['reason'] else: advert['status'] = 'Results' lots = g.tran.query(db.Advert_lot).filter_by(_deleted='infinity') \ .filter(and_(db.Advert_lot.advert_id == advert['_id'], or_(db.Advert_lot.status != 'Canceled', db.Advert_lot.status == None))) \ .order_by(db.Advert_lot._created.desc()).all() for lot in lots: appl = g.tran.query(db.Application) \ .filter(db.Application.advert_lot_id == lot._id, db.Application._deleted == INFINITY, db.Application.selected == True) \ .first() if appl: contr = g.tran.query(db.Contract) \ .outerjoin(db.ContractLots, db.Contract.id == db.ContractLots.contract_id) \ .filter(and_(db.Contract.advert_id == bag['id'], db.Contract.supplier_company_id == appl.company_id)).first() if not contr: sum_total = 0 for l in lots: application = g.tran.query(db.Application) \ .filter(and_(db.Application.advert_lot_id == l._id, db.Application._deleted == INFINITY, db.Application.selected == True, db.Application.company_id == appl.company_id)) \ .first() if application: sum_total += application.total contract = { 'code': get_code(), 'status': 'Schedule', 'advert_id': advert['_id'], 'purchaser_company_id': advert['company_id'], 'supplier_company_id': appl.company_id, 'dirsection_id': advert['dirsection_id'], 'total': sum_total, 'created_date': func.now(), } contr = entity.add({ CRUD: db.Contract, BOBJECT: contract }) if contr: text = { "company_id": appl.company_id, "type": "Announce", "title": u"Вам отправили договор", "title_kg": u"Сизге келишим жиберилди", "title_en": u"You sent the contract", "description": u"Вы получили договор, пожалуйста дайте ответ по договору", "description_kg": u"Сизге келишим жөнөтүлдү, келишим боюнча жооп бергиле", "description_en": u"You have received a contract, please give a response to the contract.", "notification_status": "active", "data": { 'contract_id': contr.id, 'application_id': appl._id, 'advert_lot_id': appl.advert_lot_id } } entity.add({ CRUD: db.NotificationCompany, BOBJECT: text }) con_lot = { 'contract_id': contr.id, 'status': 'Draft', 'application_id': appl._id, 'advert_lot_id': appl.advert_lot_id, } con_lot = entity.add({ CRUD: db.ContractLots, BOBJECT: con_lot }) else: break advert = controller.call(controller_name='data.put', bag=advert) except NoResultFound: raise CbsException(GENERIC_ERROR, u'Объявление не найден')
def create(bag): bag_advert = bag['advert'] advert_params = { 'type': 'Advert', 'status': 'Draft', 'dirsection_id': bag_advert['dirsection_id'], 'company_id': g.company._id, 'created_date': datetime.datetime.now(), 'update_date': datetime.datetime.now() } advert = controller.call(controller_name='data.put', bag=advert_params) ad_id = advert['id'] # lots for ad_lot in bag['advert_lots']: ad_lot['type'] = 'Advert_lot' ad_lot['advert_id'] = ad_id if 'data' not in ad_lot: ad_lot['data'] = {} ad_lot['data']['unit_price'] = ad_lot['unit_price'] if int(ad_lot['quantity']) <= 0: raise CbsException( GENERIC_ERROR, u'Кол-во не может быть отрицательным и должно быть больше нуля!' ) ad_lot['quantity'] = int(ad_lot['quantity']) if int(ad_lot['estimated_delivery_time']) <= 0: raise CbsException(GENERIC_ERROR, u'Не правильно указали срок поставок!!') ad_lot['estimated_delivery_time'] = int( ad_lot['estimated_delivery_time']) if ad_lot['quantity'] <= 0: raise CbsException(GENERIC_ERROR, u'Укажите количество') ad_lot['budget'] = format(ad_lot['quantity'] * ad_lot['unit_price'], '.2f') advert_lot = controller.call(controller_name='data.put', bag=ad_lot) dicts = ad_lot['dicts'] if len(dicts) > 0: for d in dicts: for v in d['values']: d_lot = { 'type': 'Advert_lot_dictionaries', 'advert_lot_id': advert_lot['id'], 'dirname': d['dirname'], 'dictionary_id': v['_id'] } advert_lot_dict = controller.call( controller_name='data.put', bag=d_lot) specs = ad_lot['specs'] if len(specs) > 0: for s in specs: for v in s['values']: s_lot = { 'type': 'Advert_lot_specification', 'advert_lot_id': advert_lot['id'], 'specification_id': ad_lot['dircategory_id'], 'specification_property_id': s['id'], 'specification_property_value_id': v['id'] } spec_lot = controller.call(controller_name='data.put', bag=s_lot) return {'id': ad_id}
def update_lots(bag): bag_advert = bag['advert'] advert = g.tran.query(db.Advert) \ .filter_by(_deleted='infinity', _id=bag_advert['_id'], company_id=g.company._id, status='Draft') \ .first() if not advert: raise CbsException(GENERIC_ERROR, u'Объявление не найдено') advert = orm_to_json(advert) ad_id = advert['_id'] # collect ids lots = g.tran.query(db.Advert_lot) \ .filter_by(_deleted='infinity', advert_id=advert['_id']) lot_ids = [] for ad_lot in lots: lot_ids.append(ad_lot._id) upd_lot_ids = [] for bag_lot in bag['advert_lots']: if '_id' in bag_lot: upd_lot_ids.append(bag_lot['_id']) # delete for lot_id in lot_ids: if lot_id not in upd_lot_ids: # delete specs specs = g.tran.query(db.Advert_lot_specification) \ .filter_by(_deleted='infinity', advert_lot_id=lot_id) \ .all() for spec in specs: spec = orm_to_json(spec) spec['type'] = 'Advert_lot_specification' controller.call(controller_name='data.delete', bag=spec) # delete dicts dicts = g.tran.query(db.Advert_lot_dictionaries) \ .filter_by(_deleted='infinity', advert_lot_id=lot_id) \ .all() for dict in dicts: dict = orm_to_json(dict) dict['type'] = 'Advert_lot_dictionaries' controller.call(controller_name='data.delete', bag=dict) # delete lot lot = g.tran.query(db.Advert_lot) \ .filter_by(_deleted='infinity', _id=lot_id) \ .one() lot = orm_to_json(lot) lot['type'] = 'Advert_lot' controller.call(controller_name='data.delete', bag=lot) # create / update for ad_lot in bag['advert_lots']: if '_id' in ad_lot: # update lot = g.tran.query(db.Advert_lot) \ .filter_by(_deleted='infinity', _id=ad_lot['_id'], advert_id=ad_id) \ .first() if not lot: raise CbsException(GENERIC_ERROR, u'Позиция не найдена') lot = orm_to_json(lot) lot['type'] = 'Advert_lot' lot['advert_id'] = ad_id lot['data'] = ad_lot['data'] if 'data' in ad_lot else {} lot['data']['unit_price'] = ad_lot['unit_price'] lot['quantity'] = int(ad_lot['quantity']) # lot['planid'] = ad_lot['planid'] if lot['quantity'] <= 0: raise CbsException(GENERIC_ERROR, u'Укажите количество') lot['budget'] = format(lot['quantity'] * lot['unit_price'], '.2f') lot['delivery_place'] = ad_lot['delivery_place'] lot['estimated_delivery_time'] = ad_lot['estimated_delivery_time'] advert_lot = controller.call(controller_name='data.put', bag=lot) else: # create ad_lot['type'] = 'Advert_lot' ad_lot['advert_id'] = ad_id if 'data' not in ad_lot: ad_lot['data'] = {} ad_lot['data']['unit_price'] = ad_lot['unit_price'] ad_lot['quantity'] = int(ad_lot['quantity']) if ad_lot['quantity'] <= 0: raise CbsException(GENERIC_ERROR, u'Укажите количество') ad_lot['budget'] = format( ad_lot['quantity'] * ad_lot['unit_price'], '.2f') advert_lot = controller.call(controller_name='data.put', bag=ad_lot) dicts = ad_lot['dicts'] if len(dicts) > 0: for d in dicts: for v in d['values']: d_lot = { 'type': 'Advert_lot_dictionaries', 'advert_lot_id': advert_lot['id'], 'dirname': d['dirname'], 'dictionary_id': v['_id'] } advert_lot_dict = controller.call( controller_name='data.put', bag=d_lot) specs = ad_lot['specs'] if len(specs) > 0: for s in specs: for v in s['values']: s_lot = { 'type': 'Advert_lot_specification', 'advert_lot_id': advert_lot['id'], 'specification_id': ad_lot['dircategory_id'], 'specification_property_id': s['id'], 'specification_property_value_id': v['id'] } spec_lot = controller.call(controller_name='data.put', bag=s_lot) return
def update_draft(bag): bag_advert = bag['advert'] advert = g.tran.query(db.Advert) \ .filter_by(_deleted='infinity', _id=bag_advert['_id'], company_id=g.company._id, status='Draft') \ .first() if not advert: raise CbsException(GENERIC_ERROR, u'Объявление не найдено') advert = orm_to_json(advert) advert['type'] = 'Advert' advert['guarantee'] = bag_advert['guarantee'] if bag_advert[ 'guarantee'] else None if bag_advert.get('deadline', ''): advert['deadline'] = bag_advert['deadline'] if bag_advert.get('step', ''): advert['step'] = bag_advert['step'] if bag_advert.get('start_date', ''): advert['start_date'] = bag_advert['start_date'] if bag_advert.get('dirprocurement_id', ''): dirprop = g.tran.query(db.DirProcurement) \ .filter_by(_deleted='infinity', _id=bag_advert['dirprocurement_id'], with_concession=True).first() if dirprop: dirprop = orm_to_json(dirprop) dirprod_total = float(dirprop['data']['totalsum']) advert_lots_budget = g.tran.query(db.Advert_lot) \ .filter_by(_deleted='infinity', advert_id=advert['_id']).all() total = 0 for item in advert_lots_budget: total += item.budget if float(dirprod_total) < float(total): raise CbsException( GENERIC_ERROR, u'Планируемая сумма при выборе закупки "Упрощенным методом" не ' u'может превышать пороговую сумму в {} сом'.format( dirprod_total)) advert['dirprocurement_id'] = bag_advert['dirprocurement_id'] if 'concession' in bag_advert and bag_advert['concession']: if float(bag_advert['concession']) < 0 or float( bag_advert['concession']) > 20: raise CbsException(GENERIC_ERROR, u'Значение льготы должно быть от 0 до 20 %') advert['concession'] = bag_advert['concession'] if bag_advert.get('data', False): advert['data'] = bag_advert['data'] advert['update_date'] = datetime.datetime.now() if bag_advert.get('comm_members', []): users = [] for cm in bag_advert['comm_members']: u = save_by_inn(cm) empl = { 'company_id': g.company._id, 'user_id': u.id, 'comm_member': True } e = save_comm_member(empl) cu = {'id': e.id} if cm.get('chairman', False): cu['chairman'] = True users.append(cu) if users: bag_advert['data'].update({'comm_members': users}) controller.call(controller_name='data.put', bag=advert) return
def save(bag): if isinstance(bag['roles_id'], (unicode, str)): bag['roles_id'] = bag['roles_id'].split(",") return controller.call(controller_name='data.put', bag=bag)