def handle_if_company_tags(i, v, splits=False): from alchemist.models.user_company import BaseCompany from alchemist.models.base import DBSession obj = BaseCompany tags = [] if splits == False: splits = [','] split = splits.pop() for tag in v.split(split): if not tag.strip(): continue if splits: tags.extend(handle_if_company_tags(i, tag, splits)) continue try: ftag = DBSession.query(obj).get(int(tag)) except: ftag = DBSession.query(obj).filter(obj.name == tag.strip()).first() if not ftag: ftag = obj(name=tag.strip()) if ftag: tags.append(ftag) v = tags return v
def __setattr__(self, name, value): if name == 'user_id': if not self._user: self._user = DBSession.query(User).get(value) types = self._user.type.split(',') types.append(self.__tablename__) self._user.type = ','.join(set(types)) return super(UserMixin, self).__setattr__(name, value) if 'tags' in name: name = 'tags' if hasattr(User, name): if not self._user and self.user_id: self._user = DBSession.query(User).get(self.user_id) if not self._user: _user = User() DBSession.add(_user) DBSession.flush() self.user_id = _user.id else: DBSession.add(self._user) try: return setattr(self._user, name, value) except DetachedInstanceError: DBSession.add(self._user) return setattr(self._user, name, value) else: return super(UserMixin, self).__setattr__(name, value)
def handle_if_company(k, v, required=True, request=False): from alchemist.models.base import DBSession from alchemist.models.company import BaseCompany from alchemist.models.settings import Settings if k in ['company', 'company_id']: is_name = False try: company_id = int(v) company = DBSession.query(BaseCompany).get(company_id) except: v = v.replace(new_company_text, '') company = DBSession.query(BaseCompany).filter(BaseCompany.name == v).first() if not company: company = DBSession.query(BaseCompany).filter(BaseCompany.name.startswith(v.strip())).first() is_name = True assert not required or company, 'The company does not exist.' if not company and is_name: company = BaseCompany() company.name = v if request and request.referer and 'add/founder' in request.referer: company.is_alchemist = True company.alchemistclass = int(Settings.get('alchemistclass')) company.companytype = 'startup' DBSession.add(company) DBSession.flush() return company.id if k == 'company_id' else company return v
def get_records(request, type, max_records, action_verb='export'): ids, excl_ids = get_ids(request) sess_query = request.session.get('query') filters = {User: [User.id.in_(ids)] if ids else user_where_from_query({'query': sess_query}), BaseCompany: [BaseCompany.id.in_(ids)] if ids else where_from_query({'sessquery': sess_query})} filters = filters[type] if excl_ids: filters.append(type.id.notin_(excl_ids)) if not request.user.is_admin: filters.append(type.activated == True) if type == User: filters.append(User.primary_type != None) elif type == BaseCompany and 'alchemist_startup' in request.referer: filters.append(BaseCompany.is_alchemist == True) filters.append(BaseCompany.companytype == 'startup') if not (ids or (request.session.get('select_all') and sess_query is not None)): request.session.flash('We didn\'t find anything to %s' % action_verb, 'error') return False if len(ids) > max_records: request.session.flash('You cannot %s more than %s %s' % (action_verb, max_records, {BaseCompany: 'companies', User: '******'}[type]), 'error') return False records = DBSession.query(type).outerjoin(User.company) if type == User else DBSession.query(type) records = records.filter(*filters).limit(max_records + 1).all() if len(records) > max_records: request.session.flash('You cannot %s more than %s %s' % (action_verb, max_records, {BaseCompany: 'companies', User: '******'}[type]), 'error') return False return records
def handle_if_tags(i, v, splits=False, is_admin=False, otype='area_of_expertise'): from alchemist.models.tag import Tag from alchemist.models.base import DBSession obj = None if i == 'tags' or i.endswith('tags') or i == 'areas_of_interest': obj = Tag if obj: tags = [] if splits == False: splits = [','] split = splits.pop() if v is not None: for tag in v.split(split): tag = tag.replace(new_tag_text, '') if not tag.strip(): continue if splits: tags.extend(handle_if_tags(i, tag, splits=splits, is_admin=is_admin, otype=otype)) continue try: ftag = DBSession.query(obj).get(int(tag)) except: ftag = DBSession.query(obj).filter(obj.text == tag.strip()).first() if not ftag and is_admin: ftag = obj(text=tag.strip(), only_type=otype) if ftag: tags.append(ftag) v = tags return v
def list_answers(page, page_size, query, request): queryAll = DBSession.query(Questions).join(Answers).filter(Answers.user_id == request.user.id) user_filter = get_filters(request) if query is not None else [] results = queryAll.filter(*user_filter). \ limit(page_size).offset(page * page_size) total = DBSession.query(func.count(Questions.id)).join(Answers).filter(Answers.user_id == request.user.id).filter( *user_filter). \ limit(page_size).offset(page * page_size).scalar() return results, total
def company(self, value): if self.company and value and self.company.id == value.id: return if self.company: DBSession.query(UserXCompany).filter(UserXCompany.company == self.company, UserXCompany.user == self, UserXCompany.end_date == None). \ update({'end_date': utcnow().datetime}) DBSession.add(UserXCompany(company=value, user=self, start_date=utcnow().datetime, relation=TypeOfRelation.employee))
def list_questions(page, page_size, query, request): user_filter = get_filters(request) if query is not None else [] if request.matchdict.get('type') == 'questions': user_filter.append(Questions.user_id == request.user.id) user_filter.append(and_(Questions.user_id != None)) results = DBSession.query(Questions).filter(*user_filter).order_by(desc(Questions.created_at)). \ limit(page_size).offset(page * page_size) total = DBSession.query(func.count(Questions.id)).filter(*user_filter). \ limit(page_size).offset(page * page_size).scalar() return results, total
def list_trackings(page, page_size, query, request): queryAll = DBSession.query(Questions).join(Trackers).filter(Trackers.tracker_id == request.user.id, Trackers.is_bookmark == ( request.matchdict.get('type') == 'bookmarked')) user_filter = get_filters(request) if query is not None else [] results = queryAll.filter(*user_filter).order_by(desc(Questions.created_at)). \ limit(page_size).offset(page * page_size) total = DBSession.query(func.count(Questions.id)).join(Trackers).filter( Trackers.tracker_id == request.user.id).filter(*user_filter). \ limit(page_size).offset(page * page_size).scalar() return results, total
def startup_wishcustomers(self, companies): cids = map(attrgetter('id'), self.startup_wishcustomers) cids_new = map(attrgetter('id'), companies) for company in self.startup_wishcustomers: if company.id not in cids_new: DBSession.query(CompanyXCompany).filter(CompanyXCompany.company == company, CompanyXCompany.by_company == self, CompanyXCompany.relation == TypeOfRelation.wishlistcustomer).delete() for company in companies: if company.id not in cids: self.related_companies.append( CompanyXCompany(company=company, by_company=self, relation=TypeOfRelation.wishlistcustomer))
def vote_to_answer(request): aid = request.POST.get('aid', -1) answer = DBSession.query(Answers).filter(Answers.id == aid).first() vote = DBSession.query(AnswerVotes).filter(AnswerVotes.answer_id == aid).filter( AnswerVotes.user_id == request.user.id).first() if vote is not None: DBSession.delete(vote) else: vote = AnswerVotes(answer=answer, user=request.user) DBSession.add(vote) vote_count = DBSession.query(func.count(AnswerVotes.id)).filter(AnswerVotes.answer_id == aid).scalar() return {'votes': vote_count}
def list_companies(self, page, page_size, query, request): filtr = [BaseCompany.name.ilike('%' + query + '%')] if not request.user or not request.user.is_admin: filtr.append(BaseCompany.activated == True) results = DBSession.query(BaseCompany.id, BaseCompany.name). \ filter(*filtr).limit(page_size).offset(page * page_size).all() total = DBSession.query(func.count(BaseCompany.id)). \ filter(*filtr).scalar() if self and page == total / page_size and len(query) > 2: nt = request.params.get('new_text') query = query.replace(nt or new_company_text, '') results.append((query, query + (nt or new_company_text))) return results, total
def render(request): conn = None existing_connection = request.params.get('conn_id') if existing_connection: conn = DBSession.query(Connection).get(int(existing_connection)) type = request.matchdict.get('type') if not type and conn and conn.user.primary_type: type = conn.user.primary_type if type == 'mentor' or type == 'faculty': by_user = conn.by_user if conn else request.user to = conn.user if conn else User.bid(request.matchdict.get('to_id')) if not existing_connection: conn_data = {'by_user_cust_name': by_user.nicename, 'by_user_cust_email': by_user.email, 'by_user_cust_linkedin': by_user.linkedin_profile, 'by_user_cust_co_name': by_user.company.name if by_user.company else '', 'by_user_cust_co_website': by_user.company.website if by_user.company else '', 'by_user_cust_co_desc': by_user.company.description if by_user.company else '', 'by_user_cust_co_teamdesc': by_user.company.startup_teamdescription if by_user.company else '', 'type': 'RM' } else: conn_data = {} conn = create_or_update_conn(by_user.id, existing_connection, to.id, **conn_data) message = conn.message if conn and conn.message else '' deleteonclose = 'connect/list' not in request.referrer return render_to_response('mentoring/request_meeting_modal.jinja2', {'to': to, 'from': by_user, 'conn': conn, 'deleteonclose': deleteonclose, 'message': message}, request) elif type == 'company': if conn: company = conn.company else: company = DBSession.query(BaseCompany).get(request.matchdict.get('to_id')) main_poc = find_poc(company, request) return render_to_response('company/connect_company_modal.jinja2', {'to': company, 'main_poc': main_poc[0], 'conn': conn, 'by_user': conn.by_user if conn else request.user, 'message': conn.message if conn else ''}, request) else: return render_to_response('connect_me/connect_me_modal.jinja2', {'to': conn.user if conn else User.bid(request.matchdict.get('to_id')), 'from': conn.by_user if conn else request.user, 'conn': conn, 'message': conn.message if conn else ''}, request)
def primary_type(self, val): current_prim = DBSession.query(RoleXUser).filter(RoleXUser.is_primary == True, RoleXUser.user_id == self.id).first() if current_prim and current_prim.role.title != val: current_prim.is_primary = False existing_role = DBSession.query(RoleXUser).join(Role).filter(Role.title == val, RoleXUser.user_id == self.id).first() if existing_role: existing_role.is_primary = True else: role = DBSession.query(Role).filter(Role.title == val).first() if role: role_x_user = RoleXUser(role=role, user=self, is_primary=True) Session.object_session(self).add(role_x_user)
def addto_track(request): qid = request.POST.get('qid', -1) question = DBSession.query(Questions).filter(Questions.id == qid).first() bookmark_ = (request.POST.get('type') == 'bookmark') existed = DBSession.query(Trackers).filter(Trackers.questions_id == qid).filter( Trackers.tracker_id == request.user.id, Trackers.is_bookmark == bookmark_).first() if existed: DBSession.delete(existed) return {'type': 'removed'} else: tracker = Trackers(tracker=request.user, question=question, is_bookmark=bookmark_) DBSession.add(tracker) return {'type': 'added'}
def item_view(request): try: uid = int(request.matchdict.get('id', 0)) except ValueError: uid = None if 'company' in request.path: if not uid and request.user: company = request.user.company return HTTPFound('/company/%s' % company.id) else: company = DBSession.query(BaseCompany).get(uid) # """ Used for the next, prev buttons on profiles - Portal v2 Adwairs time # NB! Not used actually bring up with Zach to discuss and see if worth salvaging these functions""" # if first_or_last_in_session(request) != -1: # update_session(request) return {'item': company, 'is_my_comp': request.user and request.user.company_id and request.user.company_id == company.id} user = User.load_all_roles(uid) # if first_or_last_in_session(request) != -1: # update_session(request) return {'item': user, 'user_types': user_types, 'is_my_comp': False}
def get_records(request, max_records, action_verb='export'): ids, excl_ids = get_ids(request) sess_query = request.session.get('query') filters = [BaseCompany.id.in_(ids)] if ids else where_from_query({'sessquery': sess_query}) if excl_ids: filters.append(BaseCompany.id.notin_(excl_ids)) if not request.user.is_admin: filters.append(BaseCompany.activated == True) if 'alchemist_startup' in request.referer: filters.append(BaseCompany.is_alchemist == True) filters.append(BaseCompany.companytype == 'startup') elif 'companies' not in request.referer: company_typestr = get_company_typestr(urlparse(request.referer).path[1:]) filters.append(BaseCompany.companytype == company_typestr) if not (ids or (request.session.get('select_all_comp') and sess_query is not None)): request.session.flash('We didn\'t find anything to %s' % action_verb, 'error') return False if len(ids) > max_records: request.session.flash('You cannot %s more than %s companies' % (action_verb, max_records), 'error') return False records = DBSession.query(BaseCompany).filter(*filters).limit(max_records + 1).all() if len(records) > max_records: request.session.flash('You cannot %s more than %s companies' % (action_verb, max_records), 'error') return False return records
def test_3login_flow(self): ver_code_of_last_user, last_uid = DBSession.query(User.ver_code, User.id).all()[-1] self.assert_(ver_code_of_last_user, 'Wrong order of tests') req = DummyRequest(path='linkedin_confirm/%s' % ver_code_of_last_user, matchdict={'code': ver_code_of_last_user}, user=self.founder) auth_uids = [] confirm_acc.remember = lambda x, y: auth_uids.append(y) ret = confirm_acc.linkedin_confirm_view(req) self.assert_(last_uid in auth_uids, 'User should be logged in') self.assert_(isinstance(ret, HTTPFound), 'Should redirect to linkedin') # now test the linkedin return but mock out all the linkedin credential checks req2 = Mock() req2.params = {'code': 'test'} req2.authenticated_userid = last_uid login.get_oauth_flow_linkedin = Mock() login.requests = Mock() linkedin_user_resp = Mock() linkedin_email = '*****@*****.**' linkedin_user_resp.json = {'id': 'dummyLinkedinID', 'emailAddress': linkedin_email} login.requests.get = lambda *x, **k: linkedin_user_resp login.check_csrf_token = Mock() # end of mocks self.assert_(self.get_linkedin_email_db(last_uid) != linkedin_email, 'Linkedin email should not be set yet') ret = login.oauthcallback_view(req2) # oauth callback view calls complete_confirm_acc self.assert_(isinstance(ret, HTTPFound), 'Should redirect to profile') self.assert_(self.get_linkedin_email_db(last_uid) == linkedin_email, 'Linkedin email should be set by complete_confirm_acc')
def get_records(request, max_records, action_verb='export'): ids, excl_ids = get_ids(request) sess_query = request.session.get('query_conn') filters = [User.id.in_(ids)] if ids else user_where_from_query({'query': sess_query}) if excl_ids: filters.append(User.id.notin_(excl_ids)) if not request.user.is_admin: filters.append(User.activated == True) type_from_mdict = urlparse(request.referer).path[1:] if type_from_mdict: user_type_str = get_user_typestr(type_from_mdict) if user_type_str: filters.append(User.roles.any(Role.title == user_type_str)) if not (ids or (request.session.get('select_all_conn') and sess_query is not None)): request.session.flash('We didn\'t find anything to %s' % action_verb, 'error') return False if len(ids) > max_records: request.session.flash('You cannot %s more than %s contact' % (action_verb, max_records), 'error') return False records = DBSession.query(User).outerjoin(User.companies_rel).filter(*filters).limit(max_records + 1).all() if len(records) > max_records: request.session.flash('You cannot %s more than %s contacts' % (action_verb, max_records), 'error') return False return records
def edit_company_view(request): company_id = request.matchdict.get('company_id') if company_id == 'no_company': return {'msg': 'You don\'t have a company'} company = DBSession.query(BaseCompany).get(company_id) assert company, 'No company' userid = request.authenticated_userid user = User.bid(userid) assert user.has_rights(['staff', 'admin', 'founder']) or ( user.primary_type == 'founder' and User.bid(userid).company_id == company_id), \ 'You don\'t have access to this company' if request.method != 'POST': return {'company': company} for i, v in request.POST.iteritems(): if i == 'checkboxes': i = v v = True if hasattr(company, i): v = handle_if_tags(i, v) v = handle_file_save(request.authenticated_userid, v) setattr(company, i, v) request.session.flash('Company info updated') if request.referer and '/company/' in request.referer: return HTTPFound(request.referer) return {'company': company}
def get_connect_stats(self): conns = DBSession.query(Connection).filter(Connection.by_user_id == self.id, Connection.sent_at != None).order_by(Connection.sent_at).all() connected = len([1 for c in conns if c.accepted]) sent = len(conns) meeting_reqs = [c for c in conns if c.type == 'RM' and not c.company_id] company_reqs = [c for c in conns if c.type == 'company' and not c.company_id] connect_me = [c for c in conns if c.type is None or c.type == 'CM'] f_accept = lambda x: x.accepted tracked_questions = self.tracked_questions return {'sent': sent, 'connected': connected, 'ratio': float(connected) / max(sent, 1), 'last': int(mktime(conns[0].sent_at.timetuple())) if conns else 0, 'connect_me_accept': len(filter(f_accept, connect_me)), 'connect_me_sent': len(connect_me), 'connect_me_conv': float(len(filter(f_accept, connect_me))) / max(len(connect_me), 1), 'request_meeting_accept': len(filter(f_accept, meeting_reqs)), 'request_meeting_sent': len(meeting_reqs), 'request_meeting_conv': float(len(filter(f_accept, meeting_reqs))) / max(len(meeting_reqs), 1), 'company_accept': len(filter(f_accept, company_reqs)), 'company_sent': len(company_reqs), 'company_conv': float(len(filter(f_accept, company_reqs))) / max(len(company_reqs), 1), 'questions_asked': len(self.questions_asked), 'answers_submitted': len(self.question_answers), 'questions_answered': len(set([qa.questions_id for qa in self.question_answers])), 'question_bookmarks': len(filter(lambda x: x.is_bookmark, tracked_questions)), 'question_alerts': len(filter(lambda x: not x.is_bookmark, tracked_questions)), 'answer_upvotes': len(self.answer_upvotes) }
def profile_view(request): auth_user = User.bid(request.authenticated_userid) userid = request.matchdict.get('user_id', auth_user.id) if auth_user.is_admin else auth_user.id current_type = request.matchdict.get('type', 'base') realtype = all_types[current_type] user = DBSession.query(realtype).get(userid) assert user, 'No user' if request.method == 'POST': post_data = request.POST password = post_data.get('password', '').strip() if password: assert password == post_data.get('password2', '').strip(), 'Passwords must match' assert hash_password(password) == user.password, 'The old password is incorrect' elif 'password' in post_data: del post_data['password'] for k, v in post_data.iteritems(): if hasattr(user, k) and k not in realtype.no_edit_fields: if v == 'on': v = True v = {'true': True, 'false': False}.get(v, v) v = handle_if_company(k, v) v = handle_file_save(user.id, v) v = handle_if_tags(k, v) setattr(user, k, v) if 'profile' in request.referer or 'useredit' in request.referer: for i in realtype.boolean_fields: if i not in post_data.iterkeys(): setattr(user, i, False) request.session.flash('Saved') user_url = '/%s/%s' % (getattr(user, 'type', 'company').split(',')[-1], user.id) return HTTPFound(request.referer or user_url)
def settings_view(request): settings_all = dict(DBSession.query(Settings.key, Settings).all()) if request.method == 'POST': for key, value in request.POST.iteritems(): if 'drive_id' in key: settings_all[key[:-9]].drive_id = value elif key in settings_all: settings_all[key].value = value Settings.set_docs_vals(settings_all) Settings._cache = {} get_region('main').invalidate() settings = {} settings['urls'], settings['general'], settings['drive_ids'] = [{} for x in range(3)] for k, v in settings_all.iteritems(): if 'http' in v.value: settings['urls'][k] = v.value if 'google' in v.value or v.drive_id: settings['drive_ids'][k] = v.drive_id or '' else: settings['general'][k] = v.value return { 'settings_general': settings['general'], 'settings_urls': settings['urls'], 'settings_drive_ids': settings['drive_ids'] }
def isvoted(self, uid): votes = DBSession.query(func.count(AnswerVotes.id)).filter(AnswerVotes.answer_id == self.id).filter( AnswerVotes.user_id == uid).scalar() if votes is None or votes == 0: return False else: return True
def inactivate_profile(request): if 'company' in request.referrer: cid = int(request.matchdict.get('id', 0)) company = DBSession.query(BaseCompany).filter(BaseCompany.id == cid).first() company.activated = False employees = company.employees for employee in employees: user = DBSession.query(User).filter(User._email == employee._email).first() user.activated = False employee.active = False return HTTPFound('/company/%s' % (cid)) else: uid = int(request.matchdict.get('id', 0)) user = User.bid(uid) user.activated = False return HTTPFound('/%s/%s' % (user.type.split(',')[-1], user.id))
def linkedin_confirm_view(request): code = request.matchdict.get('code') user = DBSession.query(User).filter(User.ver_code == code).first() if not user: return HTTPFound('/logout?no_redirect=1') remember(request, user.id) flow = get_oauth_flow_linkedin(request) return HTTPFound(flow.step1_get_authorize_url())
def unwanted_list(request): who = aliased(User, name="who") by = aliased(User, name="by") a = DBSession.query(UnWanted, who, by). \ join(who, UnWanted.user).join(by, UnWanted.by_user). \ all() a = obj_list_join(a, ['', 'user_', 'by_']) return {'unwanted': a}
def get_users_with_filters(*filters): general_filters = [User.login_enabled == True, User.roles_rel.any( and_(RoleXUser.role_name == RolesTypes.founder, RoleXUser.is_primary == True))] notif_filters = filters[0] if len(filters) > 1: notif_filters = or_(*filters) return DBSession.query(User).filter(*(general_filters + [notif_filters])).all()
def check_quota(user): count = DBSession.query(func.count(Connection.id)).filter(Connection.by_user == user, Connection.sent_at != None, or_(Connection.type == 'CM', Connection.type == None)).scalar() assert user.connect_me_quota >= count, \ 'Your connect me messages quota is full, use the help icon in bottom right corner or email [email protected]' return count
def send_emails_immediate_answer(request, answer_id, attr_name, nice_type, type): users_wanting_immediate_emails = get_users_with_filters( getattr(User, attr_name) == NotificationChoice.immediate) answer = DBSession.query(Answers).get(answer_id) question = answer.question for user in users_wanting_immediate_emails: user.send_mail('exchange_immediate', request, {'answer': answer, 'question': question, 'nice_type': nice_type, 'type': type})