def test_get_user_records(self):
     record = self._create_new_record()
     record.insert()
     record2 = self._create_new_record_two()
     record2.insert()
     user_records = ProjectMessageRecord.get_user_records(self.env, "milsomd")
     self.assertEqual(1, user_records[0]['record_id'])
     self.assertEqual("Test Case", user_records[0]['message_name'])
     user_records = ProjectMessageRecord.get_user_records(self.env, "goldinge")
     self.assertEqual(2, user_records[0]['record_id'])
     self.assertEqual("Another Test Case", user_records[0]['message_name'])
     user_records = ProjectMessageRecord.get_user_records(self.env, "clarki")
     self.assertEqual([], user_records)
    def process_request(self, req):
        """
        If the request is AJAX, inserts a new row into the record table for 
        the authenticated user to show they have seen a particular 
        notification.

        If the request is a normal GET, try and show the appropriate full 
        screen project message.
        """

        if req.path_info.startswith('/projectmessage'):
            try:
                name = req.path_info.split('/projectmessage/')[1]
            except IndexError:
                name = None
                self.log.debug("No project messages to show at "
                                "/projectmessage")

            if name:
                try:
                    msg = ProjectMessage(self.env, name)
                except ResourceNotFound:
                    self.log.debug("No project messages found")
                else:
                    add_script(req, 'projectmessage/js/project_message.js')
                    data = {
                        'name': msg['name'],
                        'message': msg['message'],
                        'button': msg['button'],
                    }
                    return 'project_message.html', data, None
            data = {'message': 'No project messages to show.'}
            return 'project_message.html', data, None

        elif (req.method == 'POST' and
                req.path_info.startswith('/ajax/projectmessage')):
            if req.args.get('name'):
                new_record = ProjectMessageRecord(self.env)
                new_record.populate(req)
                try:
                    new_record.insert()
                except:
                    self.log.info("Unable to create record that %s agreed "
                                  " to %s", new_record['agreed_by'], 
                                  new_record['message_name'])
                finally:
                    self.log.debug("Created a new record to show %s agreed "
                                   "to %s", new_record['agreed_by'],
                                   new_record['message_name'])
                data = {'success': True}
                req.send(to_json(data), 'text/json')
 def test_get_all_records(self):
     record = self._create_new_record()
     record.insert()
     all_records = ProjectMessageRecord.get_all_records(self.env)
     self.assertEqual(1, len(all_records))
     self.assertEqual(1, all_records[0]['record_id'])
     self.assertEqual("Test Case", all_records[0]['message_name'])
     self.assertEqual("milsomd", all_records[0]['agreed_by'])
     self.assertEqual(from_utimestamp(1396975221114382), all_records[0]['agreed_at'])
     record2 = self._create_new_record_two()
     record2.insert()
     all_records = ProjectMessageRecord.get_all_records(self.env)
     self.assertEqual(2, len(all_records))
     self.assertEqual(2, all_records[1]['record_id'])
     self.assertEqual("Another Test Case", all_records[1]['message_name'])
     self.assertEqual("goldinge", all_records[1]['agreed_by'])
     self.assertEqual(from_utimestamp(1396975221114388), all_records[1]['agreed_at'])
    def render_preference_panel(self, req, panel):

        agreed = ProjectMessageRecord.get_user_records(self.env, req.authname)
        for m in agreed:
            m['agreed_at'] = m['agreed_at'].strftime("%Y-%m-%d %H:%M")
        disagreed = ProjectMessage.get_unagreed_messages(self.env, req.authname)

        data = {
            'agreed': agreed,
            'unagreed': disagreed,
        }

        return 'project_message_prefs.html', data
    def render_admin_panel(self, req, cat, page, path_info):

        if 'LOGIN_ADMIN' in req.perm:

            if (page == 'project-message' and 
                'PROJECTMESSAGE_CREATE' in req.perm):

                groups = (sid for sid in Group.groupsBy(self.env))
                previous_msgs = ProjectMessage.get_all_messages(self.env)
                for m in previous_msgs:
                    for k in ('created_at', 'start', 'end'):
                        m[k] = m[k].strftime('%Y-%m-%d')

                data = {
                        'mode_options': ProjectMessageSystem(self.env).mode_options,
                        'group_options': itertools.chain(groups, ['*']),
                        'msgs': previous_msgs,
                        'start_date': datetime.now().strftime("%Y-%m-%d"),
                        'end_date': (datetime.now() + 
                                     timedelta(days=7)).strftime("%Y-%m-%d"),
                }

                # the message can be wiki mark-up
                Chrome(self.env).add_wiki_toolbars(req)
                add_script(req, 'projectmessage/js/project_message_admin.js')
                add_stylesheet(req, 'projectmessage/css/project_message_admin.css')

                if req.method == 'POST':
                    name = req.args.get('name')
                    message = req.args.get('message')
                    button = req.args.get('button')
                    mode = req.args.get('mode')
                    groups = req.args.get('groups', [])
                    start = req.args.get('start')
                    end = req.args.get('end')

                    if not all((name, message, button, mode, groups, start, end)):
                        add_notice(req, "Please complete the form - some "
                                        "fields were left blank.")
                        data.update(req.args)
                        return 'project_message_admin.html', data

                    new_msg = ProjectMessage(self.env)
                    msg_args = copy.deepcopy(req.args)
                    msg_args['author'] = req.authname
                    msg_args['created_at'] = to_utimestamp(datetime.now(pytz.utc))
                    if isinstance(groups, basestring):
                        msg_args['groups'] = [groups]
                    new_msg.populate(msg_args)

                    error = None
                    if not new_msg.unique_name:
                        add_warning(req, "There is already a project message "
                                        "with the name %s. Please choose "
                                        "a different name." % name)
                        error = True
                    elif not new_msg.valid_date_format:
                        add_warning(req, "Incorrect format for date. "
                                        "Should be YYYY-MM-DD" )
                        error = True
                    elif not new_msg.valid_date_range:
                        add_warning(req, "The date difference between start date and "
                                        "end date should be of atleast 1 day.")
                        error = True

                    if error:
                        data.update(req.args)
                        return 'project_message_admin.html', data

                    new_msg.insert()
                    try:
                        ProjectMessage(self.env, name)
                    except ResourceNotFound:
                        add_warning(req, "Unable to save project message. "
                            "Please try again.")
                        data.update(req.args)
                    else:
                        add_notice(req, "New project message created.")
                        self.log.info("New project message '%s' created", name)
                        # don't show a timestamp to the user - bad UI
                        new_msg['created_at'] = from_utimestamp(new_msg['created_at']).strftime('%Y-%m-%d')
                        data['msgs'].append(new_msg)

                return 'project_message_admin.html', data

            elif (page == 'project-message-records' and 
                'PROJECTMESSAGE_VIEW' in req.perm):

                records = ProjectMessageRecord.get_all_records(self.env)
                for r in records:
                    r['agreed_at'] = r['agreed_at'].strftime("%Y-%m-%d %H:%M")

                data = {
                        'records': records,
                }

                return 'project_message_records.html', data