def insert(cls, user_from_email, request): parent_key = ndb.Key(urlsafe=request.about) note_author = Userinfo() note_author.display_name = user_from_email.google_display_name note_author.photo = user_from_email.google_public_profile_photo_url note = Note(owner=user_from_email.google_user_id, organization=user_from_email.organization, author=note_author, title=request.title, content=request.content) entityKey_async = note.put_async() entityKey = entityKey_async.get_result() note.put_index() Edge.insert(start_node=parent_key, end_node=entityKey, kind='topics', inverse_edge='parents') author_shema = AuthorSchema( google_user_id=note.owner, display_name=note_author.display_name, google_public_profile_url=note_author.google_public_profile_url, photo=note_author.display_name, edgeKey="", email=note_author.email) note_schema = NoteSchema(id=str(note.key.id()), entityKey=note.key.urlsafe(), title=note.title, content=note.content, created_by=author_shema) return note_schema
def list_by_parent(cls, user_from_email, parent_key, request): case_list = [] you_can_loop = True count = 0 limit = int(request.cases.limit) case_next_curs = request.cases.pageToken while you_can_loop: edge_limit = int(request.cases.limit) - count if edge_limit > 0: case_edge_list = Edge.list(start_node=parent_key, kind='cases', limit=edge_limit, pageToken=case_next_curs) for edge in case_edge_list['items']: case = edge.end_node.get() if Node.check_permission(user_from_email, case): count += 1 tag_list = Tag.list_by_parent(parent_key=case.key) case_status_edges = Edge.list(start_node=case.key, kind='status', limit=1) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][ 0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'] [0].created_at.isoformat()) owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner. google_public_profile_photo_url, google_public_profile_url=owner. google_public_profile_url, google_user_id=owner.google_user_id) case_list.append( CaseSchema(id=str(case.key.id()), entityKey=case.key.urlsafe(), name=case.name, current_status=current_status_schema, priority=case.priority, tags=tag_list, owner=owner_schema, access=case.access, created_at=case.created_at.strftime( "%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime( "%Y-%m-%dT%H:%M:00.000"))) if case_edge_list['next_curs'] and case_edge_list['more']: case_next_curs = case_edge_list['next_curs'].urlsafe() else: you_can_loop = False case_next_curs = None
def update_status(cls, user_from_email, request): case_key = ndb.Key(urlsafe=request.entityKey) status_key = ndb.Key(urlsafe=request.status) # insert edges Edge.insert(start_node=case_key, end_node=status_key, kind='status', inverse_edge='related_cases')
def attach_files(cls, user_from_email, request): items = request.items author = Userinfo() author.google_user_id = user_from_email.google_user_id author.display_name = user_from_email.google_display_name author.photo = user_from_email.google_public_profile_photo_url if request.access: access = request.access else: access = 'public' items_attached = [] for item in items: document = cls( title=item.title, resource_id=item.id, mimeType=item.mimeType, embedLink=item.embedLink, owner=user_from_email.google_user_id, organization=user_from_email.organization, author=author, access=access, comments=0 ) document_key = document.put_async() document_key_async = document_key.get_result() if request.parent: parent_key = ndb.Key(urlsafe=request.parent) taskqueue.add( url='/workers/syncdocumentwithteam', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'doc_id': str(document_key_async.id()), 'parent_key_str': request.parent } ) # insert edges Edge.insert(start_node=parent_key, end_node=document_key_async, kind='documents', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=document_key_async, kind='documents', indexed_edge=str(parent_key.id()) ) else: data = {'id': document_key_async.id()} document.put_index(data) file_attached = iomessages.FileAttachedSchema( id=str(document_key_async.id()), name=item.title, embedLink=document.embedLink, ) items_attached.append(file_attached) return iomessages.FilesAttachedResponse(items=items_attached)
def filter_by_tag(cls, user_from_email, request): items = [] tag_keys = [] for tag_key_str in request.tags: tag_keys.append(ndb.Key(urlsafe=tag_key_str)) cases_keys = Edge.filter_by_set(tag_keys, 'tagged_on') cases = ndb.get_multi(cases_keys) for case in cases: if case is not None: is_filtered = True if request.owner and case.owner != request.owner and is_filtered: is_filtered = False if request.status and case.status != request.status and is_filtered: is_filtered = False if request.priority and case.priority != request.priority and is_filtered: is_filtered = False if is_filtered and Node.check_permission(user_from_email, case): # list of tags related to this case tag_list = Tag.list_by_parent(parent_key=case.key) case_status_edges = Edge.list( start_node=case.key, kind='status', limit=1 ) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'][0].created_at.isoformat() ) owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner.google_public_profile_photo_url, google_public_profile_url=owner.google_public_profile_url, google_user_id=owner.google_user_id ) case_schema = CaseSchema( id=str(case.key.id()), entityKey=case.key.urlsafe(), name=case.name, current_status=current_status_schema, priority=case.priority, owner=owner_schema, access=case.access, tags=tag_list, created_at=case.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) items.append(case_schema) return CaseListResponse(items=items)
def insert(cls, user_from_email, request): # prepare google drive service credentials = user_from_email.google_credentials http = httplib2.Http() service = build('drive', 'v2', http=http) credentials.authorize(http) # prepare params to insert params = { 'title': request.title, 'mimeType': request.mimeType } # execute files.insert and get resource_id created_document = service.files().insert(body=params).execute() author = Userinfo() author.google_user_id = user_from_email.google_user_id author.display_name = user_from_email.google_display_name author.photo = user_from_email.google_public_profile_photo_url document = cls( owner=user_from_email.google_user_id, organization=user_from_email.organization, access=request.access, title=request.title, mimeType=request.mimeType, resource_id=created_document['id'], embedLink=created_document['embedLink'], author=author ) document_key = document.put_async() document_key_async = document_key.get_result() if request.parent: parent_key = ndb.Key(urlsafe=request.parent) taskqueue.add( url='/workers/syncdocumentwithteam', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'doc_id': str(document_key_async.id()), 'parent_key_str': request.parent } ) # insert edges Edge.insert(start_node=parent_key, end_node=document_key_async, kind='documents', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=document_key_async, kind='documents', indexed_edge=str(parent_key.id()) ) else: data = {'id': document_key_async.id()} document.put_index(data) return DocumentSchema(id=str(document_key_async.id()), embedLink=document.embedLink)
def get_people_twitter(cls, entityKey): key = ndb.Key(urlsafe=entityKey) result = Edge.list(start_node=key, kind='twitter') if result['items']: profile_key = result['items'][0].end_node profile = profile_key.get() response = TwitterProfileSchema( id=profile.id, followers_count=profile.followers_count, last_tweet_text=profile.last_tweet_text, last_tweet_favorite_count=profile.last_tweet_favorite_count, last_tweet_retweeted=profile.last_tweet_retweeted, last_tweet_retweet_count=profile.last_tweet_retweet_count, language=profile.language, created_at=profile.created_at, nbr_tweets=profile.nbr_tweets, description_of_user=profile.description_of_user, friends_count=profile.friends_count, name=profile.name, screen_name=profile.screen_name, url_of_user_their_company=profile.url_of_user_their_company, location=profile.location, profile_image_url_https=profile.profile_image_url_https, lang=profile.lang, profile_banner_url=profile.profile_banner_url) return response
def list_by_parent(cls, parent_key, request): date_time_to_string = lambda x: x.strftime("%Y-%m-%dT%H:%M:00.000") if x else "" event_list = [] event_edge_list = Edge.list( start_node=parent_key, kind='events', limit=request.events.limit, pageToken=request.events.pageToken ) for edge in event_edge_list['items']: event = edge.end_node.get() event_schema = EventSchema( id=str(event.key.id()), entityKey=event.key.urlsafe(), title=event.title, starts_at=event.starts_at.isoformat(), ends_at=event.ends_at.isoformat(), where=event.where, created_at=event.created_at.isoformat(), updated_at=event.updated_at.isoformat() ) event_list.append(event_schema) if event_edge_list['next_curs'] and event_edge_list['more']: event_next_curs = event_edge_list['next_curs'].urlsafe() else: event_next_curs = None return EventListResponse( items=event_list, nextPageToken=event_next_curs )
def list_by_parent(cls, parent_key, request): date_time_to_string = lambda x: x.strftime("%Y-%m-%dT%H:%M:00.000") if x else "" task_list = [] task_edge_list = Edge.list( start_node=parent_key, kind='tasks', limit=request.tasks.limit, pageToken=request.tasks.pageToken ) for edge in task_edge_list['items']: task = edge.end_node.get() if task is not None: status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str(diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str(diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema( google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author.google_public_profile_url, photo=task.author.photo ) task_schema = TaskSchema( id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, created_by=author_schema, completed_by=AuthorSchema(), created_at=date_time_to_string(task.created_at), updated_at=date_time_to_string(task.updated_at) ) if task.due: task_schema.due = date_time_to_string(task.due) task_list.append(task_schema) if task_edge_list['next_curs'] and task_edge_list['more']: task_next_curs = task_edge_list['next_curs'].urlsafe() else: task_next_curs = None return TaskListResponse( items=task_list, nextPageToken=task_next_curs )
def list_by_parent(cls, parent_key, request): date_time_to_string = lambda x: x.strftime("%Y-%m-%dT%H:%M:00.000" ) if x else "" task_list = [] task_edge_list = Edge.list(start_node=parent_key, kind='tasks', limit=request.tasks.limit, pageToken=request.tasks.pageToken) for edge in task_edge_list['items']: task = edge.end_node.get() if task is not None: status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str( diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str(diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema( google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author. google_public_profile_url, photo=task.author.photo) task_schema = TaskSchema( id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, created_by=author_schema, completed_by=AuthorSchema(), created_at=date_time_to_string(task.created_at), updated_at=date_time_to_string(task.updated_at)) if task.due: task_schema.due = date_time_to_string(task.due) task_list.append(task_schema) if task_edge_list['next_curs'] and task_edge_list['more']: task_next_curs = task_edge_list['next_curs'].urlsafe() else: task_next_curs = None return TaskListResponse(items=task_list, nextPageToken=task_next_curs)
def list_by_parent(cls, parent_key, request=None): document_list = [] if request: document_edge_list = Edge.list( start_node=parent_key, kind='documents', limit=request.documents.limit, pageToken=request.documents.pageToken ) else: document_edge_list = Edge.list( start_node=parent_key, kind='documents' ) for edge in document_edge_list['items']: document = edge.end_node.get() tag_list = Tag.list_by_parent(parent_key=document.key) document_list.append( DocumentSchema( id=str(document.key.id()), entityKey=document.key.urlsafe(), title=document.title, resource_id=document.resource_id, alternateLink=document.alternateLink, thumbnailLink=document.thumbnailLink, embedLink=document.embedLink, mimeType=document.mimeType, access=document.access, tags=tag_list, created_at=document.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=document.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) ) if document_edge_list['next_curs'] and document_edge_list['more']: document_next_curs = document_edge_list['next_curs'].urlsafe() else: document_next_curs = None return DocumentListResponse( items=document_list, nextPageToken=document_next_curs )
def list_by_parent(cls, parent_key): """return the list of keywords related to an object""" edge_list = Edge.list(start_node=parent_key, kind='keywords') keyword_list = [] for edge in edge_list['items']: if edge.end_node.get() is not None: keyword_list.append( KeywordSchema(id=str(edge.end_node.id()), edgeKey=edge.key.urlsafe(), word=edge.end_node.get().word, color=edge.end_node.get().color)) return keyword_list
def list(cls, user_from_email, request): if request.tags: return cls.filter_by_tag(user_from_email, request) curs = Cursor(urlsafe=request.pageToken) if request.limit: limit = int(request.limit) else: limit = 1000 items = list() you_can_loop = True count = 0 while you_can_loop: if request.order: ascending = True if request.order.startswith('-'): order_by = request.order[1:] ascending = False else: order_by = request.order attr = cls._properties.get(order_by) if attr is None: raise AttributeError('Order attribute %s not defined.' % (attr_name, )) if ascending: cases, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(+attr).fetch_page( limit, start_cursor=curs) else: cases, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(-attr).fetch_page( limit, start_cursor=curs) else: cases, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).fetch_page(limit, start_cursor=curs) for case in cases: if len(items) < limit: is_filtered = True if request.tags and is_filtered: end_node_set = [ ndb.Key(urlsafe=tag_key) for tag_key in request.tags ] if not Edge.find(start_node=case.key, kind='tags', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.owner and case.owner != request.owner and is_filtered: is_filtered = False
def list_by_parent(cls, parent_key): """return the list of tags related to an object""" edge_list = Edge.list(start_node=parent_key, kind='tags') tag_list = [] for edge in edge_list['items']: if edge.end_node.get() is not None: tag_list.append( TagSchema(id=str(edge.end_node.id()), edgeKey=edge.key.urlsafe(), name=edge.end_node.get().name, color=edge.end_node.get().color)) return tag_list
def filter_by_tag(cls, user_from_email, request): items = [] tag_keys = [] for tag_key_str in request.tags: tag_keys.append(ndb.Key(urlsafe=tag_key_str)) cases_keys = Edge.filter_by_set(tag_keys, 'tagged_on') cases = ndb.get_multi(cases_keys) for case in cases: if case is not None: is_filtered = True if request.owner and case.owner != request.owner and is_filtered: is_filtered = False if request.status and case.status != request.status and is_filtered: is_filtered = False
def get_schema(cls, user_from_email, request): event = cls.get_by_id(int(request.id)) if event is None: raise endpoints.NotFoundException('Event not found.') tag_list = Tag.list_by_parent(parent_key=event.key) about = None edge_list = Edge.list(start_node=event.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': about_name = parent.firstname + ' ' + parent.lastname else: about_name = parent.name about = DiscussionAboutSchema( kind=about_kind, id=str(parent.key.id()), name=about_name ) author_schema = None if event.author: author_schema = AuthorSchema( google_user_id=event.author.google_user_id, email=user_from_email.email, display_name=event.author.display_name, google_public_profile_url=event.author.google_public_profile_url, photo=event.author.photo) event_schema = EventSchema( id=str(event.key.id()), entityKey=event.key.urlsafe(), title=event.title, starts_at=event.starts_at.isoformat(), ends_at=event.ends_at.isoformat(), where=event.where, description=event.description, about=about, created_by=author_schema, tags=tag_list, created_at=event.created_at.isoformat(), updated_at=event.updated_at.isoformat(), access=event.access, allday=event.allday, timezone=event.timezone ) return event_schema
def get_schema(cls, user_from_email, request): document = cls.get_by_id(int(request.id)) if document is None: raise endpoints.NotFoundException('Document not found.') tag_list = Tag.list_by_parent(parent_key=document.key) about = None edge_list = Edge.list(start_node=document.key, kind='parents') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': about_name = parent.firstname + ' ' + parent.lastname elif about_kind == 'Task' or about_kind == 'Event': about_name = parent.title else: about_name = parent.name about = DiscussionAboutSchema( kind=about_kind, id=str(parent.key.id()), name=about_name ) author_schema = None if document.author: author_schema = AuthorSchema( google_user_id=document.author.google_user_id, display_name=document.author.display_name, google_public_profile_url=document.author.google_public_profile_url, photo=document.author.photo) document_schema = DocumentSchema( id=str(document.key.id()), entityKey=document.key.urlsafe(), title=document.title, resource_id=document.resource_id, alternateLink=document.alternateLink, thumbnailLink=document.thumbnailLink, embedLink=document.embedLink, mimeType=document.mimeType, access=document.access, tags=tag_list, about=about, created_by=author_schema, created_at=document.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=document.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) return document_schema
def list_by_parent(cls, parent_key): """return the list of tags related to an object""" edge_list = Edge.list( start_node=parent_key, kind='tags' ) tag_list = [] for edge in edge_list['items']: if edge.end_node.get() is not None: tag_list.append( TagSchema( id=str(edge.end_node.id()), edgeKey=edge.key.urlsafe(), name=edge.end_node.get().name, color=edge.end_node.get().color ) ) return tag_list
def list_by_parent(cls, parent_key): """return the list of keywords related to an object""" edge_list = Edge.list( start_node=parent_key, kind='keywords' ) keyword_list = [] for edge in edge_list['items']: if edge.end_node.get() is not None: keyword_list.append( KeywordSchema( id=str(edge.end_node.id()), edgeKey=edge.key.urlsafe(), word=edge.end_node.get().word, color=edge.end_node.get().color ) ) return keyword_list
def attach_keyword(cls, user_from_email, request): start_node = ndb.Key(urlsafe=request.parent) end_node = ndb.Key(urlsafe=request.keyword_key) edge_key = Edge.insert(start_node=start_node, end_node=end_node, kind='keywords', inverse_edge='keywordged_on') edge = edge_key.get() if end_node.get().locality != 'Blog': EndpointsHelper.update_edge_indexes(parent_key=start_node, kind='keywords', indexed_edge=str( end_node.id())) return KeywordSchema(edgeKey=edge.key.urlsafe(), id=str(edge.end_node.id()), entityKey=edge.end_node.urlsafe(), word=edge.end_node.get().word, color=edge.end_node.get().color)
def attach_tag(cls, user_from_email, request): start_node = ndb.Key(urlsafe=request.parent) end_node = ndb.Key(urlsafe=request.tag_key) edge_key = Edge.insert(start_node=start_node, end_node=end_node, kind='tags', inverse_edge='tagged_on') edge = edge_key.get() if end_node.get().about_kind != 'Blog': EndpointsHelper.update_edge_indexes(parent_key=start_node, kind='tags', indexed_edge=str( end_node.id())) return TagSchema(edgeKey=edge.key.urlsafe(), id=str(edge.end_node.id()), entityKey=edge.end_node.urlsafe(), name=edge.end_node.get().name, color=edge.end_node.get().color)
def get_schema(cls, user_from_email, request): note = cls.get_by_id(int(request.id)) if note is None: raise endpoints.NotFoundException('Note not found.') author = AuthorSchema( google_user_id=note.author.google_user_id, display_name=note.author.display_name, google_public_profile_url=note.author.google_public_profile_url, photo=note.author.photo) about = None edge_list = Edge.list(start_node=note.key, kind='parents') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': if parent.lastname and parent.firstname: about_name = parent.firstname + ' ' + parent.lastname else: if parent.lastname: about_name = parent.lastname else: if parent.firstname: about_name = parent.firstname else: about_name = parent.name about = DiscussionAboutSchema(kind=about_kind, id=str(parent.key.id()), name=about_name) note_schema = NoteSchema( id=str(note.key.id()), entityKey=note.key.urlsafe(), title=note.title, content=note.content, about=about, created_by=author, created_at=note.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=note.updated_at.strftime("%Y-%m-%dT%H:%M:00.000")) return note_schema
def get_people(cls, entityKey): key = ndb.Key(urlsafe=entityKey) result = Edge.list(start_node=key, kind='linkedin') if result['items']: profile_key = result['items'][0].end_node pro = profile_key.get() response = LinkedinProfileSchema(lastname=pro.lastname, firstname=pro.firstname, industry=pro.industry, locality=pro.locality, headline=pro.headline, current_post=pro.current_post, past_post=pro.past_post, formations=pro.formations, websites=pro.websites, relation=pro.relation, experiences=pro.experiences, resume=pro.resume, certifications=pro.certifications, skills=pro.skills, url=pro.url) return response
def attach_tag(cls, user_from_email, request): start_node = ndb.Key(urlsafe=request.parent) end_node = ndb.Key(urlsafe=request.tag_key) edge_key = Edge.insert( start_node=start_node, end_node=end_node, kind='tags', inverse_edge='tagged_on' ) edge = edge_key.get() if end_node.get().about_kind != 'Blog': EndpointsHelper.update_edge_indexes( parent_key=start_node, kind='tags', indexed_edge=str(end_node.id()) ) return TagSchema( edgeKey=edge.key.urlsafe(), id=str(edge.end_node.id()), entityKey=edge.end_node.urlsafe(), name=edge.end_node.get().name, color=edge.end_node.get().color )
def attach_keyword(cls, user_from_email, request): start_node = ndb.Key(urlsafe=request.parent) end_node = ndb.Key(urlsafe=request.keyword_key) edge_key = Edge.insert( start_node=start_node, end_node=end_node, kind='keywords', inverse_edge='keywordged_on' ) edge = edge_key.get() if end_node.get().locality != 'Blog': EndpointsHelper.update_edge_indexes( parent_key=start_node, kind='keywords', indexed_edge=str(end_node.id()) ) return KeywordSchema( edgeKey=edge.key.urlsafe(), id=str(edge.end_node.id()), entityKey=edge.end_node.urlsafe(), word=edge.end_node.get().word, color=edge.end_node.get().color )
def insert(cls, user_from_email, request): if request.status: status = request.status else: status = 'open' if request.access: access = request.access else: access = 'public' author = Userinfo() author.google_user_id = user_from_email.google_user_id author.display_name = user_from_email.google_display_name author.photo = user_from_email.google_public_profile_photo_url task = Task(title=request.title, status=status, owner=user_from_email.google_user_id, organization=user_from_email.organization, access=access, author=author) if request.due: task.due = datetime.datetime.strptime(request.due, "%Y-%m-%dT%H:%M:00.000000") task_key = task.put_async() if request.due: taskqueue.add(url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': request.title, 'task_id': task_key.get_result().id() }) if request.reminder: pass task_key_async = task_key.get_result() if request.parent: # insert edges parent_key = ndb.Key(urlsafe=request.parent) Edge.insert(start_node=parent_key, end_node=task_key_async, kind='tasks', inverse_edge='related_to') EndpointsHelper.update_edge_indexes(parent_key=task_key_async, kind='tasks', indexed_edge=str( parent_key.id())) else: data = {'id': task_key_async.id()} task.put_index(data) if request.assignees: # insert edges for assignee in request.assignees: assignee_key = ndb.Key(urlsafe=assignee.entityKey) assignee_user = assignee_key.get() assignee_email = assignee_user.email # add a task queue to send notification email to assignee body = '<p>view details on ioGrow: <a href="http://app.iogrow.com/#/tasks/show/' + str( task_key_async.id()) + '">' body += request.title body += '</a></p>' taskqueue.add(url='/workers/send_email_notification', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'to': assignee_email, 'subject': '[task]: ' + request.title, 'body': body }) Edge.insert(start_node=task_key_async, end_node=assignee_key, kind='assignees', inverse_edge='assigned_to') if request.tags: # insert edges for tag in request.tags: Edge.insert(start_node=task_key_async, end_node=ndb.Key(urlsafe=tag.entityKey), kind='tags', inverse_edge='tagged_on') task_schema = TaskSchema(id=str(task_key_async.id()), entityKey=task_key_async.urlsafe(), title=task.title, status=task.status, access=task.access) if task.due: task_schema.due = task.due.isoformat() return task_schema
def get_schema(cls, user_from_email, request): case = cls.get_by_id(int(request.id)) if case is None: raise endpoints.NotFoundException('Opportunity not found.') if Node.check_permission(user_from_email, case): parents_edge_list = Edge.list( start_node=case.key, kind='parents' ) account_schema = None contact_schema = None for parent in parents_edge_list['items']: if parent.end_node.kind() == 'Account': account = parent.end_node.get() infonodes = Node.list_info_nodes(account.key, request) info_nodes_structured = Node.to_structured_data(infonodes) emails = EmailListSchema() if 'emails' in info_nodes_structured.keys(): emails = info_nodes_structured['emails'] addresses = AddressListSchema() if 'addresses' in info_nodes_structured.keys(): addresses = info_nodes_structured['addresses'] phones = PhoneListSchema() if 'phones' in info_nodes_structured.keys(): phones = info_nodes_structured['phones'] social_links = SocialLinkListSchema() if 'sociallinks' in info_nodes_structured.keys(): social_links = info_nodes_structured['sociallinks'] websites = [] if 'websites' in info_nodes_structured.keys(): sites = info_nodes_structured['websites'] for site in sites: websites.append(site['url']) account_schema = AccountSchema( id=str(account.key.id()), entityKey=account.key.urlsafe(), name=account.name, account_type=account.account_type, industry=account.industry, tagline=account.tagline, introduction=account.introduction, access=account.access, folder=account.folder, logo_img_id=account.logo_img_id, logo_img_url=account.logo_img_url, firstname=account.firstname, lastname=account.lastname, personal_account=account.personal_account, emails=emails, addresses=addresses, phones=phones, websites=websites, sociallinks=social_links ) elif parent.end_node.kind() == 'Contact': contact = parent.end_node.get() infonodes = Node.list_info_nodes(contact.key, request) info_nodes_structured = Node.to_structured_data(infonodes) emails = EmailListSchema() if 'emails' in info_nodes_structured.keys(): emails = info_nodes_structured['emails'] addresses = AddressListSchema() if 'addresses' in info_nodes_structured.keys(): addresses = info_nodes_structured['addresses'] phones = PhoneListSchema() if 'phones' in info_nodes_structured.keys(): phones = info_nodes_structured['phones'] social_links = SocialLinkListSchema() if 'sociallinks' in info_nodes_structured.keys(): social_links = info_nodes_structured['sociallinks'] websites = [] if 'websites' in info_nodes_structured.keys(): sites = info_nodes_structured['websites'] for site in sites: websites.append(site['url']) contact_schema = iomessages.ContactSchema( id=str(contact.key.id()), entityKey=contact.key.urlsafe(), firstname=contact.firstname, lastname=contact.lastname, title=contact.title, profile_img_id=contact.profile_img_id, profile_img_url=contact.profile_img_url, emails=emails, addresses=addresses, phones=phones, websites=websites, sociallinks=social_links, ) tag_list = Tag.list_by_parent(parent_key=case.key) # list of infonodes infonodes = Node.list_info_nodes( parent_key=case.key, request=request ) # list of topics related to this account topics = None if request.topics: topics = Note.list_by_parent( parent_key=case.key, request=request ) tasks = None if request.tasks: tasks = Task.list_by_parent( parent_key=case.key, request=request ) events = None if request.events: events = Event.list_by_parent( parent_key=case.key, request=request ) documents = None if request.documents: documents = Document.list_by_parent( parent_key=case.key, request=request ) case_status_edges = Edge.list( start_node=case.key, kind='status', limit=1 ) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'][0].created_at.isoformat() ) closed_date = None if case.closed_date: closed_date = case.closed_date.strftime("%Y-%m-%dT%H:%M:00.000") owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner.google_public_profile_photo_url, google_public_profile_url=owner.google_public_profile_url, google_user_id=owner.google_user_id ) case_schema = CaseSchema( id=str(case.key.id()), entityKey=case.key.urlsafe(), name=case.name, folder=case.folder, current_status=current_status_schema, priority=case.priority, tags=tag_list, topics=topics, tasks=tasks, events=events, documents=documents, infonodes=infonodes, access=case.access, description=case.description, case_origin=case.case_origin, closed_date=closed_date, type_case=case.type_case, account=account_schema, contact=contact_schema, created_at=case.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime("%Y-%m-%dT%H:%M:00.000"), owner=owner_schema ) return case_schema else: raise endpoints.NotFoundException('Permission denied')
def patch(cls, user_from_email, request): task = cls.get_by_id(int(request.id)) task_id = int(request.id) edges = Edge.query().filter(Edge.kind == "assignees", Edge.start_node == task.key) if task is None: raise endpoints.NotFoundException('Task not found.') if (task.owner != user_from_email.google_user_id) and not user_from_email.is_admin: raise endpoints.ForbiddenException('you are not the owner') if request.title: task.title = request.title if request.access: task.access = request.access if request.status: task.status = request.status if task.status == 'closed': task.completed_by = user_from_email.google_user_id body = '<p>#closed, view details on ioGrow: <a href="http://app.iogrow.com/#/tasks/show/' + str( task.key.id()) + '">' body += task.title body += '</a></p>' created_by = model.User.get_by_gid(task.owner) to = None if created_by: to = created_by.email edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() cc = None for edge in edge_list['items']: assignee_list.append(edge.end_node.get().email) cc = ",".join(assignee_list) taskqueue.add( url='/workers/send_email_notification', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'to': to, 'cc': cc, 'subject': '[task]: ' + task.title, 'body': body } ) if request.due and task.due is None: task.due = datetime.datetime.strptime(request.due, "%Y-%m-%dT%H:%M:00.000000") if edges: for edge in edges: assigned_to = edge.end_node.get() taskqueue.add( url='/workers/syncassignedtask', queue_name='iogrow-low-task', params={ 'email': assigned_to.email, 'task_key': task_id, 'assigned_to': edge.end_node.get() } ) taskqueue.add( url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_id': task_id } ) else: taskqueue.add( url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_id': task_id } ) elif request.due and task.due is not None: task.due = datetime.datetime.strptime(request.due, "%Y-%m-%dT%H:%M:00.000000") if edges: for edge in edges: assigned_to = edge.end_node.get() taskqueue.add( url='/workers/syncassignedpatchtask', queue_name='iogrow-low-task', params={ 'email': assigned_to.email, 'task_key': task_id, 'assigned_to': edge.end_node.get() } ) taskqueue.add( url='/workers/syncpatchtask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_google_id': task.task_google_id } ) else: taskqueue.add( url='/workers/syncpatchtask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_google_id': task.task_google_id } ) task_key = task.put_async() task_key_async = task_key.get_result() EndpointsHelper.update_edge_indexes( parent_key=task_key_async, kind=None, indexed_edge=None ) return cls.get_schema( user_from_email=user_from_email, request=request )
def get_schema(cls, user_from_email, request): task = cls.get_by_id(int(request.id)) if task is None: raise endpoints.NotFoundException('Task not found.') tag_list = Tag.list_by_parent(parent_key=task.key) about = None edge_list = Edge.list(start_node=task.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': if parent.lastname and parent.firstname : about_name = parent.firstname + ' ' + parent.lastname else: if parent.lastname: about_name = parent.lastname else : if parent.firstname: about_name = parent.firstname else: about_name = parent.name about = DiscussionAboutSchema( kind=about_kind, id=str(parent.key.id()), name=about_name ) # list of tags related to this task edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() for edge in edge_list['items']: assignee_list.append(AuthorSchema(edgeKey=edge.key.urlsafe(), google_user_id=edge.end_node.get().google_user_id, display_name=edge.end_node.get().google_display_name, google_public_profile_url=edge.end_node.get().google_public_profile_url, photo=edge.end_node.get().google_public_profile_photo_url )) status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str(diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str(diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema( google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author.google_public_profile_url, photo=task.author.photo) due_date = None if task.due: due_date = task.due.strftime('%Y-%m-%d') task_schema = TaskSchema( id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, due=due_date, comments=0, about=about, created_by=author_schema, completed_by=AuthorSchema(), tags=tag_list, assignees=assignee_list, access=task.access, created_at=task.created_at.isoformat(), updated_at=task.updated_at.isoformat() ) return task_schema
def list_by_parent(cls, parent_key, request): topic_list = [] topic_edge_list = Edge.list(start_node=parent_key, kind='topics', limit=request.topics.limit, pageToken=request.topics.pageToken) for edge in topic_edge_list['items']: end_node = edge.end_node.get() try: excerpt = end_node.content[0:100] except: excerpt = '' last_updater = end_node.author if edge.end_node.kind() == 'Note': if end_node.comments == 0: last_updater = end_node.author excerpt = None if end_node.content: excerpt = end_node.content[0:100] else: # get the last comment comments_edge_list = Edge.list(start_node=end_node.key, kind='comments', limit=1) if len(comments_edge_list['items']) > 0: last_comment = comments_edge_list['items'][ 0].end_node.get() last_updater = last_comment.author excerpt = None if last_comment.content: excerpt = end_node.content[0:100] else: # get the last comment comments_edge_list = Edge.list(start_node=end_node.key, kind='comments', limit=1) if len(comments_edge_list['items']) > 0: last_comment = comments_edge_list['items'][0].end_node.get( ) last_updater = last_comment.author excerpt = None if last_comment.content: excerpt = end_node.content[0:100] author = AuthorSchema(google_user_id=last_updater.google_user_id, display_name=last_updater.display_name, google_public_profile_url=last_updater. google_public_profile_url, photo=last_updater.photo) topic_list.append( TopicSchema(id=str(end_node.key.id()), last_updater=author, title=edge.end_node.get().title, excerpt=excerpt, topic_kind=end_node.key.kind(), updated_at=end_node.updated_at.strftime( "%Y-%m-%dT%H:%M:00.000"))) if topic_edge_list['next_curs'] and topic_edge_list['more']: topic_next_curs = topic_edge_list['next_curs'].urlsafe() else: topic_next_curs = None return TopicListResponse(items=topic_list, nextPageToken=topic_next_curs)
class Case(EndpointsModel): _message_fields_schema = ('id', 'entityKey', 'owner', 'folder', 'access', 'collaborators_list', 'collaborators_ids', 'name', 'status', 'type_case', 'priority', 'account', 'account_name', 'contact', 'contact_name', 'created_at', 'updated_at', 'type_case', 'description', 'case_origin', 'closed_date') # Sharing fields owner = ndb.StringProperty() collaborators_list = ndb.StructuredProperty(model.Userinfo, repeated=True) collaborators_ids = ndb.StringProperty(repeated=True) organization = ndb.KeyProperty() folder = ndb.StringProperty() account = ndb.KeyProperty() account_name = ndb.StringProperty() contact = ndb.KeyProperty() contact_name = ndb.StringProperty() name = ndb.StringProperty() status = ndb.StringProperty() type_case = ndb.StringProperty() industry = ndb.StringProperty() priority = ndb.IntegerProperty() created_at = ndb.DateTimeProperty(auto_now_add=True) updated_at = ndb.DateTimeProperty(auto_now=True) created_by = ndb.KeyProperty() description = ndb.StringProperty() case_origin = ndb.StringProperty() closed_date = ndb.DateTimeProperty() # public or private access = ndb.StringProperty() def put(self, **kwargs): ndb.Model.put(self, **kwargs) try: self.put_index() except: print 'error on saving document index' def set_perm(self): about_item = str(self.key.id()) perm = model.Permission(about_kind='Case', about_item=about_item, type='user', role='owner', value=self.owner) perm.put() def put_index(self, data=None): """ index the element at each""" empty_string = lambda x: x if x else "" collaborators = " ".join(self.collaborators_ids) organization = str(self.organization.id()) title_autocomplete = ','.join( tokenize_autocomplete(self.name + ' ' + empty_string(self.account_name) + ' ' + empty_string(self.contact_name))) if data: search_key = ['infos', 'cases', 'tags', 'collaborators'] for key in search_key: if key not in data.keys(): data[key] = "" my_document = search.Document( doc_id=str(data['id']), fields=[ search.TextField(name=u'type', value=u'Case'), search.TextField(name='organization', value=empty_string(organization)), search.TextField(name='access', value=empty_string(self.access)), search.TextField(name='owner', value=empty_string(self.owner)), search.TextField(name='collaborators', value=data['collaborators']), search.TextField(name='title', value=empty_string(self.name)), search.TextField(name='account_name', value=empty_string(self.account_name)), search.TextField(name='contact_name', value=empty_string(self.contact_name)), search.TextField(name='status', value=empty_string(self.status)), search.NumberField(name='priority', value=int(self.priority or 1)), search.DateField(name='created_at', value=self.created_at), search.DateField(name='updated_at', value=self.updated_at), search.TextField(name='infos', value=data['infos']), search.TextField(name='tags', value=data['tags']), search.TextField(name='cases', value=data['cases']), search.TextField(name='title_autocomplete', value=empty_string(title_autocomplete)), search.TextField(name='type_case', value=empty_string(self.type_case)) ]) else: my_document = search.Document( doc_id=str(self.key.id()), fields=[ search.TextField(name=u'type', value=u'Case'), search.TextField(name='organization', value=empty_string(organization)), search.TextField(name='access', value=empty_string(self.access)), search.TextField(name='owner', value=empty_string(self.owner)), search.TextField(name='collaborators', value=collaborators), search.TextField(name='title', value=empty_string(self.name)), search.TextField(name='account_name', value=empty_string(self.account_name)), search.TextField(name='contact_name', value=empty_string(self.contact_name)), search.TextField(name='status', value=empty_string(self.status)), search.NumberField(name='priority', value=int(self.priority)), search.DateField(name='created_at', value=self.created_at), search.DateField(name='updated_at', value=self.updated_at), search.TextField(name='title_autocomplete', value=empty_string(title_autocomplete)), search.TextField(name='type_case', value=empty_string(self.type_case)) ]) my_index = search.Index(name="GlobalIndex") my_index.put(my_document) @classmethod def get_schema(cls, user_from_email, request): case = cls.get_by_id(int(request.id)) if case is None: raise endpoints.NotFoundException('Opportunity not found.') if Node.check_permission(user_from_email, case): parents_edge_list = Edge.list(start_node=case.key, kind='parents') account_schema = None contact_schema = None for parent in parents_edge_list['items']: if parent.end_node.kind() == 'Account': account = parent.end_node.get() infonodes = Node.list_info_nodes(account.key, request) info_nodes_structured = Node.to_structured_data(infonodes) emails = EmailListSchema() if 'emails' in info_nodes_structured.keys(): emails = info_nodes_structured['emails'] addresses = AddressListSchema() if 'addresses' in info_nodes_structured.keys(): addresses = info_nodes_structured['addresses'] phones = PhoneListSchema() if 'phones' in info_nodes_structured.keys(): phones = info_nodes_structured['phones'] social_links = SocialLinkListSchema() if 'sociallinks' in info_nodes_structured.keys(): social_links = info_nodes_structured['sociallinks'] websites = [] if 'websites' in info_nodes_structured.keys(): sites = info_nodes_structured['websites'] for site in sites: websites.append(site['url']) account_schema = AccountSchema( id=str(account.key.id()), entityKey=account.key.urlsafe(), name=account.name, account_type=account.account_type, industry=account.industry, tagline=account.tagline, introduction=account.introduction, access=account.access, folder=account.folder, logo_img_id=account.logo_img_id, logo_img_url=account.logo_img_url, firstname=account.firstname, lastname=account.lastname, personal_account=account.personal_account, emails=emails, addresses=addresses, phones=phones, websites=websites, sociallinks=social_links) elif parent.end_node.kind() == 'Contact': contact = parent.end_node.get() infonodes = Node.list_info_nodes(contact.key, request) info_nodes_structured = Node.to_structured_data(infonodes) emails = EmailListSchema() if 'emails' in info_nodes_structured.keys(): emails = info_nodes_structured['emails'] addresses = AddressListSchema() if 'addresses' in info_nodes_structured.keys(): addresses = info_nodes_structured['addresses'] phones = PhoneListSchema() if 'phones' in info_nodes_structured.keys(): phones = info_nodes_structured['phones'] social_links = SocialLinkListSchema() if 'sociallinks' in info_nodes_structured.keys(): social_links = info_nodes_structured['sociallinks'] websites = [] if 'websites' in info_nodes_structured.keys(): sites = info_nodes_structured['websites'] for site in sites: websites.append(site['url']) contact_schema = iomessages.ContactSchema( id=str(contact.key.id()), entityKey=contact.key.urlsafe(), firstname=contact.firstname, lastname=contact.lastname, title=contact.title, profile_img_id=contact.profile_img_id, profile_img_url=contact.profile_img_url, emails=emails, addresses=addresses, phones=phones, websites=websites, sociallinks=social_links, ) tag_list = Tag.list_by_parent(parent_key=case.key) # list of infonodes infonodes = Node.list_info_nodes(parent_key=case.key, request=request) # list of topics related to this account topics = None if request.topics: topics = Note.list_by_parent(parent_key=case.key, request=request) tasks = None if request.tasks: tasks = Task.list_by_parent(parent_key=case.key, request=request) events = None if request.events: events = Event.list_by_parent(parent_key=case.key, request=request) documents = None if request.documents: documents = Document.list_by_parent(parent_key=case.key, request=request) case_status_edges = Edge.list(start_node=case.key, kind='status', limit=1) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'] [0].created_at.isoformat()) closed_date = None if case.closed_date: closed_date = case.closed_date.strftime( "%Y-%m-%dT%H:%M:00.000") owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner. google_public_profile_photo_url, google_public_profile_url=owner.google_public_profile_url, google_user_id=owner.google_user_id) case_schema = CaseSchema( id=str(case.key.id()), entityKey=case.key.urlsafe(), name=case.name, folder=case.folder, current_status=current_status_schema, priority=case.priority, tags=tag_list, topics=topics, tasks=tasks, events=events, documents=documents, infonodes=infonodes, access=case.access, description=case.description, case_origin=case.case_origin, closed_date=closed_date, type_case=case.type_case, account=account_schema, contact=contact_schema, created_at=case.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime("%Y-%m-%dT%H:%M:00.000"), owner=owner_schema) return case_schema
cases_keys = Edge.filter_by_set(tag_keys, 'tagged_on') cases = ndb.get_multi(cases_keys) for case in cases: if case is not None: is_filtered = True if request.owner and case.owner != request.owner and is_filtered: is_filtered = False if request.status and case.status != request.status and is_filtered: is_filtered = False if request.priority and case.priority != request.priority and is_filtered: is_filtered = False if is_filtered and Node.check_permission( user_from_email, case): # list of tags related to this case tag_list = Tag.list_by_parent(parent_key=case.key) case_status_edges = Edge.list(start_node=case.key, kind='status', limit=1) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][ 0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'] [0].created_at.isoformat()) owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id),
def list_by_parent(cls, user_from_email, parent_key, request): pipeline_list = [] you_can_loop = True count = 0 limit = int(request.pipelines.limit) pipeline_next_curs = request.pipelines.pageToken while you_can_loop: edge_limit = int(request.pipelines.limit) - count if edge_limit > 0: pipeline_edge_list = Edge.list( start_node=parent_key, kind='pipelines', limit=edge_limit, pageToken=pipeline_next_curs ) for edge in pipeline_edge_list['items']: pipeline = edge.end_node.get() if Node.check_permission(user_from_email, pipeline): count += 1 tag_list = Tag.list_by_parent(parent_key=pipeline.key) pipeline_status_edges = Edge.list( start_node=pipeline.key, kind='status', limit=1 ) current_status_schema = None if len(pipeline_status_edges['items']) > 0: current_status = pipeline_status_edges['items'][0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=pipeline_status_edges['items'][0].created_at.isoformat() ) owner = model.User.get_by_gid(pipeline.owner) owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner.google_public_profile_photo_url, google_public_profile_url=owner.google_public_profile_url, google_user_id=owner.google_user_id ) pipeline_list.append( CaseSchema( id=str(pipeline.key.id()), entityKey=pipeline.key.urlsafe(), name=pipeline.name, current_status=current_status_schema, priority=pipeline.priority, tags=tag_list, owner=owner_schema, access=pipeline.access, created_at=pipeline.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=pipeline.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) ) if pipeline_edge_list['next_curs'] and pipeline_edge_list['more']: pipeline_next_curs = pipeline_edge_list['next_curs'].urlsafe() else: you_can_loop = False pipeline_next_curs = None if count == limit: you_can_loop = False return CaseListResponse( items=pipeline_list, nextPageToken=pipeline_next_curs )
def receive(self, mail_message): sender_id = mail_message.to.split("@")[0] try: bcc = mail_message.bcc.split("@")[0] except: bcc = 'undefined' user_id = 'undefined' if sender_id.isdigit(): user_id = sender_id if bcc.isdigit(): user_id = bcc user = User.get_by_gid(user_id) if user: sender_email = re.findall(r'[\w\.-]+@[\w\.-]+', mail_message.sender) if user.email == sender_email[0]: print 'authorized' html_bodies = mail_message.bodies('text/html') email_body = '' additional_emails = ' ' for content_type, body in html_bodies: decoded_html = smart_str(body.decode()) email_body += decoded_html additional_emails += ' ' + smart_str(mail_message.to) try: additional_emails += ' ' + smart_str(mail_message.bcc) except: pass try: additional_emails += ' ' + smart_str(mail_message.cc) except: pass re_emails = re.findall(r'[\w\.-]+@[\w\.-]+', email_body + additional_emails) emails = list(set(re_emails)) print 'emails' print emails for email in emails: generic_prop = ndb.GenericProperty() generic_prop._name = 'email' nodes = Node.query(generic_prop == email).fetch() if len(nodes) > 0: for node in nodes: parents_edge_list = Edge.list(start_node=node.key, kind='parents') for edge in parents_edge_list['items']: parent_key = edge.end_node # insert a note related to the parent node note_author = Userinfo() note_author.display_name = user.google_display_name note_author.photo = user.google_public_profile_photo_url note = Note(owner=user.google_user_id, organization=user.organization, author=note_author, title=mail_message.subject, content=email_body) entityKey_async = note.put_async() entityKey = entityKey_async.get_result() Edge.insert(start_node=parent_key, end_node=entityKey, kind='topics', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=entityKey, kind='topics', indexed_edge=str(parent_key.id())) else: pass # We should create a lead related to this email # and attach this email with this lead else: print 'not authorized' else: print 'user doesnt exist'
def insert(cls, user_from_email, request): author = Userinfo() author.google_user_id = user_from_email.google_user_id author.display_name = user_from_email.google_display_name author.photo = user_from_email.google_public_profile_photo_url event = cls( owner=user_from_email.google_user_id, organization=user_from_email.organization, access=request.access, title=request.title, starts_at=datetime.datetime.strptime(request.starts_at, "%Y-%m-%dT%H:%M:00.000000"), ends_at=datetime.datetime.strptime(request.ends_at, "%Y-%m-%dT%H:%M:00.000000"), where=request.where, description=request.description, author=author, allday=request.allday, timezone=request.timezone ) event_key = event.put_async() attendees = [] if request.invites: attendees = request.invites taskqueue.add( url='/workers/syncevent', queue_name='iogrow-low-event', params={ 'email': user_from_email.email, 'starts_at': request.starts_at, 'ends_at': request.ends_at, 'summary': request.title, 'event_id': event_key.get_result().id(), 'attendees': attendees, 'guest_modify': request.guest_modify, 'guest_invite': request.guest_invite, 'guest_list': request.guest_list, 'description': request.description, 'reminder': request.reminder, 'method': request.method, 'timezone': request.timezone, 'where': request.where } ) event_key_async = event_key.get_result() if request.parent: parent_key = ndb.Key(urlsafe=request.parent) # insert edges Edge.insert(start_node=parent_key, end_node=event_key_async, kind='events', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=event_key_async, kind='events', indexed_edge=str(parent_key.id()) ) else: data = {'id': event_key_async.id()} event.put_index(data) event_schema = EventSchema( id=str(event_key_async.id()), entityKey=event_key_async.urlsafe(), title=event.title, starts_at=event.starts_at.isoformat(), ends_at=event.ends_at.isoformat(), where=event.where, created_at=event.created_at.isoformat(), updated_at=event.updated_at.isoformat(), access=event.access, timezone=event.timezone, allday=event.allday ) return event_schema
def patch(cls, user_from_email, request): task = cls.get_by_id(int(request.id)) task_id = int(request.id) edges = Edge.query().filter(Edge.kind == "assignees", Edge.start_node == task.key) if task is None: raise endpoints.NotFoundException('Task not found.') if (task.owner != user_from_email.google_user_id ) and not user_from_email.is_admin: raise endpoints.ForbiddenException('you are not the owner') if request.title: task.title = request.title if request.access: task.access = request.access if request.status: task.status = request.status if task.status == 'closed': task.completed_by = user_from_email.google_user_id body = '<p>#closed, view details on ioGrow: <a href="http://app.iogrow.com/#/tasks/show/' + str( task.key.id()) + '">' body += task.title body += '</a></p>' created_by = model.User.get_by_gid(task.owner) to = None if created_by: to = created_by.email edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() cc = None for edge in edge_list['items']: assignee_list.append(edge.end_node.get().email) cc = ",".join(assignee_list) taskqueue.add(url='/workers/send_email_notification', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'to': to, 'cc': cc, 'subject': '[task]: ' + task.title, 'body': body }) if request.due and task.due is None: task.due = datetime.datetime.strptime(request.due, "%Y-%m-%dT%H:%M:00.000000") if edges: for edge in edges: assigned_to = edge.end_node.get() taskqueue.add(url='/workers/syncassignedtask', queue_name='iogrow-low-task', params={ 'email': assigned_to.email, 'task_key': task_id, 'assigned_to': edge.end_node.get() }) taskqueue.add(url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_id': task_id }) else: taskqueue.add(url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_id': task_id }) elif request.due and task.due is not None: task.due = datetime.datetime.strptime(request.due, "%Y-%m-%dT%H:%M:00.000000") if edges: for edge in edges: assigned_to = edge.end_node.get() taskqueue.add(url='/workers/syncassignedpatchtask', queue_name='iogrow-low-task', params={ 'email': assigned_to.email, 'task_key': task_id, 'assigned_to': edge.end_node.get() }) taskqueue.add(url='/workers/syncpatchtask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_google_id': task.task_google_id }) else: taskqueue.add(url='/workers/syncpatchtask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': task.title, 'task_google_id': task.task_google_id }) task_key = task.put_async() task_key_async = task_key.get_result() EndpointsHelper.update_edge_indexes(parent_key=task_key_async, kind=None, indexed_edge=None) return cls.get_schema(user_from_email=user_from_email, request=request)
def cascade_delete(cls, entityKey): Edge.delete_all_cascade(start_node=entityKey)
def insert(cls, user_from_email, request): case = cls( owner=user_from_email.google_user_id, organization=user_from_email.organization, access=request.access, name=request.name, priority=request.priority, description=request.description ) case_key = case.put_async() case_key_async = case_key.get_result() indexed = False status_key = None if request.status: status_key = ndb.Key(urlsafe=request.status) # insert edges Edge.insert(start_node=case_key_async, end_node=status_key, kind='status', inverse_edge='related_cases') account = None if request.account: try: account_key = ndb.Key(urlsafe=request.account) account = account_key.get() except: from crm.iomodels.accounts import Account account_key = Account.get_key_by_name( user_from_email=user_from_email, name=request.account ) if account_key: account = account_key.get() else: is_new_account = True account = Account( name=request.account, owner=user_from_email.google_user_id, organization=user_from_email.organization, access=request.access ) account_key_async = account.put_async() account_key = account_key_async.get_result() data = EndpointsHelper.get_data_from_index(str(account.key.id())) account.put_index(data) if account: # insert edges Edge.insert(start_node=account.key, end_node=case_key_async, kind='cases', inverse_edge='parents' ) EndpointsHelper.update_edge_indexes( parent_key=case_key_async, kind='cases', indexed_edge=str(account.key.id()) ) indexed = True contact = None if request.contact: try: contact_key = ndb.Key(urlsafe=request.contact) contact = contact_key.get() except: from crm.iomodels.contacts import Contact contact_key = Contact.get_key_by_name( user_from_email=user_from_email, name=request.contact ) if contact_key: contact = contact_key.get() else: firstname = request.contact.split()[0] lastname = " ".join(request.contact.split()[1:]) contact = Contact( firstname=firstname, lastname=lastname, owner=user_from_email.google_user_id, organization=user_from_email.organization, access=request.access ) contact_key_async = contact.put_async() contact_key = contact_key_async.get_result() if account: data = EndpointsHelper.get_data_from_index(str(contact.key.id())) contact.put_index(data) Edge.insert(start_node=account.key, end_node=contact.key, kind='contacts', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=contact.key, kind='contacts', indexed_edge=str(account.key.id()) ) if contact: # insert edges Edge.insert(start_node=contact.key, end_node=case_key_async, kind='cases', inverse_edge='parents') EndpointsHelper.update_edge_indexes( parent_key=case_key_async, kind='cases', indexed_edge=str(contact.key.id()) ) for infonode in request.infonodes: Node.insert_info_node( case_key_async, iomessages.InfoNodeRequestSchema( kind=infonode.kind, fields=infonode.fields ) ) if not indexed: data = {'id': case_key_async.id()} case.put_index(data) current_status_schema = None if status_key: if status_key.get(): current_status_schema = CaseStatusSchema( name=status_key.get().status ) case_schema = CaseSchema( id=str(case_key_async.id()), entityKey=case_key_async.urlsafe(), name=case.name, current_status=current_status_schema, priority=case.priority, created_at=case.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) return case_schema
def receive(self, mail_message): sender_id = mail_message.to.split("@")[0] try: bcc = mail_message.bcc.split("@")[0] except: bcc = 'undefined' user_id = 'undefined' if sender_id.isdigit(): user_id=sender_id if bcc.isdigit(): user_id=bcc user = User.get_by_gid(user_id) if user: sender_email=re.findall(r'[\w\.-]+@[\w\.-]+', mail_message.sender) if user.email==sender_email[0]: print 'authorized' html_bodies = mail_message.bodies('text/html') email_body = '' additional_emails = ' ' for content_type, body in html_bodies: decoded_html = smart_str(body.decode()) email_body+=decoded_html additional_emails+=' ' + smart_str(mail_message.to) try: additional_emails+=' ' + smart_str(mail_message.bcc) except: pass try: additional_emails+=' ' + smart_str(mail_message.cc) except: pass re_emails = re.findall(r'[\w\.-]+@[\w\.-]+', email_body + additional_emails) emails = list(set(re_emails)) print 'emails' print emails for email in emails: generic_prop = ndb.GenericProperty() generic_prop._name = 'email' nodes = Node.query(generic_prop==email).fetch() if len(nodes)>0: for node in nodes: parents_edge_list = Edge.list( start_node = node.key, kind = 'parents' ) for edge in parents_edge_list['items']: parent_key = edge.end_node # insert a note related to the parent node note_author = Userinfo() note_author.display_name = user.google_display_name note_author.photo = user.google_public_profile_photo_url note = Note( owner = user.google_user_id, organization = user.organization, author = note_author, title = mail_message.subject, content = email_body ) entityKey_async = note.put_async() entityKey = entityKey_async.get_result() Edge.insert( start_node = parent_key, end_node = entityKey, kind = 'topics', inverse_edge = 'parents' ) EndpointsHelper.update_edge_indexes( parent_key=entityKey, kind='topics', indexed_edge=str(parent_key.id()) ) else: pass # We should create a lead related to this email # and attach this email with this lead else: print 'not authorized' else: print 'user doesnt exist'
def list(cls, user_from_email, request): if request.tags: return cls.filter_by_tag(user_from_email, request) curs = Cursor(urlsafe=request.pageToken) if request.limit: limit = int(request.limit) else: limit = 1000 items = list() you_can_loop = True count = 0 while you_can_loop: if request.order: ascending = True if request.order.startswith('-'): order_by = request.order[1:] ascending = False else: order_by = request.order attr = cls._properties.get(order_by) if attr is None: raise AttributeError('Order attribute %s not defined.' % (attr_name,)) if ascending: cases, next_curs, more = cls.query().filter(cls.organization == user_from_email.organization).order( +attr).fetch_page(limit, start_cursor=curs) else: cases, next_curs, more = cls.query().filter(cls.organization == user_from_email.organization).order( -attr).fetch_page(limit, start_cursor=curs) else: cases, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).fetch_page(limit, start_cursor=curs) for case in cases: if len(items) < limit: is_filtered = True if request.tags and is_filtered: end_node_set = [ndb.Key(urlsafe=tag_key) for tag_key in request.tags] if not Edge.find(start_node=case.key, kind='tags', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.owner and case.owner != request.owner and is_filtered: is_filtered = False if request.status and case.status != request.status and is_filtered: is_filtered = False if request.priority and case.priority != request.priority and is_filtered: is_filtered = False if is_filtered and Node.check_permission(user_from_email, case): count += 1 # list of tags related to this case tag_list = Tag.list_by_parent(parent_key=case.key) case_status_edges = Edge.list( start_node=case.key, kind='status', limit=1 ) current_status_schema = None if len(case_status_edges['items']) > 0: current_status = case_status_edges['items'][0].end_node.get() current_status_schema = CaseStatusSchema( name=current_status.status, status_changed_at=case_status_edges['items'][0].created_at.isoformat() ) owner = model.User.get_by_gid(case.owner) owner_schema = None if owner: owner_schema = iomessages.UserSchema( id=str(owner.id), email=owner.email, google_display_name=owner.google_display_name, google_public_profile_photo_url=owner.google_public_profile_photo_url, google_public_profile_url=owner.google_public_profile_url, google_user_id=owner.google_user_id ) case_schema = CaseSchema( id=str(case.key.id()), entityKey=case.key.urlsafe(), name=case.name, current_status=current_status_schema, priority=case.priority, tags=tag_list, owner=owner_schema, access=case.access, created_at=case.created_at.strftime("%Y-%m-%dT%H:%M:00.000"), updated_at=case.updated_at.strftime("%Y-%m-%dT%H:%M:00.000") ) items.append(case_schema) if len(items) >= limit: you_can_loop = False if next_curs: if count >= limit: next_curs_url_safe = next_curs.urlsafe() else: next_curs_url_safe = curs.urlsafe() if next_curs: curs = next_curs else: you_can_loop = False next_curs_url_safe = None return CaseListResponse(items=items, nextPageToken=next_curs_url_safe)
def list(cls, user_from_email, request): curs = Cursor(urlsafe=request.pageToken) if request.limit: limit = int(request.limit) else: limit = 10 items = list() date_to_string = lambda x: x.strftime("%Y-%m-%d") if x else "" date_time_to_string = lambda x: x.strftime("%Y-%m-%dT%H:%M:00.000") if x else "" you_can_loop = True count = 0 while you_can_loop: if request.order: ascending = True if request.order.startswith('-'): order_by = request.order[1:] ascending = False else: order_by = request.order attr = cls._properties.get(order_by) if attr is None: raise AttributeError('Order attribute %s not defined.' % (order_by,)) if ascending: tasks, next_curs, more = cls.query().filter(cls.organization == user_from_email.organization).order( +attr).fetch_page(limit, start_cursor=curs) else: tasks, next_curs, more = cls.query().filter(cls.organization == user_from_email.organization).order( -attr).fetch_page(limit, start_cursor=curs) else: tasks, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).fetch_page(limit, start_cursor=curs) for task in tasks: if len(items) < limit: is_filtered = True if task.access == 'private' and task.owner != user_from_email.google_user_id: end_node_set = [user_from_email.key] if not Edge.find(start_node=task.key, kind='permissions', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.status and task.status != request.status and is_filtered: is_filtered = False if request.tags and is_filtered: end_node_set = [ndb.Key(urlsafe=tag_key) for tag_key in request.tags] if not Edge.find(start_node=task.key, kind='tags', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.assignee and is_filtered: user_assigned = model.User.get_by_gid(request.assignee) end_node_set = [user_assigned.key] if not Edge.find(start_node=task.key, kind='assignees', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.owner and task.owner != request.owner and is_filtered: is_filtered = False if request.completed_by and task.completed_by != request.completed_by and is_filtered: is_filtered = False if request.about and is_filtered: end_node_set = [ndb.Key(urlsafe=request.about)] if not Edge.find(start_node=task.key, kind='related_to', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.urgent and is_filtered: if task.due is None: is_filtered = False else: now = datetime.datetime.now() diff = task.due - now if diff.days > 2: is_filtered = False if task.status == 'closed': is_filtered = False if is_filtered: count += 1 # list of tags related to this task tag_list = Tag.list_by_parent(parent_key=task.key) about = None edge_list = Edge.list(start_node=task.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': about_name = parent.firstname + ' ' + parent.lastname else: about_name = parent.name about = DiscussionAboutSchema(kind=about_kind, id=str(parent.key.id()), name=about_name) # list of tags related to this task edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() for edge in edge_list['items']: if edge.end_node.get(): assignee_list.append(AuthorSchema(edgeKey=edge.key.urlsafe(), google_user_id=edge.end_node.get().google_user_id, google_public_profile_url=edge.end_node.get().google_public_profile_url, photo=edge.end_node.get().google_public_profile_photo_url)) status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str(diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str(diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema(google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author.google_public_profile_url, photo=task.author.photo) task_schema = TaskSchema( id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, comments=0, about=about, created_by=author_schema, completed_by=AuthorSchema(), tags=tag_list, assignees=assignee_list, created_at=date_time_to_string(task.created_at), updated_at=date_time_to_string(task.updated_at) ) if task.due: task_schema.due = date_to_string(task.due) items.append(task_schema) if len(items) >= limit: you_can_loop = False if next_curs: if count >= limit: next_curs_url_safe = next_curs.urlsafe() else: next_curs_url_safe = curs.urlsafe() if next_curs: curs = next_curs else: you_can_loop = False next_curs_url_safe = None return TaskListResponse(items=items, nextPageToken=next_curs_url_safe)
def get_schema(cls, user_from_email, request): task = cls.get_by_id(int(request.id)) if task is None: raise endpoints.NotFoundException('Task not found.') tag_list = Tag.list_by_parent(parent_key=task.key) about = None edge_list = Edge.list(start_node=task.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': if parent.lastname and parent.firstname: about_name = parent.firstname + ' ' + parent.lastname else: if parent.lastname: about_name = parent.lastname else: if parent.firstname: about_name = parent.firstname else: about_name = parent.name about = DiscussionAboutSchema(kind=about_kind, id=str(parent.key.id()), name=about_name) # list of tags related to this task edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() for edge in edge_list['items']: assignee_list.append( AuthorSchema( edgeKey=edge.key.urlsafe(), google_user_id=edge.end_node.get().google_user_id, display_name=edge.end_node.get().google_display_name, google_public_profile_url=edge.end_node.get( ).google_public_profile_url, photo=edge.end_node.get().google_public_profile_photo_url)) status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str(diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str(diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema( google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author. google_public_profile_url, photo=task.author.photo) due_date = None if task.due: due_date = task.due.strftime('%Y-%m-%d') task_schema = TaskSchema(id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, due=due_date, comments=0, about=about, created_by=author_schema, completed_by=AuthorSchema(), tags=tag_list, assignees=assignee_list, access=task.access, created_at=task.created_at.isoformat(), updated_at=task.updated_at.isoformat()) return task_schema
def insert(cls, user_from_email, request): if request.status: status = request.status else: status = 'open' if request.access: access = request.access else: access = 'public' author = Userinfo() author.google_user_id = user_from_email.google_user_id author.display_name = user_from_email.google_display_name author.photo = user_from_email.google_public_profile_photo_url task = Task(title=request.title, status=status, owner=user_from_email.google_user_id, organization=user_from_email.organization, access=access, author=author) if request.due: task.due = datetime.datetime.strptime( request.due, "%Y-%m-%dT%H:%M:00.000000" ) task_key = task.put_async() if request.due: taskqueue.add( url='/workers/synctask', queue_name='iogrow-low-task', params={ 'email': user_from_email.email, 'starts_at': request.due, 'ends_at': request.due, 'summary': request.title, 'task_id': task_key.get_result().id() } ) if request.reminder: pass task_key_async = task_key.get_result() if request.parent: # insert edges parent_key = ndb.Key(urlsafe=request.parent) Edge.insert(start_node=parent_key, end_node=task_key_async, kind='tasks', inverse_edge='related_to') EndpointsHelper.update_edge_indexes( parent_key=task_key_async, kind='tasks', indexed_edge=str(parent_key.id()) ) else: data = {'id': task_key_async.id()} task.put_index(data) if request.assignees: # insert edges for assignee in request.assignees: assignee_key = ndb.Key(urlsafe=assignee.entityKey) assignee_user = assignee_key.get() assignee_email = assignee_user.email # add a task queue to send notification email to assignee body = '<p>view details on ioGrow: <a href="http://app.iogrow.com/#/tasks/show/' + str( task_key_async.id()) + '">' body += request.title body += '</a></p>' taskqueue.add( url='/workers/send_email_notification', queue_name='iogrow-low', params={ 'user_email': user_from_email.email, 'to': assignee_email, 'subject': '[task]: ' + request.title, 'body': body } ) Edge.insert(start_node=task_key_async, end_node=assignee_key, kind='assignees', inverse_edge='assigned_to') if request.tags: # insert edges for tag in request.tags: Edge.insert(start_node=task_key_async, end_node=ndb.Key(urlsafe=tag.entityKey), kind='tags', inverse_edge='tagged_on') task_schema = TaskSchema( id=str(task_key_async.id()), entityKey=task_key_async.urlsafe(), title=task.title, status=task.status, access=task.access ) if task.due: task_schema.due = task.due.isoformat() return task_schema
def list(cls, user_from_email, request): curs = Cursor(urlsafe=request.pageToken) if request.limit: limit = int(request.limit) else: limit = 10 items = list() date_to_string = lambda x: x.strftime("%Y-%m-%d") if x else "" date_time_to_string = lambda x: x.strftime("%Y-%m-%dT%H:%M:00.000" ) if x else "" you_can_loop = True count = 0 while you_can_loop: if request.order: ascending = True if request.order.startswith('-'): order_by = request.order[1:] ascending = False else: order_by = request.order attr = cls._properties.get(order_by) if attr is None: raise AttributeError('Order attribute %s not defined.' % (order_by, )) if ascending: tasks, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(+attr).fetch_page( limit, start_cursor=curs) else: tasks, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(-attr).fetch_page( limit, start_cursor=curs) else: tasks, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).fetch_page(limit, start_cursor=curs) for task in tasks: if len(items) < limit: is_filtered = True if task.access == 'private' and task.owner != user_from_email.google_user_id: end_node_set = [user_from_email.key] if not Edge.find(start_node=task.key, kind='permissions', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.status and task.status != request.status and is_filtered: is_filtered = False if request.tags and is_filtered: end_node_set = [ ndb.Key(urlsafe=tag_key) for tag_key in request.tags ] if not Edge.find(start_node=task.key, kind='tags', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.assignee and is_filtered: user_assigned = model.User.get_by_gid(request.assignee) end_node_set = [user_assigned.key] if not Edge.find(start_node=task.key, kind='assignees', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.owner and task.owner != request.owner and is_filtered: is_filtered = False if request.completed_by and task.completed_by != request.completed_by and is_filtered: is_filtered = False if request.about and is_filtered: end_node_set = [ndb.Key(urlsafe=request.about)] if not Edge.find(start_node=task.key, kind='related_to', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.urgent and is_filtered: if task.due is None: is_filtered = False else: now = datetime.datetime.now() diff = task.due - now if diff.days > 2: is_filtered = False if task.status == 'closed': is_filtered = False if is_filtered: count += 1 # list of tags related to this task tag_list = Tag.list_by_parent(parent_key=task.key) about = None edge_list = Edge.list(start_node=task.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': about_name = parent.firstname + ' ' + parent.lastname else: about_name = parent.name about = DiscussionAboutSchema( kind=about_kind, id=str(parent.key.id()), name=about_name) # list of tags related to this task edge_list = Edge.list(start_node=task.key, kind='assignees') assignee_list = list() for edge in edge_list['items']: if edge.end_node.get(): assignee_list.append( AuthorSchema( edgeKey=edge.key.urlsafe(), google_user_id=edge.end_node.get( ).google_user_id, google_public_profile_url=edge.end_node .get().google_public_profile_url, photo=edge.end_node.get( ).google_public_profile_photo_url)) status_color = 'green' status_label = '' if task.due: now = datetime.datetime.now() diff = task.due - now if 0 <= diff.days <= 2: status_color = 'orange' status_label = 'soon: due in ' + str( diff.days) + ' days' elif diff.days < 0: status_color = 'red' status_label = 'overdue' else: status_label = 'due in ' + str( diff.days) + ' days' if task.status == 'closed': status_color = 'white' status_label = 'closed' author_schema = None if task.author: author_schema = AuthorSchema( google_user_id=task.author.google_user_id, display_name=task.author.display_name, google_public_profile_url=task.author. google_public_profile_url, photo=task.author.photo) task_schema = TaskSchema( id=str(task.key.id()), entityKey=task.key.urlsafe(), title=task.title, status=task.status, status_color=status_color, status_label=status_label, comments=0, about=about, created_by=author_schema, completed_by=AuthorSchema(), tags=tag_list, assignees=assignee_list, created_at=date_time_to_string(task.created_at), updated_at=date_time_to_string(task.updated_at)) if task.due: task_schema.due = date_to_string(task.due) items.append(task_schema) if len(items) >= limit: you_can_loop = False if next_curs: if count >= limit: next_curs_url_safe = next_curs.urlsafe() else: next_curs_url_safe = curs.urlsafe() if next_curs: curs = next_curs else: you_can_loop = False next_curs_url_safe = None return TaskListResponse(items=items, nextPageToken=next_curs_url_safe)
def list(cls, user_from_email, request): curs = Cursor(urlsafe=request.pageToken) if request.limit: limit = int(request.limit) else: limit = 10 items = [] you_can_loop = True count = 0 while you_can_loop: if request.order: ascending = True if request.order.startswith('-'): order_by = request.order[1:] ascending = False else: order_by = request.order attr = cls._properties.get(order_by) if attr is None: raise AttributeError('Order attribute %s not defined.' % (order_by,)) if ascending: events, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(+attr).fetch_page(limit, start_cursor=curs) else: events, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).order(-attr).fetch_page(limit, start_cursor=curs) else: events, next_curs, more = cls.query().filter( cls.organization == user_from_email.organization).fetch_page(limit, start_cursor=curs) for event in events: if count <= limit: is_filtered = True if event.access == 'private' and event.owner != user_from_email.google_user_id: end_node_set = [user_from_email.key] if not Edge.find(start_node=event.key, kind='permissions', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.tags and is_filtered: end_node_set = [ndb.Key(urlsafe=tag_key) for tag_key in request.tags] if not Edge.find(start_node=event.key, kind='tags', end_node_set=end_node_set, operation='AND'): is_filtered = False if request.owner and event.owner != request.owner and is_filtered: is_filtered = False if request.about and is_filtered: end_node_set = [ndb.Key(urlsafe=request.about)] if not Edge.find(start_node=event.key, kind='related_to', end_node_set=end_node_set, operation='AND'): is_filtered = False if is_filtered: count += 1 # list of tags related to this event tag_list = Tag.list_by_parent(parent_key=event.key) about = None edge_list = Edge.list(start_node=event.key, kind='related_to') for edge in edge_list['items']: about_kind = edge.end_node.kind() parent = edge.end_node.get() if parent: if about_kind == 'Contact' or about_kind == 'Lead': about_name = parent.firstname + ' ' + parent.lastname else: about_name = parent.name about = DiscussionAboutSchema(kind=about_kind, id=str(parent.key.id()), name=about_name) author_schema = None if event.author: author_schema = AuthorSchema(google_user_id=event.author.google_user_id, display_name=event.author.display_name, google_public_profile_url=event.author.google_public_profile_url, photo=event.author.photo) event_schema = EventSchema( id=str(event.key.id()), entityKey=event.key.urlsafe(), title=event.title, starts_at=event.starts_at.isoformat(), ends_at=event.ends_at.isoformat(), where=event.where, description=event.description, about=about, created_by=author_schema, tags=tag_list, created_at=event.created_at.isoformat(), updated_at=event.updated_at.isoformat() ) items.append(event_schema) if count == limit: you_can_loop = False if more and next_curs: curs = next_curs else: you_can_loop = False if next_curs and more: next_curs_url_safe = next_curs.urlsafe() else: next_curs_url_safe = None return EventListResponse(items=items, nextPageToken=next_curs_url_safe)