def get_all_users( include_suspend: bool = False ) -> Generator[dict[str, Any], None, None]: ''' Get all users Args: include_suspend (bool): Include suspend. Yields: Return all users datas. ''' query = {} if not include_suspend: query = { '$or': [ { 'property.suspend': { '$exists': False } }, { 'property.suspend': False }, ] } for row in UsersDB().find(query, {'_id': 1}): yield row
def count(include_suspend: bool = False) -> int: ''' Count users Args: include_suspend (bool): Include suspend. Returns: Count users. ''' query = {} if not include_suspend: query = { '$or': [ { 'property.suspend': { '$exists': False } }, { 'property.suspend': False }, ] } return UsersDB().count_documents(query)
def get(self): ''' Get user data :rtype: dict ''' return UsersDB().find_one({'$or': [{'_id': self.uid}, {'mail': self.mail}]})
def get_info(uids: list[str], need_sensitive: bool = False) -> dict[str, Any]: ''' Get user info Args: uids (list): List of `uid`. need_sensitive (bool): Return sensitive data. Returns: Return the user data. TODO: Need refactor in pydantic. ''' users = {} base_fields = { 'profile': 1, 'profile_real.phone': 1, 'profile_real.name': 1, 'profile_real.dietary_habit': 1, } if need_sensitive: base_fields['profile_real.roc_id'] = 1 for user in UsersDB().find({'_id': {'$in': uids}}, base_fields): users[user['_id']] = user oauth_data = OAuthDB().find_one( {'owner': user['_id']}, { 'data.name': 1, 'data.picture': 1, 'data.email': 1 }, ) if not oauth_data: raise Exception(f"no user's oauth: {user['_id']}") users[user['_id']]['oauth'] = { 'name': oauth_data['data']['name'], 'picture': oauth_data['data']['picture'], 'email': oauth_data['data']['email'], } if 'profile' not in user: users[user['_id']]['profile'] = { 'badge_name': oauth_data['data']['name'], 'intro': '', } if 'profile_real' not in user: users[user['_id']]['profile_real'] = { 'phone': '', 'name': '', } return users
def update_profile_real(self, data): ''' update profile :param dict data: data ''' return UsersDB().find_one_and_update( {'_id': self.uid}, {'$set': {'profile_real': data}}, return_document=ReturnDocument.AFTER, )
def get(self) -> Optional[dict[str, Any]]: ''' Get user data Returns: Return user info. ''' return UsersDB().find_one( {'$or': [{ '_id': self.uid }, { 'mail': self.mail }]})
def create(mail, force=False): ''' create user :param str mail: mail :rtype: dict ''' if not force: oauth_data = OAuthDB().find_one({'_id': mail}, {'owner': 1}) if 'owner' in oauth_data and oauth_data['owner']: raise Exception('mail:`%s` already bind' % mail) user = UsersDB().add(UsersDB.new(mail=mail)) OAuthDB().setup_owner(mail=user['mail'], uid=user['_id']) return user
def property_suspend(self, value: bool = True) -> dict[str, Any]: ''' Property suspend Args: value (bool): suspend or not. Returns: Return the updated data. ''' return UsersDB().find_one_and_update( {'_id': self.uid}, {'$set': { 'property.suspend': value }}, return_document=ReturnDocument.AFTER, )
def index() -> Text: ''' Index page ''' if request.method == 'GET': if 'tc' not in session: session['tc'] = 0 session['tc'] += 1 return render_template('./dev_index.html', count=session['tc']) if request.method == 'POST': data = request.get_json() if data: if 'casename' in data and data['casename'] == 'get': accounts = [] for user in UsersDB().find(): accounts.append(user) sessions = [] for usession in USessionDB().find(): sessions.append(usession) return jsonify({ 'sid': session['sid'], 'accounts': accounts, 'sessions': sessions, 'projects': list(Project.all()), }) if 'casename' in data and data['casename'] == 'create_project': usession = USessionDB().find_one({'_id': session['sid']}) if usession: project_data = data['project'] Project.create( pid=project_data['pid'], name=project_data['name'], owners=[ usession['uid'], ], action_date=project_data['action_date'], ) return jsonify({})
def make_index() -> None: ''' Make index for the collection with `index()` ''' BudgetDB().index() ExpenseDB().index() FormDB().index() MailLetterDB().index() MattermostLinkDB().index() MattermostUsersDB().index() OAuthDB().index() ProjectDB(pid='').index() SenderReceiverDB().index() TeamDB(pid='', tid='').index() TeamMemberChangedDB().index() TeamMemberTagsDB().index() TeamPlanDB().index() TelegramDB().index() USessionDB().index() UsersDB().index() WaitListDB().index()
def get_address(uid: str) -> dict[str, Any]: ''' Get Address Args: uid (str): User id. Returns: Return the data. TODO: Need refactor in pydantic. ''' address = {'code': '', 'receiver': '', 'address': ''} for user in UsersDB().find({'_id': uid}, {'profile_real.address': 1}): if 'profile_real' in user and 'address' in user['profile_real']: address.update(user['profile_real']['address']) return address
def get_bank(uid: str) -> dict[str, Any]: ''' Get bank info Args: uid (str): User id. Returns: Return the data. TODO: Need refactor in pydantic. ''' bank = {'code': '', 'no': '', 'branch': '', 'name': ''} for user in UsersDB().find({'_id': uid}, {'profile_real.bank': 1}): if 'profile_real' in user and 'bank' in user['profile_real']: bank.update(user['profile_real']['bank']) return bank
def update_profile_real(self, data: dict[str, Any]) -> dict[str, Any]: ''' update profile Args: data (dict): Profile data. Returns: Return the updated data. Bug: Need to verify and filter. ''' return UsersDB().find_one_and_update( {'_id': self.uid}, {'$set': { 'profile_real': data }}, return_document=ReturnDocument.AFTER, )
def get_info(uids, need_sensitive=False): ''' Get user info :param list uids: uid :param bool need_sensitive: show sensitive data ''' users = {} base_fields = {'profile': 1, 'profile_real.phone': 1, 'profile_real.name': 1, } if need_sensitive: base_fields['profile_real.roc_id'] = 1 for u in UsersDB().find({'_id': {'$in': uids}}, base_fields): users[u['_id']] = u oauth_data = OAuthDB().find_one( {'owner': u['_id']}, {'data.name': 1, 'data.picture': 1, 'data.email': 1}, ) users[u['_id']]['oauth'] = { 'name': oauth_data['data']['name'], 'picture': oauth_data['data']['picture'], 'email': oauth_data['data']['email'], } if 'profile' not in u: users[u['_id']]['profile'] = { 'badge_name': oauth_data['data']['name'], 'intro': '', } if 'profile_real' not in u: users[u['_id']]['profile_real'] = { 'phone': '', 'name': '', } return users
def create(mail: str, force: bool = False) -> dict[str, Any]: ''' create user Args: mail (str): User mail. force (bool): Force to create. Returns: Return the created data. ''' if not force: oauth_data = OAuthDB().find_one({'_id': mail}, {'owner': 1}) if oauth_data is None: raise Exception(f'mail: `{mail}` not in the oauth dbs') if 'owner' in oauth_data and oauth_data['owner']: raise Exception(f'mail:`{mail}` already bind') user = UsersDB().add(UsersDB.new(mail=mail)) OAuthDB().setup_owner(mail=user['mail'], uid=user['_id']) return user
def project_form_api(pid): ''' Project form API ''' # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements project = Project.get(pid) if g.user['account']['_id'] not in project['owners']: return redirect( url_for('project.team_page', pid=pid, _scheme='https', _external=True)) if request.method == 'POST': data = request.get_json() if 'case' not in data: return redirect( url_for('project.team_page', pid=pid, _scheme='https', _external=True)) if data['case'] == 'volunteer_certificate': fieldnames = ('uid', 'picture', 'value', 'name', 'roc_id', 'birthday', 'company') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_volunteer_certificate(pid): user_info = UsersDB().find_one({'_id': raw['uid']}) oauth = OAuthDB().find_one({'owner': raw['uid']}, {'data.picture': 1}) data = { 'uid': raw['uid'], 'picture': oauth['data']['picture'], 'value': raw['data']['value'], 'name': user_info['profile_real']['name'], 'roc_id': user_info['profile_real']['roc_id'], 'birthday': user_info['profile_real']['birthday'], 'company': user_info['profile_real']['company'], } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'traffic_fee': fieldnames = ('uid', 'picture', 'name', 'apply', 'fee', 'fromwhere', 'howto') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_traffic_fee(pid): user_info = User.get_info(uids=[ raw['uid'], ])[raw['uid']] data = { 'uid': raw['uid'], 'picture': user_info['oauth']['picture'], 'name': user_info['profile']['badge_name'], 'apply': raw['data']['apply'], 'fee': raw['data']['fee'], 'fromwhere': raw['data']['fromwhere'], 'howto': raw['data']['howto'], } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'accommodation': fieldnames = ('uid', 'picture', 'name', 'key', 'status') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_accommodation(pid): user_info = User.get_info(uids=[ raw['uid'], ])[raw['uid']] data = { 'uid': raw['uid'], 'picture': user_info['oauth']['picture'], 'name': user_info['profile']['badge_name'], 'key': raw['data']['key'], 'status': raw['data']['status'], } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'appreciation': fieldnames = ('uid', 'picture', 'name', 'available', 'key', 'value') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_appreciation(pid): if not raw['data']['available']: continue user_info = User.get_info(uids=[ raw['uid'], ])[raw['uid']] data = { 'uid': raw['uid'], 'picture': user_info['oauth']['picture'], 'name': user_info['profile']['badge_name'], 'available': raw['data']['available'], 'key': raw['data']['key'], 'value': raw['data']['value'], } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'clothes': all_users = {} for team in Team.list_by_pid(pid=pid): for uid in team['chiefs'] + team['members']: all_users[uid] = {'tid': team['tid']} user_info = User.get_info(uids=list(all_users.keys())) fieldnames = ('uid', 'picture', 'name', '_has_data', 'tid', 'clothes', 'htg') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_clothes(pid): if raw['uid'] not in all_users: continue all_users[raw['uid']]['clothes'] = raw['data']['clothes'] if 'htg' in raw['data']: all_users[raw['uid']]['htg'] = raw['data']['htg'] for uid, value in all_users.items(): data = { 'uid': uid, 'picture': user_info[uid]['oauth']['picture'], 'name': user_info[uid]['profile']['badge_name'], '_has_data': bool(value.get('clothes', False)), 'tid': value['tid'], 'clothes': value.get('clothes'), 'htg': value.get('htg'), } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'parking_card': fieldnames = ('uid', 'picture', 'name', 'carno', 'dates') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_parking_card(pid): if not raw['data']['dates']: continue user_info = User.get_info(uids=[ raw['uid'], ])[raw['uid']] data = { 'uid': raw['uid'], 'picture': user_info['oauth']['picture'], 'name': user_info['profile']['badge_name'], 'carno': raw['data']['carno'], 'dates': ', '.join(raw['data']['dates']), } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) elif data['case'] == 'drink': all_users = {} for team in Team.list_by_pid(pid=pid): for uid in team['chiefs'] + team['members']: all_users[uid] = {'tid': team['tid']} user_info = User.get_info(uids=list(all_users.keys())) fieldnames = ('uid', 'picture', 'name', '_has_data', 'tid', 'y18') with io.StringIO() as str_io: csv_writer = csv.DictWriter(str_io, fieldnames=fieldnames) csv_writer.writeheader() for raw in Form.all_drink(pid): if raw['uid'] not in all_users: continue all_users[raw['uid']]['y18'] = raw['data']['y18'] for uid, value in all_users.items(): data = { 'uid': uid, 'picture': user_info[uid]['oauth']['picture'], 'name': user_info[uid]['profile']['badge_name'], '_has_data': bool(value.get('y18')), 'tid': value['tid'], 'y18': value.get('y18'), } csv_writer.writerow(data) result = [] for raw in csv.reader(io.StringIO(str_io.getvalue())): result.append(raw) return jsonify({'result': result}) return jsonify({}), 404
from models.formdb import FormDB from models.mailletterdb import MailLetterDB from models.mattermost_link_db import MattermostLinkDB from models.mattermostdb import MattermostUsersDB from models.oauth_db import OAuthDB from models.projectdb import ProjectDB from models.senderdb import SenderReceiverDB from models.teamdb import TeamDB from models.teamdb import TeamMemberChangedDB from models.teamdb import TeamMemberTagsDB from models.teamdb import TeamPlanDB from models.users_db import UsersDB from models.usessiondb import USessionDB from models.waitlistdb import WaitListDB if __name__ == '__main__': FormDB().index() MailLetterDB().index() MattermostLinkDB().index() MattermostUsersDB().index() OAuthDB().index() ProjectDB(pid=None).index() SenderReceiverDB().index() TeamDB(pid=None, tid=None).index() TeamMemberChangedDB().index() TeamMemberTagsDB().index() TeamPlanDB().index() USessionDB().index() UsersDB().index() WaitListDB().index()