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 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 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 put(bag): user = g.tran.query(db.User).filter_by(id=bag['id']).first() 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(GENERIC_ERROR, u'Такой Email зарегистрирован') 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.email = bag['email'] user.citizenship_id = bag['citizenship_id'] or None user.nationality_id = bag['nationality_id'] or None user.birthplace = bag['birthplace'] or None user.data = bag['data'] or {} user.first_name = bag['first_name'] user.last_name = bag['last_name'] user.middle_name = bag['middle_name'] user.birthday = bag['birthday'] if 'roles_id' in bag: user.roles_id = bag['roles_id'] user_data = { ID: user.id, EMAIL: user.email, 'first_name': user.first_name, 'last_name': user.last_name, 'middle_name': user.middle_name, 'role': user.role, 'roles_id': user.roles_id, 'rec_date': user.rec_date, 'data': user.data, 'citizenship_id': user.citizenship_id, 'nationality_id': user.nationality_id, 'birthplace': user.birthplace, 'status': user.status } return {'user': user_data}
def find_relations(row, related_table_name): if not isinstance(row, dict) and not isinstance(row, list): return row if isinstance(row, list): rel_column = [] for r in row: rel_column.append(find_relations(r, related_table_name)) return rel_column rel_column = {} if '_deleted' in row: del row['_deleted'] for column in row: if re.match("[\w_]+_id", column) and (isinstance( row[column], basestring) or isinstance(row[column], int)): rel_table_name = "" up = True for char in column[:-3]: if up: rel_table_name += char.upper() up = False elif char != "_": rel_table_name += char if char == "_": up = True if rel_table_name == "Parent": related_table = getattr(db, related_table_name) if hasattr( db, related_table_name) else None else: related_table = getattr(db, rel_table_name) if hasattr( db, rel_table_name) else None if related_table is None: rel_table_name_copy = rel_table_name[:-1] + 'ies' if \ rel_table_name.endswith('y') else rel_table_name + 'es' related_table = getattr( db, rel_table_name_copy) if hasattr( db, rel_table_name_copy) else None if related_table is None: rel_table_name_copy = rel_table_name + 's' related_table = getattr( db, rel_table_name_copy) if hasattr( db, rel_table_name_copy) else None if related_table is not None: if issubclass(related_table, db.CouchSync): rel_table_data = g.tran.query(related_table).filter_by( _deleted='infinity', _id=row[column]) if issubclass(related_table, db.CompanySync): if not is_admin(): if g.company.company_type == 'agent': insurance_company = g.tran.query(db.Companies).filter_by(_deleted='infinity') \ .filter( db.Companies.agents_id.contains(type_coerce([g.company._id], JSONB))).first() # .filter(db.Companies.agent # .contains(type_coerce({'agents_id': [g.company._id]}, JSONB))).first() rel_table_data = rel_table_data.filter( or_( related_table.company_id == insurance_company._id, related_table.company_id == g.company._id)) else: rel_table_data = rel_table_data.filter_by( company_id=g.company._id) rel_table_data = rel_table_data.first() else: rel_table_data = g.tran.query(related_table).filter_by( id=row[column]) if related_table == db.User and not is_admin(): # TODO implement filter for user of company pass rel_table_data = rel_table_data.first() if rel_table_data is not None: rel_table_data = orm_to_json(rel_table_data) if issubclass(related_table, db.CouchSync): del rel_table_data["_deleted"] if 'password' in rel_table_data: del rel_table_data['password'] if 'secure' in rel_table_data: del rel_table_data['secure'] rel_column[column[:-3]] = rel_table_data rel_column[column] = row[column] elif isinstance(row[column], dict) or isinstance(row[column], list): if isinstance(row[column], list) and re.match("[\w_]+_id", column): rel_table_name = "" up = True for char in column[:-3]: if up: rel_table_name += char.upper() up = False elif char != "_": rel_table_name += char if char == "_": up = True related_table = getattr(db, rel_table_name) if hasattr( db, rel_table_name) else None if related_table is not None: rel_table_data = g.tran.query(related_table) if issubclass(related_table, db.CouchSync): rel_table_data = rel_table_data.filter_by(_deleted='infinity') \ .filter(related_table._id.in_(row[column])) if issubclass(related_table, db.CompanySync): if not is_admin(): if g.company.company_type == 'agent': insurance_company = g.tran.query(db.Companies).filter_by(_deleted='infinity') \ .filter(db.Companies.agent .contains(type_coerce({'agents_id': [g.company._id]}, JSONB))).first() rel_table_data = rel_table_data.filter( or_( related_table.company_id == insurance_company._id, related_table.company_id == g.company._id)) else: rel_table_data = rel_table_data.filter_by( company_id=g.company._id) else: rel_table_data = rel_table_data.filter( related_table.id.in_(row[column])) if related_table == db.User and not is_admin(): # TODO implement filter for user of company pass rel_table_data = orm_to_json(rel_table_data.all()) for rel_table_data_item in rel_table_data: if issubclass(related_table, db.CouchSync): del rel_table_data_item["_deleted"] if 'password' in rel_table_data_item: del rel_table_data_item['password'] if 'secure' in rel_table_data_item: del rel_table_data_item['secure'] rel_column[column[:-3]] = rel_table_data rel_column[column] = find_relations(row[column], related_table_name) else: if isinstance(row[column], basestring): rel_enum = g.tran.query(db.Enums).filter_by(name=column) \ .filter(db.Enums.data.contains(type_coerce({"key": row[column]}, JSONB))).first() if rel_enum is not None: rel_column[str.format('{}_value', column)] = rel_enum.data['name'] rel_column[column] = row[column] return rel_column
def listing(bag): table_name = bag["type"] table = getattr(db, table_name) if hasattr(db, table_name) else None if table is None or not issubclass(table, (db.Base, db.CouchSync)): raise CbsException(TABLE_NOT_FOUND) if table_name == "Organization" or table_name == "Position": query = g.tran.query() elif issubclass(table, db.Normal): query = g.tran.query(table.id).filter_by(_deleted='infinity') elif issubclass(table, db.CouchSync): query = g.tran.query(table._id).filter_by(_deleted='infinity') else: query = g.tran.query(table).filter_by(_deleted='infinity') doc_vars = vars(table) for var in doc_vars: if isinstance(doc_vars[var], InstrumentedAttribute): query = query.add_column(doc_vars[var]) if table == db.Journal: if 'filter' in bag and 'date_start' in bag['filter']: query = query.filter(table.date >= bag["filter"]["date_start"]) del bag["filter"]["date_start"] if 'filter' in bag and 'date_end' in bag['filter']: query = query.filter(bag["filter"]["date_end"] >= table.date) del bag["filter"]["date_end"] if 'filter' in bag and 'status' in bag['filter']: query = query.filter(bag["filter"]["status"] == table.status) del bag["filter"]["status"] if 'filter' in bag and 'userdoc_name' in bag['filter']: query = query.filter(table.client['name'].cast(TEXT).ilike( u"%{}%".format(bag["filter"]["userdoc_name"]))) del bag["filter"]["userdoc_name"] if 'filter' in bag and 'number' in bag['filter']: query = query.filter(table.number == bag["filter"]["number"]) del bag["filter"]["number"] if 'filter' in bag and 'user_id' in bag['filter']: query = query.filter( table.entry_user_id == bag["filter"]["user_id"]) del bag["filter"]["user_id"] if 'filter' in bag and 'country_id' in bag['filter']: query = query.filter( table.country_id == bag["filter"]["country_id"]) del bag["filter"]["country_id"] if 'filter' in bag and 'typeperson_id' in bag['filter']: query = query.filter( table.data.contains( type_coerce( {"typeperson_id": bag["filter"]["typeperson_id"]}, JSONB))) del bag["filter"]["typeperson_id"] if 'filter' in bag and 'dtypes_id' in bag['filter']: query = query.filter( table.adocument.contains( type_coerce({"dtypes_id": bag["filter"]["dtypes_id"]}, JSONB))) del bag["filter"]["dtypes_id"] elif table == db.Menus: if not is_admin(): menus_id = [] roles = g.tran.query(db.Roles).filter_by(_deleted='infinity') \ .filter(db.Roles._id.in_(g.user.roles_id if g.user.roles_id is not None else [])).all() for role in roles: menus_id.extend(role.menus_id) query = query.filter(db.Menus._id.in_(menus_id)) elif table == db.Document: if 'filter' in bag and 'search' in bag['filter']: query = query.filter( or_( db.Document.title.ilike(u"%{}%".format( bag["filter"]["search"])))) del bag["filter"]["search"] if 'filter' in bag and 'organization_id' in bag['filter']: query = query.filter(db.Document.organization_id == bag["filter"] ["organization_id"]) del bag["filter"]["organization_id"] if 'filter' in bag and 'position_id' in bag['filter']: query = query.filter( db.Document.position_id == bag["filter"]["position_id"]) del bag["filter"]["position_id"] elif table == db.Organizations: if 'search_ru' in bag: query = query.filter( table.name_ru.ilike(u"%{}%".format(bag["search_ru"]))) del bag["search_ru"] if 'search_kg' in bag: query = query.filter( table.name_kg.ilike(u"%{}%".format(bag["search_kg"]))) del bag["search_kg"] if 'search_inn' in bag: query = query.filter( table.inn.ilike(u"%{}%".format(bag["search_inn"]))) del bag["search_inn"] elif table == db.Positions: if 'search' in bag: query = query.filter( table.name.ilike(u"%{}%".format(bag["search"]))) del bag["search"] if "filter" in bag: if "data" in bag["filter"] and isinstance(bag["filter"]["data"], dict): query = query.filter( table.data.contains(type_coerce(bag["filter"]["data"], JSONB))) del bag["filter"]["data"] query = query.filter_by(**bag["filter"]) if "order_by" in bag: query = query.order_by(*bag["order_by"]) count = query.count() if "limit" in bag: query = query.limit(bag["limit"]) if "offset" in bag: query = query.offset(bag["offset"]) result = orm_to_json(query.all()) if "with_related" in bag and bag["with_related"] == True: result = find_relations(result, table_name) return {"docs": result, "count": count}
def listing(bag): table_name = bag["type"] table = getattr(db, table_name) if hasattr(db, table_name) else None if table is None or not issubclass(table, (db.Base, db.CouchSync)): raise CbsException(TABLE_NOT_FOUND) query = g.tran.query(table._id).filter_by(_deleted='infinity') doc_vars = vars(table) for var in doc_vars: if isinstance(doc_vars[var], InstrumentedAttribute): query = query.add_column(doc_vars[var]) if table == db.Menus: if not is_admin(): menus_id = [] roles = g.tran.query(db.Roles).filter_by(_deleted='infinity') \ .filter(db.Roles._id.in_(g.user.roles_id if g.user.roles_id is not None else [])).all() for role in roles: menus_id.extend(role.menus_id) query = query.filter(db.Menus._id.in_(menus_id)) if table == db.Journals: if not is_admin(): query = g.tran.query( db.Journals).filter(db.Journals.entry_user_id == g.user.id) if table == db.Queue: dissov = g.tran.query(db.Dissov).filter_by(_deleted='infinity')\ .filter(db.Dissov.secretary == g.user.id).first() query = query.filter(table.dissov_id == dissov._id) if table == db.New: if "sectionsofpublication_id" in bag: query = query.filter(db.New.sectionsofpublication_id == bag["sectionsofpublication_id"]) del bag["sectionsofpublication_id"] if table == db.Dcomposition: if "dissov_id" in bag: query = query.filter(db.Dcomposition.dissov_id == bag["dissov_id"]) del bag["dissov_id"] if table == db.Theme: if 'user_id' in bag: query = query.filter(table.entry_user_id == bag["user_id"]) del bag["user_id"] if 'search' in bag: query = query.filter( or_(func.concat(table.name, ' ')).ilike(u"%{0}%".format(bag['search']))) del bag["search"] if "filter" in bag: if 'filter' in bag and 'user_id' in bag['filter']: query = query.filter(table.user_id == bag["filter"]["user_id"]) del bag["filter"]["user_id"] if 'filter' in bag and 'academicdegree_id' in bag['filter']: query = query.filter( table.academicdegree_id == bag["filter"]["academicdegree_id"]) del bag["filter"]["academicdegree_id"] if 'filter' in bag and 'branchesofscience_id' in bag['filter']: query = query.filter(table.branchesofscience_id == bag["filter"] ["branchesofscience_id"]) del bag["filter"]["branchesofscience_id"] if 'filter' in bag and 'specialty_id' in bag['filter']: query = query.filter( table.specialty_id == bag["filter"]["specialty_id"]) del bag["filter"]["specialty_id"] if "data" in bag["filter"] and isinstance(bag["filter"]["data"], dict): query = query.filter( table.data.contains(type_coerce(bag["filter"]["data"], JSONB))) del bag["filter"]["data"] query = query.filter_by(**bag["filter"]) if 'search' in bag: query = query.filter( or_(func.concat(table.name_ru, ' ', table.name_kg, '')).ilike(u"%{}%".format(bag['search']))) del bag["search"] if 'user_id' in bag: query = query.filter(table.user_id == bag["user_id"]) del bag["user_id"] if "order_by" in bag: query = query.order_by(*bag["order_by"]) elif bag.get(IDS) and hasattr(table, "_id"): query = query.filter(table._id.in_(bag.get(IDS))) count = query.count() if "limit" in bag: query = query.limit(bag["limit"]) if "offset" in bag: query = query.offset(bag["offset"]) if "with_related" in bag and bag["with_related"] is True: if table == db.Documents: theme = g.tran.query(func.jsonb_agg(func.row_to_json(text('theme.*')))) \ .select_from(db.Theme) \ .filter_by(_deleted='infinity').filter( db.Theme._id == db.Documents.theme_id).as_scalar() \ .label('theme') query = query.add_columns(theme) if table == db.Userdegree: degreespeciality = g.tran.query(func.jsonb_agg(func.row_to_json(text('degreespeciality.*')))) \ .select_from(db.Degreespeciality) \ .filter_by(_deleted='infinity').filter(db.Degreespeciality.userdegree_id == db.Userdegree._id).as_scalar() \ .label('degreespeciality') query = query.add_columns(degreespeciality) if table == db.Dissov: programs = g.tran.query(func.jsonb_agg(func.row_to_json(text('dspecialty.*'))))\ .select_from(db.Dspecialty)\ .filter_by(_deleted='infinity').filter(db.Dspecialty.dissov_id == db.Dissov._id).as_scalar()\ .label('programs') compositions = g.tran.query(func.jsonb_agg(func.row_to_json(text('dcomposition.*')))) \ .select_from(db.Dcomposition) \ .filter_by(_deleted='infinity').filter(db.Dcomposition.dissov_id == db.Dissov._id).as_scalar() \ .label('compositions') query = query.add_columns(programs, compositions) if table == db.DisApplication: application_status = g.tran.query( func.row_to_json(text('enums.*'))).select_from(db.Enums) \ .filter_by(_deleted='infinity', name='status') \ .filter(db.Enums.data['key'].cast(TEXT) == cast(db.DisApplication.status, TEXT)) \ .as_scalar().label('application_status') theme = g.tran.query(func.jsonb_agg(func.row_to_json(text('theme.*')))) \ .select_from(db.Theme) \ .filter_by(_deleted='infinity').filter( db.Documents._id == db.DisApplication.document_id, db.Theme._id == db.Documents.theme_id).as_scalar() \ .label('theme') remark = g.tran.query(func.jsonb_agg(func.row_to_json(text('disremarks.*')))) \ .select_from(db.DisRemarks) \ .filter_by(_deleted='infinity').filter( db.DisRemarks.dissov_id == db.DisApplication.dissov_id).as_scalar() \ .label('remark') query = query.add_columns(application_status, theme, remark) result = orm_to_json(query.all()) if "with_related" in bag and bag["with_related"] is True: result = find_relations(result, table_name) return {"docs": result, "count": count}