def decline(bag): contract = g.tran.query(db.Contract).filter_by(id=bag['id']) \ .filter(or_(db.Contract.status == 'Pending', db.Contract.status == 'Schedule')) \ .first() if not contract: raise CbsException(GENERIC_ERROR, u'Контракт не найден') if g.company.company_type != 'supplier': raise CbsException(GENERIC_ERROR, u'Вы не являетесь поставщиком!') contract.status = 'Declined' contract = { 'id': contract.id, 'code': contract.code, 'status': contract.status, 'advert_id': contract.advert_id, 'purchaser_company_id': contract.purchaser_company_id, 'supplier_company_id': contract.supplier_company_id, 'dirsection_id': contract.dirsection_id, 'total': contract.total, 'created_date': contract.created_date } contr = entity.add({CRUD: db.Contract, BOBJECT: contract}) return {'doc': contr}
def put(bag): data = {"type": bag["type"]} del bag["type"] if '_created' in bag: del bag["_created"] if '_deleted' in bag: del bag["_deleted"] table_name = data["type"] table = getattr(db, table_name) if table is None or not issubclass(table, (db.Base, db.CouchSync)): raise CbsException(TABLE_NOT_FOUND) for key in bag: data[key] = bag[key] # del_columns(data) for column in table.metadata.tables.get(table_name.lower()).columns._data: nullable = table.metadata.tables.get( table_name.lower()).columns._data[column].nullable if not nullable and not column.startswith( "_") and not column == "entry_user_id" and column not in data: raise CbsException(KEY_ERROR, MESSAGE.get(KEY_ERROR).format(column)) elif not column.startswith( "_") and not column == "entry_user_id" and column not in data: data[column] = None pg_db = PostgresDatabase() _id, _rev = pg_db.store(data, new_edits=True) return {"ok": True, "id": _id, "rev": _rev}
def putUsername(bag): user = g.tran.query(db.User).filter(db.User.id != g.user.id, db.User.username == bag[USERNAME]).first() if user is not None: raise CbsException(GENERIC_ERROR, u'Такое имя пользователя уже есть') result = re.match('^[a-zA-Z]+[\w\-_]+$', bag[USERNAME]) if not result: raise CbsException(GENERIC_ERROR, u'Имя пользователя может содержать только латинские буквы, цифры и знаки "-" и "_"!') user = g.tran.query(db.User).filter_by(id=g.user.id).first() password = sha1(bag[PASSWORD].encode('utf-8') + user.secure.encode('utf-8')).hexdigest() if password == user.password: user.username = bag[USERNAME] else: raise CbsException(WRONG_PASSWORD) return user_data = { ID: user.id, USERNAME: user.username, EMAIL: user.email, 'role': user.role, 'rec_date': user.rec_date, 'data': user.data } return {'user': user_data}
def finish(bag): inv = g.tran.query(db.Invoice)\ .filter(and_(db.Invoice.id == int(bag['id']), db.Invoice.status is not True, db.Invoice.purchaser_company_id == g.company._id))\ .first() if not inv: raise CbsException(GENERIC_ERROR, u'Не найден счет') contract = g.tran.query(db.Contract)\ .filter(and_(db.Contract.id == inv.contract_id, db.Contract.status == 'Active', db.Contract.purchaser_company_id == g.company._id))\ .first() if not contract: raise CbsException(GENERIC_ERROR, u'Не найден договор') inv.status = 'Finished' # save g.tran.add(inv) g.tran.flush() return
def wrapped_function(*args, **kwargs): # Only for not authenticated users. if not hasattr(g, 'user') or not g.user: raise CbsException(USER_NOT_AUTHORIZED) if g.user.role < 10: raise CbsException(USER_NO_ACCESS) return fn(*args, **kwargs)
def save(self, bag): if '_created' in bag: del bag["_created"] if '_deleted' in bag: del bag["_deleted"] if 'date' not in bag['data']: bag["data"]['date'] = str(datetime.now()) if '_id' in bag: query = g.tran.query(db.Document).filter_by(_id=bag['_id']) \ .filter(db.Document.data.contains(type_coerce({"user_id": g.user.id}, JSONB)), db.Document.document_status != 'committed') document = query.first() if document is None: raise CbsException(USER_NO_ACCESS) if g.user.roles_id is None: raise CbsException(GENERIC_ERROR, u'Вам необходимо получить права') else: pg_db = PostgresDatabase() bag['type'] = 'Document' bag['document_status'] = 'draft' bag['data']['user_id'] = g.user.id if len(g.user.roles_id) > 0: bag['approval']['approval_roles'] = [] for role_id in bag['approval']['roles_id']: bag['approval']['approval_roles'].append({ 'role_id': role_id }) _id, _rev = pg_db.store(bag, new_edits=True) return {"ok": True, "id": _id, "rev": _rev}
def put(bag): user = g.tran.query(db.User).filter_by(id=bag['id']).first() if user.username != bag['username']: if g.tran.query(db.User).filter_by(username=bag['username']).filter(db.User.id != user.id).count() > 0: raise CbsException(USER_ALREADY_EXISTS) if user.email != bag['email']: if g.tran.query(db.User).filter_by(email=bag['email']).filter(db.User.id != user.id).count() > 0: raise CbsException(USER_EMAIL_ALREADY_EXISTS) if 'password' in bag: password = sha1(bag[PASSWORD].encode('utf-8') + user.secure.encode('utf-8')).hexdigest() if bag[PASSWORD] != user.password and password != user.password and is_admin(): user.password = password else: CbsException(USER_NO_ACCESS) user.username = bag['username'] user.email = bag['email'] user.data = bag['data'] if 'roles_id' in bag: user.roles_id = bag['roles_id'] user_data = { ID: user.id, USERNAME: user.username, EMAIL: user.email, 'role': user.role, 'roles_id': user.roles_id, 'rec_date': user.rec_date, 'data': user.data } return {'user': user_data}
def delete(bag): if 'company_id' in g.session and not is_admin(): bag['company_id'] = g.session['company_id'] # if not is_admin() and "company_id" not in bag: # raise CbsException(USER_NO_ACCESS) table_name = bag["type"] table = getattr(db, table_name) if table is None or not issubclass(table, (db.Base, db.CouchSync)): raise CbsException(TABLE_NOT_FOUND) if not is_admin(): item_query = g.tran.query(table).filter_by(_deleted="infinity", _id=bag["_id"]) if table == db.Companies: item_query = item_query.filter(table._id == bag["company_id"], table.user_id == g.user.id) if issubclass(table, db.CompanySync): item_query = item_query.filter( table.company_id == bag["company_id"]) elif table == db.Companyemployees: item_query = item_query.filter(table.user_id == bag["user_id"]) if issubclass(table, db.CompanySync): item_query = item_query.filter( table.company_id == bag["company_id"]) else: item_query = item_query.first() if item_query is None: raise CbsException(USER_NO_ACCESS) pg_db = PostgresDatabase() _id, _rev = pg_db.remove(bag["_id"], bag["_rev"]) return {"ok": True, "id": _id, "rev": _rev}
def register(bag): if 'data' not in bag: bag['data'] = {} bag['secure'] = pyotp.random_base32() bag[PASSWORD] = sha1(bag[PASSWORD] + bag['secure']).hexdigest() if not re.match('^[a-zA-Z]+[\w\-_]+$', bag[USERNAME]): raise CbsException(GENERIC_ERROR, u'Имя пользователя может содержать только латинские буквы, цифры и знаки "-" и "_"!') user = g.tran.query(db.User).filter(or_(db.User.username == bag[USERNAME], db.User.email == bag[EMAIL])).first() if user: raise CbsException(USER_ALREADY_EXISTS) user = entity.add({CRUD: db.User, BOBJECT: bag}) user_data = { ID: user.id, USERNAME: user.username, EMAIL: user.email, 'role': user.role, 'roles_id': user.roles_id, 'rec_date': user.rec_date, 'data': user.data } token = redis_session.open_session({'user_id': user.id}) return {'token': token, 'user': user_data}
def finish(bag): contract = g.tran.query(db.Contract) \ .filter(and_(db.Contract.id == bag['id'], db.Contract.status == 'Active', db.Contract.purchaser_company_id == g.company._id)) \ .first() if not contract: raise CbsException(GENERIC_ERROR, u'Не найден договор') invoices = g.tran.query(db.Invoice) \ .filter(and_(db.Invoice.contract_id == contract.id, db.Invoice.status != 'Finished')) \ .all() if invoices: raise CbsException( GENERIC_ERROR, u'Необходимо завершить все платежи по данному контракту!') consigments = g.tran.query(db.Consignment) \ .filter(db.Consignment.contract_id == contract.id, db.Consignment.got_status != True) \ .all() if consigments: raise CbsException(GENERIC_ERROR, u'Необходимо завершить накладные!') contract.status = 'Finished' # save g.tran.add(contract) g.tran.flush() return
def check_email(email): if has_cyrillic(email): raise CbsException(CYRILLIC_LOGIN) if not is_valid_email(email): raise CbsException(WRONG_EMAIL) user = g.tran.query(db.User).filter(db.User.email == email).first() if user: raise CbsException(USER_EMAIL_ALREADY_EXISTS)
def check_role(): role_type = g.user.roleType err_msg = 'У Вас нет полномочий для этой подписи.Необходим учетная запись Руководителя организации.' if role_type['roleType'] == 1: if role_type['id'] != 8: raise CbsException(GENERIC_ERROR, err_msg) elif role_type['roleType'] == 2: if role_type['id'] != 5: raise CbsException(GENERIC_ERROR, err_msg)
def get(bag): if not bag.get('inn'): raise CbsException(GENERIC_ERROR, u'ИНН организации отсутствует') if not bag.get('code'): raise CbsException(GENERIC_ERROR, u'CPV Код отсутствует') url = "http://localhost:8080" data = {'inn': bag['inn'], 'code': bag['code']} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers, timeout=60) return {'data': r}
def build(doc_type): if not doc_type: raise CbsException(DOCUMENT_TYPE_UNDEFINED) try: module = importlib.import_module('app.docs.' + doc_type) clazz = getattr(module, doc_type.capitalize()) clazz = clazz() except Exception: raise CbsException(DOCUMENT_TYPE_UNDEFINED) return clazz
def check_password(bag): if has_cyrillic(bag[PASSWORD]): raise CbsException(CYRILLIC_PASSWORD) elif not has_digit(bag[PASSWORD]): raise CbsException(PASSWORD_MUSTBE_LATIN_AND_DIGIT) elif not has_latin(bag[PASSWORD]): raise CbsException(PASSWORD_MUSTBE_LATIN_AND_DIGIT) elif 'confirm_password' in bag and bag[PASSWORD] != bag['confirm_password']: raise CbsException(DO_NOT_MATCH_PASSWORDS) elif len(bag[PASSWORD]) < 6: raise CbsException(PASSWORD_MUSTBE_MORE_THAN_6_SYMBOLS)
def app_check(bag): if bag.get('_id'): advert = g.tran.query(db.Advert).filter_by(_deleted='infinity', _id=bag['_id'], status='Published').first() advert_lots = g.tran.query(db.Advert_lot).filter_by( _deleted='infinity', advert_id=advert._id).all() for lot in advert_lots: applications = g.tran.query(db.Application).filter_by( _deleted='infinity', advert_lot_id=lot._id).all() for app in applications: if app.company_id != g.company._id: c_emp_user_ids = [] my_c_emp_user_ids = [] company_employes = g.tran.query(db.Companyemployees) \ .filter(db.Companyemployees.company_id == app.company_id).all() for user in company_employes: c_emp_user_ids.append(user.user_id) my_comp_emp = g.tran.query(db.Companyemployees) \ .filter(db.Companyemployees.company_id == g.company._id).all() for user in my_comp_emp: my_c_emp_user_ids.append(user.user_id) ce = Set(c_emp_user_ids) mce = Set(my_c_emp_user_ids) set_user = list(ce.intersection(mce)) if len(set_user) > 0: raise CbsException( GENERIC_ERROR, u'Уважаемый поставщик, система не пропустит заявку поставщика, если подается' u' одними и теми же лицами от двух и более организаций на опубликованный ' u'конкурс либо закупку, в этой связи просим проверить у себя лиц, подавщих ' u'заявку от другой организации, но числящийся в вашей организации.' u' Основание: "Статья 6 Конфликт интересов" Закона Кыргызской ' u'Республики о государственных закупках') return
def saveapproval(self, bag): if '_created' in bag: del bag["_created"] if '_deleted' in bag: del bag["_deleted"] if 'date' not in bag['data']: bag["data"]['date'] = str(datetime.now()) if '_id' in bag: query = g.tran.query(db.Document).filter_by(_id=bag['_id']) \ .filter(db.Document.document_status != 'committed') document = query.first() if document is None: raise CbsException(USER_NO_ACCESS) pg_db = PostgresDatabase() bag['type'] = 'Document' bag['document_status'] = 'draft' if len(g.user.roles_id) > 0: bag['approval']['approval_roles'] = [] for role_id in bag['approval']['roles_id']: bag['approval']['approval_roles'].append({ 'role_id': role_id }) _id, _rev = pg_db.store(bag, new_edits=True) return {"ok": True, "id": _id, "rev": _rev}
def wrapped_function(*args, **kwargs): if not hasattr(g, 'company') and g.company.company_type == 'supplier': raise CbsException( GENERIC_ERROR, u'Ваша организация не является поставщиком!') return fn(*args, **kwargs)
def pur_submit(bag): con_status = ["Schedule", "Review"] contract = g.tran.query(db.Contract) \ .filter_by(id=bag['id']) \ .filter(and_(db.Contract.status.in_(con_status), db.Contract.purchaser_company_id == g.company._id)) \ .first() if not contract: raise CbsException(GENERIC_ERROR, u'Не найден договор') contract.date_pur_submit = datetime.datetime.now() contract.status = 'Pending' if bag.get('comment'): contract.comment.append({ "pur_company": g.company._id, "comment": bag['comment'], "date": datetime.datetime.now() }) # save entity.add({CRUD: db.Contract, BOBJECT: orm_to_json(contract)}) return
def listing(bag): invoices = [] pur_comp = aliased(db.Companies) sup_comp = aliased(db.Companies) if not bag.get('contract_id'): raise CbsException(GENERIC_ERROR, u'Укажите id договора') sql = g.tran.query(db.Invoice, pur_comp.short_name.label('pur_company'), db.DirSection, sup_comp.short_name.label('sup_company')) \ .outerjoin(pur_comp, and_(db.Invoice.purchaser_company_id == pur_comp._id, pur_comp._deleted == INFINITY)) \ .outerjoin(db.Advert, and_(db.Invoice.advert_id == db.Advert._id, db.Advert._deleted == INFINITY)) \ .outerjoin(db.DirSection, and_(db.Advert.dirsection_id == db.DirSection._id, db.DirSection._deleted == INFINITY)) \ .outerjoin(sup_comp, and_(db.Invoice.supplier_company_id == sup_comp._id, sup_comp._deleted == INFINITY)) \ .filter(or_(db.Invoice.purchaser_company_id == g.company._id, db.Invoice.supplier_company_id == g.company._id)) \ .filter(db.Invoice.contract_id == bag['contract_id'])\ .order_by(db.Invoice.date)\ .order_by(db.Invoice.created_date) for ct, pur_company, section, sup_company in sql.all(): contract = orm_to_json(ct) contract['pur_company'] = pur_company if pur_company else '' contract['sup_company'] = sup_company if sup_company else '' contract['dirsection'] = section.name if section else '' invoices.append(contract) return {'docs': invoices}
def read(bag): notification = g.tran.query(db.NotificationCompany).filter_by( company_id=g.company._id, id=bag[ID]).first() if notification: notification.notification_status = 'read' return {'notification': notification} raise CbsException(NO_DATA)
def getSpecDict(bag): if "id" in bag: Advert_lot_specifications = g.tran.query(db.Advert_lot_specification) \ .filter_by(_deleted='infinity', advert_lot_id=bag['id']).all() Advert_lot_dictionary = g.tran.query(db.Advert_lot_dictionaries) \ .filter_by(_deleted='infinity', advert_lot_id=bag['id']).all() s = '' code = '' for lot_spec in Advert_lot_specifications: property = g.tran.query(db.SpecificationProperty) \ .filter_by(id=lot_spec.specification_property_id).first() value = g.tran.query(db.SpecificationPropertyValue) \ .filter_by(id=lot_spec.specification_property_value_id).first() s += ' ' + property.name + ": " + value.name + ', ' for lot_dict in Advert_lot_dictionary: table = getattr(db, lot_dict.dirname) if hasattr( db, lot_dict.dirname) else None dirvalue = g.tran.query(table).filter_by( _deleted='infinity').filter( table._id == lot_dict.dictionary_id).first() spec_dict = g.tran.query(db.SpecificationDictionary).filter_by( dirname=lot_dict.dirname).first() s += ' ' + spec_dict.name + ": " + dirvalue.name + ', ' if table == db.DirUnits: code = dirvalue return {'specifications': s, 'dirunitcode': code} else: raise CbsException(GENERIC_ERROR, u'Не хватает LotId')
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 get_product(bag): if "id" in bag: product = g.tran.query(db.Product).filter_by( _deleted='infinity').filter(db.Product._id == bag["id"]).first() product.specifications = [] product.dictionaries = [] dircategory = g.tran.query( db.DirCategory).filter_by(id=product.dircategory_id).all() productspec = g.tran.query(db.ProductSpec).filter_by(_deleted='infinity') \ .filter_by(product_id=product._id).all() productdict = g.tran.query(db.ProductDict).filter_by(_deleted='infinity') \ .filter_by(product_id=product._id).all() product.dircategory = dircategory for prodspec in productspec: specs = {} property = g.tran.query(db.SpecificationProperty) \ .filter_by(id=prodspec.specification_property_id).first() value = g.tran.query(db.SpecificationPropertyValue) \ .filter_by(id=prodspec.specification_property_value_id).first() specs['property'] = property specs['value'] = value product.specifications.append(specs) for proddict in productdict: dicts = {} table = getattr(db, proddict.dirname) if hasattr( db, proddict.dirname) else None dirvalue = g.tran.query(table).filter_by( _deleted='infinity').filter( table._id == proddict.dictionary_id).first() dicts['dirname'] = proddict.dirname dicts['value'] = dirvalue product.dictionaries.append(dicts) return {'doc': product} else: raise CbsException(GENERIC_ERROR, u'Выберите продукт')
def wrapped_function(*args, **kwargs): # Only for not authenticated users. if hasattr(g, 'batch') or hasattr(g, 'user') or request.path in [ '/user/auth', '/user/register' ]: return fn(*args, **kwargs) raise CbsException(USER_NOT_AUTHORIZED)
def remove(bag): table_name = bag["type"] table = getattr(db, table_name) if table is None or not issubclass(table, (db.Base, db.CouchSync)): raise CbsException(TABLE_NOT_FOUND) if not is_admin(): item_query = g.tran.query(table).filter_by(_deleted="infinity", _id=bag["_id"]) item_query = item_query.first() if item_query is None: raise CbsException(USER_NO_ACCESS) pg_db = PostgresDatabase() _id, _rev = pg_db.remove(bag["_id"], bag["_rev"]) return {"ok": True, "id": _id, "rev": _rev}
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 listing(bag): inn = g.user.company['companyInn'] if not inn: raise CbsException(GENERIC_ERROR, u'ИНН организации отсутствует') year = datetime.date.today().year data = {'companyInn': inn, 'year': year} resp = portal_post('plan', data) return {'data': resp}
def get(bag): if hasattr(g, 'company'): roles = g.tran.query(db.Roles).filter_by(_deleted='infinity').filter( db.Roles.parent_id.in_(g.company.roles_id)) count = roles.count() roles = orm_to_json(roles.all()) else: raise CbsException(GENERIC_ERROR, u'У вас не выбрана организация') return {'docs': roles, 'count': count}
def listing(bag): if hasattr(g, 'company'): procurement_id = '62e43b5e-3cca-4d3f-9680-c106c91ed7cf' auctions_data = g.tran.query(db.Advert).filter_by(_deleted='infinity', dirprocurement_id=procurement_id) \ .order_by(db.Advert.created_date.desc(), db.Advert._created).all() if bag.get('filter', {}): if bag['filter'].get('status', ''): auctions_data = auctions_data.filter( db.Advert.status == bag['filter']['status']) auctions = [] for auction in auctions_data: advert_lots = g.tran.query( db.Advert_lot).filter_by(_deleted='infinity').filter( db.Advert_lot.advert_id == auction._id).all() lot_budget = 0 for advert_lot in advert_lots: lot_budget += advert_lot.budget dirsection = g.tran.query(db.DirSection) \ .filter_by(_deleted='infinity').filter(db.DirSection._id == auction.dirsection_id).first() organization = g.tran.query(db.Companies) \ .filter_by(_deleted='infinity') \ .filter(db.Companies._id == auction.company_id).first() dirprocurement = g.tran.query(db.DirProcurement) \ .filter_by(_deleted='infinity') \ .filter(db.DirProcurement._id == auction.dirprocurement_id).first() if g.lang == "ru": dirsectionlabel = dirsection.name elif g.lang == "en": dirsectionlabel = dirsection.name_en if dirsection.name_en else dirsection.name elif g.lang == "kg": dirsectionlabel = dirsection.name_kg if dirsection.name_kg else dirsection.name else: dirsectionlabel = dirsection.name data = { "_id": auction._id, "code": auction.code, "step": auction.step, "status": auction.status, "start_date": auction.start_date, "published_date": auction.published_date, "create_date": auction.created_date, "update_date": auction.update_date, "dirsection": dirsectionlabel, "deadline": auction.deadline, "organization": organization.name, "dirprocurement": dirprocurement.name if dirprocurement else {}, "count_lot": len(advert_lots), "budget": lot_budget } auctions.append(data) count = len(auctions) return {'docs': auctions, 'count': count} else: raise CbsException(GENERIC_ERROR, u'У вас нет выбранной организации')