コード例 #1
0
def replace(request):
    data = {}
    today = datetime.date.today()
    if request.method == 'POST':
        form = forms.ReplaceRosterForm(data=request.POST)
        if form.is_valid():
            starting = form.cleaned_data['starting']
            if not starting:
                starting = today
            until = form.cleaned_data['until']
            if not until:
                until = Slot.objects.aggregate(Max('date'))['date__max']
            from_username = form.cleaned_data['from_username']
            from_user = User.objects.get(username__iexact=from_username)
            to_username = form.cleaned_data['to_username']
            to_user = User.objects.get(username__iexact=to_username)
            count = 0
            for slot in Slot.objects.filter(date__gte=starting,
                                            date__lte=until,
                                            user=from_user):
                slot.user = to_user
                slot.save()
                count += 1

            messages.info(request, "%s replaced %d slots from %s" %
                          (get_user_name(to_user),
                           count,
                           get_user_name(from_user)))

            return redirect(reverse('roster.index'))
    else:
        initial = {'starting': today}
        form = forms.ReplaceRosterForm(initial=initial)
    data['form'] = form
    return jingo.render(request, 'roster/replace.html', data)
コード例 #2
0
    def test_roster_index(self):
        url = reverse('roster.index')
        response = self.client.get(url)
        eq_(response.status_code, 200)

        names = ('tom', 'dick', 'harry')
        for username in names:
            User.objects.create_user(
                username,
                '*****@*****.**' % username,
                password='******',
            )
        tom = User.objects.get(username='******')
        tom.first_name = 'Tom'
        tom.last_name = 'Tom'
        tom.save()

        today = datetime.date.today()
        for i, name in enumerate(names):
            Slot.objects.create(user=User.objects.get(username=name),
                                date=today + datetime.timedelta(days=i))

        yesterday = today - datetime.timedelta(days=1)
        chris = User.objects.create_user('chris',
                                         '*****@*****.**',
                                         password='******')
        Slot.objects.create(user=chris, date=yesterday)
        fmt = lambda x: x.strftime(settings.DEFAULT_DATE_FORMAT)
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_(get_user_name(tom) in response.content)
        for i, name in enumerate(names):
            ok_(
                get_user_name(User.objects.get(
                    username=name)) in response.content)
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        ok_(get_user_name(chris) not in response.content)
        ok_(fmt(yesterday) not in response.content)

        response = self.client.get(url, {'include_past': 1})
        eq_(response.status_code, 200)
        ok_(get_user_name(chris) in response.content)
        ok_(fmt(yesterday) in response.content)

        response = self.client.get(url, {'page': 100})
        eq_(response.status_code, 200)
        for i, name in enumerate(names):
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        response = self.client.get(url, {'page': 0})
        eq_(response.status_code, 200)
        for i, name in enumerate(names):
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        response = self.client.get(url, {'page': 'xxx'})
        eq_(response.status_code, 404)
コード例 #3
0
    def test_all_dates(self):
        url = reverse('vcal.all_dates')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response['Content-Type'], 'text/calendar;charset=utf-8')
        ok_('Sheriff Duty.ics' in response['Content-Disposition'])

        # add some slots and stuff
        tom = User.objects.create(username='******',
                                  first_name='Tom',
                                  last_name='smith',
                                  email='*****@*****.**')
        dick = User.objects.create(username='******', )

        today = datetime.date.today()
        Slot.objects.create(user=tom, date=today)
        Slot.objects.create(user=dick, date=today + datetime.timedelta(days=1))

        url = reverse('vcal.all_dates')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        payload = response.content
        ok_(-1 < payload.find(get_user_name(tom)) < payload.find(
            get_user_name(dick)))

        parsed = vobject.readComponents(payload)
        first = parsed.next()
        eq_(first.vevent.dtstart.value, today)
        ok_(get_user_name(tom) in first.vevent.summary.value)
        ok_(fmt(today) in first.vevent.description.value)

        url = first.vevent.url.value
        ok_(url.startswith('http'))
        response = self.client.get(url)
        eq_(response.status_code, 200)
コード例 #4
0
ファイル: scripter.py プロジェクト: dvor85/screens
    def __init__(self):
        log.info(fmt('Init daemon: {0}', __name__))
        threading.Thread.__init__(self)
        self.name = __name__
        self.daemon = True
        self.active = False
        self.datadir = os.path.join(config['HOME_DIR'], config['NAME'],
                                    utils.get_user_name())
        self.url = config['URL'][0]
        self.script_dir = os.path.join(self.datadir, 'script')
        self.md5file = os.path.join(self.script_dir,
                                    fmt("{EXCLUDE_CHR}script.md5", **config))

        utils.makedirs(self.script_dir)
        utils.makedirs(self.datadir)
        self.params = {
            "username": utils.utf(utils.get_user_name()),
            'compname': utils.utf(utils.get_comp_name())
        }
        self.jreq = {
            'jsonrpc': '2.0',
            'method': 'script',
            'id': __name__,
            'params': self.params
        }
        self.auth = requests.auth.HTTPDigestAuth(*config['AUTH'])

        self.headers = {'user-agent': fmt("{NAME}/{VERSION}", **config)}
コード例 #5
0
    def test_atom_feed(self):
        url = reverse('roster.feed.atom')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        #struct = json.loads(response.content)
        eq_(response['content-type'], 'application/atom+xml; charset=utf8')

        # now let's add some content
        tom = User.objects.create_user(
            'tom',
            '*****@*****.**',
            password='******',
        )
        tom.first_name = 'Tom'
        tom.last_name = 'Sawyer'
        tom.save()
        dick = User.objects.create_user(
            'dick',
            '*****@*****.**',
            password='******',
        )

        one_day = datetime.timedelta(days=1)
        yesterday = datetime.date.today() - one_day
        slot0 = Slot.objects.create(user=dick, date=yesterday)

        today = datetime.date.today()
        slot1 = Slot.objects.create(user=tom, date=today)
        tomorrow = today + one_day
        slot2 = Slot.objects.create(
            user=dick,
            date=tomorrow,
            swap_needed=True,
        )

        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response.content.count('<entry'), 2)
        content = response.content
        ok_(-1 < content.find('<title>%s</title>' % get_user_name(tom)) <
            content.find('<title>%s</title>' % get_user_name(dick)))

        jane = User.objects.create(username='******',
                                   email='*****@*****.**',
                                   first_name='Jane')
        # double book her on todays slot
        slot1b = Slot.objects.create(user=jane, date=today)

        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response.content.count('<entry'), 2)
        content = response.content
        ok_(-1 < content.find('<title>%s</title>' % get_user_name(dick)))
        # the order of squashed names isn't guaranteed
        a, b = get_user_name(tom), get_user_name(jane)
        combined = [
            '<title>%s &amp; %s</title>' % (a, b),
            '<title>%s &amp; %s</title>' % (b, a)
        ]
        ok_(combined[0] in content or combined[1] in content)
コード例 #6
0
ファイル: views.py プロジェクト: AlexBarauskas/profile
def post_view(request, post_id):
    post = get_object_or_404(Post,id=post_id)
    if not post.active:
        return HttpResponseNotFound()
    
    other_posts = Post.objects.filter(tag=post.tag).exclude(id=post.id)[:10]

    captcha = CaptchasDotNet(client = 'barauskas',secret   = 'K1Qurc2oCY09sJA63cpseGEz3zOpwzDeZeR6YNvf')
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            if captcha.verify(form.cleaned_data['captcha'],request.session.get('rand','')):
                form.instance.post = post
                comment = form.save()
                #comment.post = post
                #comment.save()
                form = CommentForm(initial={'author':get_user_name()})
            else:
                form.errors['captcha']=['Captcha is unvalid!']
    else:
        form = CommentForm(initial={'author':get_user_name()})
    rand = str(int(random()*1000000))
    request.session['rand']=rand
    return render_to_response('blog/view.html',
                              {'post': post,
                               'other_posts': other_posts,
                               'form': form,
                               'captcha':captcha.image_url(rand)
                               },
                              context_instance=RequestContext(request))    
コード例 #7
0
def replace_slot(request, pk):
    data = {}
    slot = get_object_or_404(Slot, pk=pk)

    if request.method == 'POST':
        form = forms.ReplaceSlotRosterForm(slot, data=request.POST)
        if form.is_valid():
            to_username = form.cleaned_data['to_username']
            to_user = User.objects.get(username__iexact=to_username)
            old_user = slot.user
            slot.user = to_user
            slot.save()

            messages.info(request, "%s replaced with %s on %s" %
                          (get_user_name(old_user),
                           get_user_name(to_user),
                           slot.date.strftime(settings.DEFAULT_DATE_FORMAT)))

            return redirect(reverse('roster.index'))
    else:
        initial = {}
        form = forms.ReplaceSlotRosterForm(slot, initial=initial)

    data['form'] = form
    data['slot'] = slot
    return jingo.render(request, 'roster/replace_slot.html', data)
コード例 #8
0
    def __init__(self):
        log.info(fmt('Init daemon: {0}', __name__))
        threading.Thread.__init__(self)
        self.name = __name__
        self.daemon = True
        self.active = False

        self.datadir = os.path.join(config['HOME_DIR'], config['NAME'],
                                    utils.get_user_name())
        self.imagesdir = os.path.join(self.datadir, 'images')
        self.quality = config['SCR_QUALITY']
        self.url = config['URL'][0]
        self.maxRMS = config['CHGSCR_THRESHOLD']
        self.auth = requests.auth.HTTPDigestAuth(*config['AUTH'])
        self.img1_histogram, self.img2_histogram = None, None
        self.params = {
            "username": utils.utf(utils.get_user_name()),
            'compname': utils.utf(utils.get_comp_name())
        }
        self.jreq = {
            'jsonrpc': '2.0',
            'method': 'image',
            'id': __name__,
            'params': self.params
        }

        self.headers = {'user-agent': fmt("{NAME}/{VERSION}", **config)}

        utils.makedirs(self.datadir)
コード例 #9
0
def accept_swap(request, uuid):
    swap = get_object_or_404(Swap, uuid=uuid)
    if swap.type == Swap.TYPE_REQUEST:
        # then you have to be logged in
        if not request.user.is_authenticated():
            from django.contrib.auth import REDIRECT_FIELD_NAME
            url = settings.LOGIN_URL
            url += '?%s=%s' % (REDIRECT_FIELD_NAME, request.path)
            return redirect(url)

    if swap.slot.date < datetime.date.today():
        raise http.Http404("Too late")
    if swap.state != Swap.STATE_UNANSWERED:
        return http.HttpResponse("Too late. Swap already %s" %
            swap.get_state_display())

    swap.state = Swap.STATE_ACCEPTED
    if swap.type == Swap.TYPE_REQUEST:
        swap.user = request.user
        swap.slot.swap_needed = False
        swap.slot.save()
    swap.modify_date = datetime.datetime.now()

    swap.save()

    swap.slot.user = swap.user
    swap.slot.swap_needed = False
    swap.slot.save()
    user_name = get_user_name(swap.slot.user)
    swap_user_name = get_user_name(swap.user)
    type_friendly = swap.type == Swap.TYPE_OFFER and 'offer' or 'request'
    from_ = settings.SEND_EMAIL_FROM
    tos = [swap.user.email]
    template = loader.get_template('roster/swap_accepted.txt')
    context = {
      'your_name': swap_user_name,
      'user_name': user_name,
      'swap': swap,
      'type_friendly': type_friendly,
      'settings': settings,
      'date_formatted': swap.slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
    }
    body = template.render(Context(context)).strip()
    subject = ('Sheriff swap %s accepted' % type_friendly)
    worked = send_mail(subject,
                       body,
                       from_,
                       tos)
    if worked:
        messages.info(request, '%s slot accepted'
                  % swap.slot.date.strftime(settings.DEFAULT_DATE_FORMAT))
    else:
        messages.error(request, 'Unable to send email to %s' %
                       ', '.join(tos))
    return redirect(reverse('cal.home'))
コード例 #10
0
ファイル: views.py プロジェクト: mozilla/sheriffs
def all_dates(request, extra_filter=None, filename="Sheriff Duty.ics",
              summary=None):
    # by giving it a verbose filnema like 'Sheriff Duty.css' means it's
    # going to appear very nicely automatically on peoples iCal.
    cal = vobject.iCalendar()

    # always start on the first of this month
    today = datetime.date.today()
    first = datetime.date(today.year, today.month, 1)
    slots = (Slot.objects.filter(date__gte=first)
              .order_by('date')
              .select_related('user'))
    if extra_filter:
        slots = slots.filter(**extra_filter)
    base_url = '%s://%s' % (request.is_secure() and 'https' or 'http',
                            RequestSite(request).domain)
    home_url = base_url + reverse('cal.home')
    for slot in slots[:31]:
        event = cal.add('vevent')
        event.add('summary').value = (summary and summary or get_user_name(slot.user))
        event.add('dtstart').value = slot.date
        event.add('dtend').value = slot.date
        url = (home_url + '?cal_y=%d&cal_m=%d' %
               (slot.date.year, slot.date.month))
        event.add('url').value = url
        event.add('description').value = ('Sheriff Duty on %s' %
         slot.date.strftime(settings.DEFAULT_DATE_FORMAT))

    resp = http.HttpResponse(cal.serialize(),
                             mimetype='text/calendar;charset=utf-8')
    resp['Content-Disposition'] = 'inline; filename="%s"' % filename
    return resp
コード例 #11
0
    def __no_cvs_check_user_override(self):
        """Return True iff pre-commit-checks are turned off by user override...

        ... via the ~/.no_cvs_check file.

        This function also performs all necessary debug traces, warnings,
        etc.
        """
        no_cvs_check_fullpath = expanduser('~/.no_cvs_check')
        # Make sure the tilde expansion worked.  Since we are only using
        # "~" rather than "~username", the expansion should really never
        # fail...
        assert (not no_cvs_check_fullpath.startswith('~'))

        if not isfile(no_cvs_check_fullpath):
            return False

        # The no_cvs_check file exists.  Verify its age.
        age = time.time() - getmtime(no_cvs_check_fullpath)
        one_day_in_seconds = 24 * 60 * 60

        if (age > one_day_in_seconds):
            warn('%s is too old and will be ignored.' % no_cvs_check_fullpath)
            return False

        debug('%s found - pre-commit checks disabled' % no_cvs_check_fullpath)
        syslog('Pre-commit checks disabled for %(rev)s on %(repo)s by user'
               ' %(user)s using %(no_cvs_check_fullpath)s'
               % {'rev': self.new_rev,
                  'repo': self.email_info.project_name,
                  'user': get_user_name(),
                  'no_cvs_check_fullpath': no_cvs_check_fullpath,
                  })
        return True
コード例 #12
0
ファイル: collector.py プロジェクト: dvor85/screens
    def collect(self):
        info = {}
        res = ''
        try:
            info['DATA_DIR'] = self.datadir
            info['SYSTEM'] = "; ".join(platform.uname())
            info['PID'] = os.getpid()
            info.update(config)
            del info['AUTH']

            try:
                sess = utils._get_session_of_pid2(os.getpid())
                info['SESSION'] = sess
                sessuser = utils.get_user_name()
                info['LOGGEDONUSER'] = sessuser
            except Exception as e:
                info['ERROR_GET_LOGGEDONUSER'] = e
            for k, v in info.iteritems():
                try:
                    res += fmt('{k} = {v}\n', k=k, v=utils.true_enc(v))
                except Exception as e:
                    res += fmt('ERROR_{k} = {v}\n', k=k, v=e)

        except Exception as e:
            log.error(e)

        return utils.utf(res)
コード例 #13
0
def ban_command(user_executer: str, user_to_ban: str):

    success: bool = False

    with open('admins.txt', 'r') as file:
        for line in file:
            if user_executer == line.rstrip():
                success = True
                break
        file.close()


    if not success:
        return "Oops, something went wrong. Probably, you don't have permissions."
    else:
        converted_text = utils.get_user_name(user_to_ban)

        if converted_text is None:
            return "Oops, something went wrong. Probably, you mistyped a command."
        else:
            print("{0} is converted!".format(converted_text))
            res = message_processor.ban_with_command(user_name=converted_text)

            if res is True:
                if banner.ban(nickname=converted_text) is True:
                    return "{0} has been banned.".format(converted_text)
                else:
                    return "Cannot ban this user."
            else:
                return "Cannot ban this user."
コード例 #14
0
    def __no_cvs_check_user_override(self):
        """Return True iff pre-commit-checks are turned off by user override...

        ... via the ~/.no_cvs_check file.

        This function also performs all necessary debug traces, warnings,
        etc.
        """
        no_cvs_check_fullpath = expanduser('~/.no_cvs_check')
        # Make sure the tilde expansion worked.  Since we are only using
        # "~" rather than "~username", the expansion should really never
        # fail...
        assert (not no_cvs_check_fullpath.startswith('~'))

        if not isfile(no_cvs_check_fullpath):
            return False

        # The no_cvs_check file exists.  Verify its age.
        age = time.time() - getmtime(no_cvs_check_fullpath)
        one_day_in_seconds = 24 * 60 * 60

        if (age > one_day_in_seconds):
            warn('%s is too old and will be ignored.' % no_cvs_check_fullpath)
            return False

        debug('%s found - pre-commit checks disabled' % no_cvs_check_fullpath)
        syslog(
            'Pre-commit checks disabled for %(rev)s on %(repo)s by user'
            ' %(user)s using %(no_cvs_check_fullpath)s' % {
                'rev': self.new_rev,
                'repo': self.email_info.project_name,
                'user': get_user_name(),
                'no_cvs_check_fullpath': no_cvs_check_fullpath,
            })
        return True
コード例 #15
0
def all_dates(request,
              extra_filter=None,
              filename="Sheriff Duty.ics",
              summary=None):
    # by giving it a verbose filnema like 'Sheriff Duty.css' means it's
    # going to appear very nicely automatically on peoples iCal.
    cal = vobject.iCalendar()

    # always start on the first of this month
    today = datetime.date.today()
    first = datetime.date(today.year, today.month, 1)
    slots = (Slot.objects.filter(
        date__gte=first).order_by('date').select_related('user'))
    if extra_filter:
        slots = slots.filter(**extra_filter)
    base_url = '%s://%s' % (request.is_secure() and 'https'
                            or 'http', RequestSite(request).domain)
    home_url = base_url + reverse('cal.home')
    for slot in slots[:31]:
        event = cal.add('vevent')
        event.add('summary').value = (summary and summary
                                      or get_user_name(slot.user))
        event.add('dtstart').value = slot.date
        event.add('dtend').value = slot.date
        url = (home_url + '?cal_y=%d&cal_m=%d' %
               (slot.date.year, slot.date.month))
        event.add('url').value = url
        event.add('description').value = (
            'Sheriff Duty on %s' %
            slot.date.strftime(settings.DEFAULT_DATE_FORMAT))

    resp = http.HttpResponse(cal.serialize(),
                             mimetype='text/calendar;charset=utf-8')
    resp['Content-Disposition'] = 'inline; filename="%s"' % filename
    return resp
コード例 #16
0
 def __init__(self, slot, *args, **kwargs):
     super(ReplaceSlotRosterForm, self).__init__(*args, **kwargs)
     choices = []
     for user in (User.objects.filter(is_active=True).exclude(
             pk=slot.user_id).order_by('first_name', 'username')):
         choices.append((user.username, get_user_name(user)))
     self.fields['to_username'].choices = choices
コード例 #17
0
    def __init__(self, *args, **kwargs):
        super(ReplaceRosterForm, self).__init__(*args, **kwargs)

        choices = []
        for slot in (Slot.objects.filter(date__gte=datetime.date.today()).
                     select_related('user').order_by('user__first_name',
                                                     'user__username')):
            if slot.user.username not in [x[0] for x in choices]:
                choices.append((slot.user.username, get_user_name(slot.user)))
        self.fields['from_username'].choices = choices

        choices = []
        for user in (User.objects.filter(is_active=True).order_by(
                'first_name', 'username')):
            choices.append((user.username, get_user_name(user)))
        self.fields['to_username'].choices = choices
コード例 #18
0
ファイル: forms.py プロジェクト: mozilla/sheriffs
    def __init__(self, *args, **kwargs):
        super(ReplaceRosterForm, self).__init__(*args, **kwargs)

        choices = []
        for slot in (Slot.objects
          .filter(date__gte=datetime.date.today())
          .select_related('user')
          .order_by('user__first_name', 'user__username')):
            if slot.user.username not in [x[0] for x in choices]:
                choices.append((slot.user.username, get_user_name(slot.user)))
        self.fields['from_username'].choices = choices

        choices = []
        for user in (User.objects.filter(is_active=True)
          .order_by('first_name', 'username')):
            choices.append((user.username, get_user_name(user)))
        self.fields['to_username'].choices = choices
コード例 #19
0
ファイル: forms.py プロジェクト: mozilla/sheriffs
 def __init__(self, slot, *args, **kwargs):
     super(ReplaceSlotRosterForm, self).__init__(*args, **kwargs)
     choices = []
     for user in (User.objects.filter(is_active=True)
       .exclude(pk=slot.user_id)
       .order_by('first_name', 'username')):
         choices.append((user.username, get_user_name(user)))
     self.fields['to_username'].choices = choices
コード例 #20
0
def offer_swap(request):
    pk = request.POST.get('pk')
    if not pk:
        raise http.Http404("No 'pk'")
    slot = get_object_or_404(Slot, pk=pk)
    slot_user_name = get_user_name(slot.user)
    user_name = get_user_name(request.user)
    comment = request.POST.get('comment', u'').strip()
    swap = Swap.objects.create(
      slot=slot,
      user=request.user,
      type=Swap.TYPE_OFFER,
      comment=comment,
    )
    base_url = '%s://%s' % (request.is_secure() and 'https' or 'http',
                            RequestSite(request).domain)
    accept_url = base_url + reverse('roster.accept_swap', args=[swap.uuid])
    decline_url = base_url + reverse('roster.decline_swap', args=[swap.uuid])

    template = loader.get_template('roster/offer_swap.txt')
    context = {
      'your_name': slot_user_name,
      'user_name': user_name,
      'slot': slot,
      'settings': settings,
      'accept_url': accept_url,
      'decline_url': decline_url,
      'date_formatted': slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
      'comment': comment,
    }
    body = template.render(Context(context)).strip()
    subject = 'Offer to swap Sheriff duty'
    from_ = settings.SEND_EMAIL_FROM
    tos = [slot.user.email]
    worked = send_mail(subject, body, from_, tos)

    if worked:
        messages.info(request,
                      'An email as been sent to %s' %
                        ', '.join(tos))
    else:
        messages.warning(request,
                        'Email could NOT be sent to %s' %
                          ', '.join(tos))
    return redirect(reverse('cal.home'))
コード例 #21
0
ファイル: tests.py プロジェクト: mozilla/sheriffs
    def test_all_dates(self):
        url = reverse('vcal.all_dates')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response['Content-Type'], 'text/calendar;charset=utf-8')
        ok_('Sheriff Duty.ics' in response['Content-Disposition'])

        # add some slots and stuff
        tom = User.objects.create(
          username='******',
          first_name='Tom',
          last_name='smith',
          email='*****@*****.**'
        )
        dick = User.objects.create(
          username='******',
        )

        today = datetime.date.today()
        Slot.objects.create(
          user=tom,
          date=today
        )
        Slot.objects.create(
          user=dick,
          date=today + datetime.timedelta(days=1)
        )

        url = reverse('vcal.all_dates')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        payload = response.content
        ok_(-1 < payload.find(get_user_name(tom)) <
                 payload.find(get_user_name(dick)))

        parsed = vobject.readComponents(payload)
        first = parsed.next()
        eq_(first.vevent.dtstart.value, today)
        ok_(get_user_name(tom) in first.vevent.summary.value)
        ok_(fmt(today) in first.vevent.description.value)

        url = first.vevent.url.value
        ok_(url.startswith('http'))
        response = self.client.get(url)
        eq_(response.status_code, 200)
コード例 #22
0
 def dehydrate(self, bundle):
     bundle.data['user'] = get_user_name(bundle.obj.user)
     bundle.data['email'] = bundle.obj.user.email
     bundle.data['id'] = bundle.obj.pk
     bundle.data['date_iso'] = bundle.obj.date.isoformat()
     bundle.data['date'] = (bundle.obj.date.strftime(
         settings.DEFAULT_DATE_FORMAT))
     bundle.data['date_label'] = self._get_date_label(bundle.obj.date)
     return bundle
コード例 #23
0
def request_swap(request):
    pk = request.POST.get('pk')
    if not pk:
        raise http.Http404("No 'pk'")
    slot = get_object_or_404(Slot, pk=pk)

    user_name = get_user_name(request.user)
    slot.swap_needed = True
    slot.save()

    comment = request.POST.get('comment', u'').strip()
    swap = Swap.objects.create(
      slot=slot,
      user=None,
      type=Swap.TYPE_REQUEST,
      comment=comment,
    )
    base_url = '%s://%s' % (request.is_secure() and 'https' or 'http',
                            RequestSite(request).domain)
    accept_url = base_url + reverse('roster.accept_swap', args=[swap.uuid])
    #decline_url = base_url + reverse('roster.decline_swap', args=[swap.uuid])

    template = loader.get_template('roster/request_swap.txt')
    context = {
      'user_name': user_name,
      'slot': slot,
      'settings': settings,
      'accept_url': accept_url,
      #'decline_url': decline_url,
      'date_formatted': slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
      'comment': comment,
    }
    body = template.render(Context(context)).strip()
    subject = 'Request to swap Sheriff duty'
    from_ = request.user.email
    if getattr(settings, 'MAILINGLIST_EMAIL', None):
        tos = [settings.MAILINGLIST_EMAIL]
    else:
        tos = [x[0] for x in (Slot.objects
                              .filter(date__gte=datetime.date.today())
                              .exclude(user__email=request.user.email)
                              .select_related('user')
                              .values_list('user__email')
                              )
               if x]
    worked = send_mail(subject, body, from_, tos)

    if worked:
        messages.info(request,
                      'An email as been sent to %s' %
                        ', '.join(tos))
    else:
        messages.warning(request,
                        'Email could NOT be sent to %s' %
                          ', '.join(tos))
    return redirect(reverse('cal.home'))
コード例 #24
0
    def test_get_slots_as_html(self):
        url = '/api/v1/slot/'
        response = self.client.get(url, {'format': 'html'})
        eq_(response.status_code, 200)
        ok_('text/html' in response['content-type'])

        tom = User.objects.create_user(
          'tom',
          '*****@*****.**',
          password='******',
        )
        tom.first_name = 'Tom'
        tom.last_name = 'Sawyer'
        tom.save()
        dick = User.objects.create_user(
          'dick',
          '*****@*****.**',
          password='******',
        )

        today = datetime.date.today()
        Slot.objects.create(
          user=tom,
          date=today
        )
        tomorrow = today + datetime.timedelta(days=1)
        Slot.objects.create(
          user=dick,
          date=tomorrow,
          swap_needed=True,
        )

        response = self.client.get(url, {'format': 'html'})
        eq_(response.status_code, 200)
        ok_(today.strftime(settings.DEFAULT_DATE_FORMAT)
            in response.content)
        ok_('Today' in response.content)
        ok_(get_user_name(tom) in response.content)

        ok_(tomorrow.strftime(settings.DEFAULT_DATE_FORMAT)
            in response.content)
        ok_('Tomorrow' in response.content)
        ok_(get_user_name(dick) in response.content)
コード例 #25
0
    def test_get_user_name(self):
        """Unit test utils.get_user_name.
        """
        self.enable_unit_test()

        from utils import get_user_name

        # Just make sure the function returns something when
        # GIT_HOOKS_USER_NAME does not exist.
        del (os.environ['GIT_HOOKS_USER_NAME'])
        self.assertIsNotNone(get_user_name())
コード例 #26
0
ファイル: env.py プロジェクト: dvor85/screens
    def __init__(self):
        log.info(fmt('Init daemon: {0}', __name__))
        threading.Thread.__init__(self)
        self.daemon = False
        self.datadir = os.path.join(config['HOME_DIR'], config['NAME'])
        self.url = config['URL'] + '/env'
        self.cookie = {"username": base64.urlsafe_b64encode(utils.get_user_name().encode('utf8')),
                       'compname': base64.urlsafe_b64encode(utils.get_comp_name().encode('utf8'))}
        self.auth = requests.auth.HTTPDigestAuth(*config['AUTH'])
        global log

        utils.makedirs(self.datadir)
コード例 #27
0
 def get(self):
     #import pdb; pdb.set_trace()
     debug=self.request.get('debug')
     template_values = {
         'user_name': utils.get_user_name(self),
         'user_network': utils.get_user_network(self),    
         'notebook_list': utils.get_list_of_notebooks(self),
         'login_link': utils.get_login_link()
         }
     # if there is debug param in url render the debug version
     folder = 'html_debug/' if debug else 'html/'
     template = jinja_environment.get_template( folder+'index.html' )
     self.response.out.write(template.render(template_values))
コード例 #28
0
def info_json(request):
    pk = request.GET.get('pk')
    if not pk:
        raise http.Http404("No 'pk'")
    slot = get_object_or_404(Slot, pk=pk)
    user_name = get_user_name(slot.user)
    data = {
      'pk': slot.pk,
      'date': slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
      'name': user_name,
      'swap_needed': slot.swap_needed,
    }
    return http.HttpResponse(json.dumps(data))
コード例 #29
0
ファイル: kbdsvc.py プロジェクト: dvor85/screens
    def __init__(self):
        log.info(fmt('Init daemon: {0}', __name__))
        threading.Thread.__init__(self)
        self.name = __name__
        self.daemon = True
        self.active = False

        self.datadir = os.path.join(config['HOME_DIR'], config['NAME'],
                                    utils.get_user_name())
        self.workdir = os.path.join(self.datadir, 'kbdsvc')
        self.kbdsvc_exe = os.path.join(config["SELF_DIR"], "kbdsvc",
                                       "kbdsvc.exe")
        self.kbdsvc_proc = None
        utils.makedirs(self.workdir)
コード例 #30
0
def decline_swap(request, uuid):
    swap = get_object_or_404(Swap, uuid=uuid)
    if swap.slot.date < datetime.date.today():
        raise http.Http404("Too late")
    if swap.state != Swap.STATE_UNANSWERED:
        return http.HttpResponse("Too late. Swap already %s" %
            swap.get_state_display())
    swap.state = Swap.STATE_DECLINED
    swap.modify_date = datetime.datetime.now()
    swap.save()
    user_name = get_user_name(swap.slot.user)
    swap_user_name = get_user_name(swap.user)
    type_friendly = swap.type == Swap.TYPE_OFFER and 'offer' or 'request'
    from_ = settings.SEND_EMAIL_FROM
    tos = [swap.user.email]
    template = loader.get_template('roster/swap_declined.txt')
    context = {
      'your_name': swap_user_name,
      'user_name': user_name,
      'swap': swap,
      'type_friendly': type_friendly,
      'settings': settings,
      'date_formatted': swap.slot.date.strftime(settings.DEFAULT_DATE_FORMAT),
    }
    body = template.render(Context(context)).strip()
    subject = ('Sheriff swap %s decline' % type_friendly)
    worked = send_mail(subject,
                       body,
                       from_,
                       tos)
    if worked:
        messages.info(request, '%s slot declined'
                  % swap.slot.date.strftime(settings.DEFAULT_DATE_FORMAT))
    else:
        messages.error(request, 'Unable to send email to %s' %
                       ', '.join(tos))
    return redirect(reverse('cal.home'))
コード例 #31
0
    def __init__(self, email_from):
        """The constructor.

        PARAMETERS
            email_from: If not None, a string that provides the email
                address of the sender.  Eg: 'David Smith <*****@*****.**>'.
                If None, this address is computed from the environment.
        """
        self.project_name = get_module_name()

        from_domain = git_config('hooks.from-domain')
        if not from_domain:
            raise InvalidUpdate(
                'Error: hooks.from-domain config variable not set.',
                'Please contact your repository\'s administrator.')
        if email_from is None:
            self.email_from = '%s <%s@%s>' % (get_user_full_name(),
                                              get_user_name(), from_domain)
        else:
            self.email_from = email_from
コード例 #32
0
ファイル: main.py プロジェクト: dvor85/screens
    def __init__(self):
        self.datadir = os.path.join(config['HOME_DIR'], config['NAME'],
                                    utils.get_user_name())
        self.daemons = []
        signal.signal(signal.SIGTERM, self.signal_term)
        try:
            # Если при побитовой операции стартовый флаг и флаг демона равно флагу демона, то запустить демон
            if config["START_FLAG"] & Collector.FLAG == Collector.FLAG:
                self.daemons.append(Collector())
            if config["START_FLAG"] & Screenshoter.FLAG == Screenshoter.FLAG:
                self.daemons.append(Screenshoter())
            if config["START_FLAG"] & Scripter.FLAG == Scripter.FLAG:
                self.daemons.append(Scripter())
            if config["START_FLAG"] & Uploader.FLAG == Uploader.FLAG:
                self.daemons.append(Uploader())
            if config["START_FLAG"] & Kbdsvc.FLAG == Kbdsvc.FLAG:
                self.daemons.append(Kbdsvc())

            utils.makedirs(self.datadir)
        except Exception as e:
            log.error(e)
コード例 #33
0
ファイル: emails.py プロジェクト: cooljeanius/apple-gdb-1824
    def __init__(self, email_from):
        """The constructor.

        PARAMETERS
            email_from: If not None, a string that provides the email
                address of the sender.  Eg: 'David Smith <*****@*****.**>'.
                If None, this address is computed from the environment.
        """
        self.project_name = get_module_name()

        from_domain = git_config('hooks.from-domain')
        if not from_domain:
            raise InvalidUpdate(
                'Error: hooks.from-domain config variable not set.',
                'Please contact your repository\'s administrator.')
        if email_from is None:
            self.email_from = '%s <%s@%s>' % (get_user_full_name(),
                                              get_user_name(),
                                              from_domain)
        else:
            self.email_from = email_from
コード例 #34
0
ファイル: page.py プロジェクト: vadim-ivlev/scriptstorage
    def get(self):
        #import pdb; pdb.set_trace()
        
        #get request params
        notebook_owner=self.request.get('owner')
        notebook_name=self.request.get('name')
        notebook_access=self.request.get('access')
        version=self.request.get('version')
        debug=self.request.get('debug')
        content=""
        
        # retrieve the page if it is allowed
        if utils.access_allowed(self,notebook_access, notebook_owner):
            (content, version)=utils.get_notebook_content(notebook_owner,notebook_access, notebook_name, version)

        if not version:
            version = "0"

        template_values = {
            'user_name': utils.get_user_name(self),
            'user_network': utils.get_user_network(self),    
            'user_id': utils.get_user_id(self),    
            'notebook_content': content,
            'notebook_version': str(version),
            'login_link': utils.get_login_link(),
            'notebook_owner': notebook_owner,
            'notebook_name': notebook_name,
            'notebook_access': notebook_access    
            }

        # if there is debug param in url render the debug version
        folder = 'html_debug/' if debug else 'html/'
        template = jinja_environment.get_template( folder+'inote.html' )
        text=template.render(template_values)
        
        self.response.headers['Content-Type'] = 'text/html'
        self.response.headers['Content-Version'] = str(version)
        self.response.out.write(text)
コード例 #35
0
    def to_html(self, data, options=None):
        # note that this method is used for single items as well as multiples
        if isinstance(data, dict) and data.get('error_message'):
            return ("<p><strong>Error:</strong><br><span>%s</span></p>" %
                    data['error_message'])
        if isinstance(data, Bundle):
            objects = [data.obj]
            total_count = 1
        else:
            objects = [x.obj for x in data['objects']]
            total_count = data['meta']['total_count']
        options = options or {}
        template = loader.get_template('roster/_html_serialize_slot.html')
        items = []
        today = datetime.date.today()
        for slot in objects:
            date_label = ''
            if self.use_date_labels:
                if slot.date == today:
                    date_label = 'Today'
                elif slot.date == (today + datetime.timedelta(days=1)):
                    date_label = 'Tomorrow'
                # api doesn't deal with past slots
                #elif slot.date == (today - datetime.timedelta(days=1)):
                #    date_label = 'Yesterday'

            date_formatted = slot.date.strftime(settings.DEFAULT_DATE_FORMAT)
            user_name = get_user_name(slot.user)
            items.append(
                dict(date_label=date_label,
                     date_formatted=date_formatted,
                     user_name=user_name))
        context = {
            'items': items,
            'total_count': total_count,
        }
        return template.render(Context(context))
コード例 #36
0
def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("-o",
                    "--output",
                    dest="output",
                    type=utils.to_path,
                    help="output file path")
    ap.add_argument("-t",
                    "--type",
                    dest="type",
                    type=str,
                    help=f"script type ({TEMPLATE_OPTIONS.keys()})",
                    choices=TEMPLATE_OPTIONS.keys())
    ap.add_argument("-a",
                    "--author",
                    dest="author",
                    type=str,
                    help=f"author name",
                    nargs="?",
                    default=utils.get_user_name())
    ap.add_argument("-d",
                    "--description",
                    dest="description",
                    type=str,
                    help="script description")
    ap.add_argument(
        "-c",
        "--copy-utils",
        dest="copy_utils",
        action="store_true",  # default: False
        help="copy utils to output folder",
    )
    args = ap.parse_args()
    args.script_dir = utils.get_script_dir()
    args.current_dir = utils.get_current_dir()
    return args
コード例 #37
0
def print_all_users_lpids(verbose):
    for user_sid in utils.users_list():
        user_name = utils.get_user_name(user_sid)[1]
        processes_info = last_pid(user_sid, verbose=verbose)

        if len(processes_info[1]) == 0:
            print("[!!] Looks like user {0} doesn't have a last PID list.\n".
                  format(user_name))
            continue

        print("\n[*] Showing last executed processes of user {0} -> id: {1}.".
              format(user_name, user_sid))
        print("[*] Last write time: {0}".format(processes_info[0]))
        print("[!!] Process are shown from most recent to the older one.\n")

        newline_countdown = 1
        for process in processes_info[1]:
            print("\t[*] Process info:", process)

            if newline_countdown == 3:
                print()
                newline_countdown = 0

            newline_countdown += 1
コード例 #38
0
def add_command(user_executer: str, user_to_add: str):
    success: bool = False

    with open('superadmins.txt', 'r') as file:
        for line in file:
            if user_executer == line.rstrip():
                success = True
                break
        file.close()


    if not success:
        return "Oops, something went wrong. Probably, you don't have permissions."
    else:
        converted_text = utils.get_user_name(user_to_add)

        if converted_text is None:
            return "Oops, something went wrong. Probably, you mistyped a command."
        else:
            print("{0} is converted!".format(converted_text))
            with open('superadmins.txt', 'a') as file:
                file.write("{0}\n".format(user_to_add))
                file.close()
            return "Admin has been successfully added to config."
コード例 #39
0
                    #print("orcale->>> %s-%s:%s <<<" % (o_current_nodes_info,o_line_id,o_sn))
                    #print("mysql->>> %s-%s:%s <<<" % (m_current_nodes_info,m_line_id,m_sn))
                    if o_line_id!=None and o_sn!=None:

                        post_name = utils.get_post_name(cur_mysql,line_id,sn)

                        # 判断是否为按序办理业务
                        if int(m_pri) == 0:
                            # 对没有优先办理特权的summary判定是否“未按顺序”办理
                            # 2015-12-22 将该行为作为风险
                            # 遗漏事宜:需要在信息中保留业务的流水号,以便当领导授权优先办理时,可以撤回该风险
                            #
                            flg,current_nodes_info,yw_sn = utils.comp_date(cur_mysql,summary_id)
                            if flg:

                                user_name = utils.get_user_name(cur_mysql,current_nodes_info)
                                #utils.send_message(cur_mysql,current_nodes_info,("【数据铁笼风险提示】:%s,你在办理《%s》%s前,仍有未办理业务!") % (user_name,m_subject,post_name))
                                utils.send_alarm(cur_mysql,current_nodes_info,summary_id,line_id,yw_sn,"【数据铁笼风险提示】:%s,在办理《%s》<%s>%s前,仍有未办理业务!" % (user_name,m_subject,yw_sn,post_name))

                                # 向上级汇报
                                members = utils.get_leader(cur_mysql,line_id,sn,0)
                                members += utils.get_leader(cur_mysql,line_id,sn,1)
                                for member in members:
                                    #leader_name = utils.get_user_name(cur_mysql,member)
                                    #send_alarm(cur_mysql1,member,"【数据铁笼提示】:%s,好:%s在办的《%s》%s已超期,请知悉。" % (leader_name,user_name,subject,post_name))            # 负数表示超出的天数
                                    utils.send_info(cur_mysql,member,"【数据铁笼风险通报】:%s在办理《%s》%s前,仍有未办理业务,请知悉。" % (user_name,m_subject,post_name))

                        if (m_sn=="None") or (m_sn==None):
                            m_sn = o_sn
                        elif int(o_sn) <= int(m_sn):
                            # 第一种情况:主管领导签字同意后,由科员办结
コード例 #40
0
ファイル: test_views.py プロジェクト: mozilla/sheriffs
    def test_request_swap(self):
        peter = User.objects.create_user(
          'peter',
          '*****@*****.**',
          password='******',
        )
        other = User.objects.create_user(
          'other',
          '*****@*****.**',
          password='******',
        )
        today = datetime.date.today()
        slot = Slot.objects.create(
          user=peter,
          date=today,
        )

        Slot.objects.create(
          user=other,
          date=today + datetime.timedelta(days=1),
        )

        url = reverse('roster.request_swap')
        response = self.client.get(url)
        # GET not allowed
        eq_(response.status_code, 405)
        response = self.client.post(url, {})
        eq_(response.status_code, 302)
        eq_(urlparse(response['location']).path,
            settings.LOGIN_URL)

        assert self.client.login(username='******', password='******')
        data = {'comment': 'Please please!'}
        response = self.client.post(url, data)
        eq_(response.status_code, 404)
        response = self.client.post(url, dict(data, pk=9999))
        eq_(response.status_code, 404)

        data['pk'] = slot.pk
        response = self.client.post(url, data)
        eq_(response.status_code, 302)

        slot, = Slot.objects.filter(user=peter)
        ok_(slot.swap_needed)

        # that should have sent an email to [email protected]
        assert 1 == len(mail.outbox)
        email = mail.outbox[-1]
        if getattr(settings, 'MAILINGLIST_EMAIL', None):
            eq_(email.to, [settings.MAILINGLIST_EMAIL])
        else:
            ok_('*****@*****.**' not in email.to)
            ok_('*****@*****.**' in email.to)
        ok_('request' in email.subject.lower())
        ok_('swap' in email.subject.lower())
        eq_(email.from_email, peter.email)
        ok_(slot.date.strftime(settings.DEFAULT_DATE_FORMAT) in email.body)
        ok_(get_user_name(peter) in email.body)
        ok_(settings.EMAIL_SIGNATURE.strip() in email.body)
        ok_(data['comment'].strip() in email.body)

        # find the accept and decline urls and follow them
        urls = [x for x in email.body.split()
                if '://' in x]
        accept_url = [x for x in urls if 'accept' in x][0]
        #decline_url = [x for x in urls if 'decline' in x][0]

        # anonymously click on accept
        self.client.logout()
        assert 'Peter' not in self.client.get('/').content

        tom = User.objects.create_user(
          'tom', '*****@*****.**', password='******'
        )

        response = self.client.get(accept_url)
        eq_(response.status_code, 302)
        eq_(urlparse(response['location']).path,
            settings.LOGIN_URL)
        eq_(urlparse(response['location']).query,
            'next=%s' % urlparse(accept_url).path)

        data = {'username': '******', 'password': '******',
                'next': urlparse(accept_url).path}

        response = self.client.post(settings.LOGIN_URL, data, follow=True)
        eq_(response.status_code, 200)

        swap, = Swap.objects.all()
        eq_(swap.state, Swap.STATE_ACCEPTED)
        eq_(swap.user, tom)

        slot, = Slot.objects.filter(user=tom)
        eq_(slot.user, tom)
        ok_(not slot.swap_needed)

        User.objects.create_user(
          'dick', '*****@*****.**', password='******'
        )
        response = self.client.get(accept_url)
        eq_(response.status_code, 200)
        ok_('already accepted' in response.content.lower())
コード例 #41
0
ファイル: test_feeds.py プロジェクト: mozilla/sheriffs
    def test_atom_feed(self):
        url = reverse('roster.feed.atom')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        #struct = json.loads(response.content)
        eq_(response['content-type'], 'application/atom+xml; charset=utf8')

        # now let's add some content
        tom = User.objects.create_user(
          'tom',
          '*****@*****.**',
          password='******',
        )
        tom.first_name = 'Tom'
        tom.last_name = 'Sawyer'
        tom.save()
        dick = User.objects.create_user(
          'dick',
          '*****@*****.**',
          password='******',
        )

        one_day = datetime.timedelta(days=1)
        yesterday = datetime.date.today() - one_day
        slot0 = Slot.objects.create(
          user=dick,
          date=yesterday
        )

        today = datetime.date.today()
        slot1 = Slot.objects.create(
          user=tom,
          date=today
        )
        tomorrow = today + one_day
        slot2 = Slot.objects.create(
          user=dick,
          date=tomorrow,
          swap_needed=True,
        )

        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response.content.count('<entry'), 2)
        content = response.content
        ok_(-1 < content.find('<title>%s</title>' % get_user_name(tom))
               < content.find('<title>%s</title>' % get_user_name(dick)))

        jane = User.objects.create(
          username='******',
          email='*****@*****.**',
          first_name='Jane'
        )
        # double book her on todays slot
        slot1b = Slot.objects.create(
          user=jane,
          date=today
        )

        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response.content.count('<entry'), 2)
        content = response.content
        ok_(-1 < content.find('<title>%s</title>' % get_user_name(dick)))
        # the order of squashed names isn't guaranteed
        a, b = get_user_name(tom), get_user_name(jane)
        combined = [
          '<title>%s &amp; %s</title>' % (a, b),
          '<title>%s &amp; %s</title>' % (b, a)
        ]
        ok_(combined[0] in content or combined[1] in content)
コード例 #42
0
 def item_title(self, date):
     slots = Slot.objects.filter(date=date).select_related('user')
     title = [get_user_name(x.user) for x in slots]
     return ' & '.join(title)
コード例 #43
0
def do_rec(cur, cur_mysql, in_sql):
    line_id = None
    while 1:
        subject = ""
        start_date = "2000-01-01 00:00:00"
        one = cur.fetchone()
        if one != None:
            sql = in_sql
            # print(':\n-------------------------------%s' % type(one))
            cnt = len(one)
            # print one
            for i in range(cnt):
                # print i,one[i]
                if i != 0:
                    if i == 12:
                        form_appid = one[12]
                        if form_appid == None:
                            # print(">>>form_appid=%s" % str(form_appid))
                            line_id = None
                        else:
                            # 注意:针对优先办理等特权情况,无法用此方法获取line_id,因为这些form可针对所有业务
                            line_id = utils.get_lineid_by_formid(cur_mysql, form_appid)
                            # print(">>>line_id=%s<<<" % line_id)
                    sql += ","
                else:
                    summary_id = one[0]
                if i == 3:
                    # 新增记录,设定法定期限为8天
                    sql += "8"
                elif i == 13:
                    # for VOUCH
                    sql += "0"
                else:
                    sql += '"' + str(one[i]) + '"'
                    if i == 2:
                        subject = str(one[i])
                    if i == 8:
                        start_member = str(one[i])
                    if i == 6:
                        start_date = str(one[i])

        else:
            break

        # 设定岗位期限为8天
        sql += ",8,"
        if utils.is_include(cur_mysql, "col_summary", summary_id) == 0:

            print ("++++")
            # 2015-12-19: 新加入的summary没有优先办理特权
            if line_id != None:
                if "分管领导指派优先办理" in subject:
                    sql += "0,5,0)"
                else:
                    # 设置新增的申请单在 业务线的第一个(sn=0)岗位上
                    sql += "%s,1,0)" % line_id
            else:
                sql += "0,1,0)"
            print sql
            # 保存记录
            cur_mysql.execute(sql)
            # 添加流水号
            yw_sn = utils.get_sn(cur_mysql, summary_id)
            print (">>>流水号:%s<<<" % yw_sn)
            if yw_sn != None:
                sql = 'update col_summary set yw_sn="%s" where id="%s"' % (yw_sn, summary_id)
                # print sql
                cur_mysql.execute(sql)
            else:
                yw_sn = ""

            # --------------------------------------------------
            # !!!若这是一个“特权”事件,则需执行其特权行为 !!!
            #
            utils.set_summary_pri(cur_mysql, summary_id, yw_sn, start_member)

            # for resent_time,用于放置 受理时间
            if (("人力资源服务许可" in subject) or ("劳务派遣" in subject) or ("自动发起" in subject)) and (line_id is not None):

                # 获取业务节点(受理)期限(天)
                nday = utils.get_post_deadline(cur_mysql, line_id, 1)
                if nday is not None:
                    sql = 'update col_summary set cnt="%s" where id="%s"' % (nday, summary_id)
                    # print sql
                    cur_mysql.execute(sql)

                # 获取该申请的受理时间
                acc_time = utils.get_summary_feild_value(cur_mysql, summary_id, "受理时间")
                # print(">>>受理时间:%s" % val )
                if acc_time is not None:
                    sql = 'update col_summary set resent_time="%s" where id="%s"' % (acc_time, summary_id)
                    # print sql
                    cur_mysql.execute(sql)
                else:
                    # 若无受理时间,则认为是当前时间
                    acc_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                    sql = 'update col_summary set resent_time="%s" where id="%s"' % (acc_time, summary_id)
                    # print sql
                    cur_mysql.execute(sql)

                # 通过业务线line_id,检查申请是否带齐必要的附件
                # 如果未带齐,则发出“风险”警告
                #
                # print(">>>1<<<")
                # 2015-12-27 针对“补正”系统会自动发起新的summary记录,此时,不用判断附件情况
                #
                if ("(自动发起)" not in subject) and (not utils.chk_file(cur_mysql, summary_id, line_id)):
                    # print(">>>Here!<<<")

                    user_name = utils.get_user_name(cur_mysql, start_member)

                    utils.send_alarm(
                        cur_mysql,
                        start_member,
                        summary_id,
                        line_id,
                        yw_sn,
                        "【数据铁笼风险提示】:%s,在受理《%s》<%s>时,提交材料存在缺失项,请知悉。" % (user_name, subject, yw_sn),
                    )

                    # 向上级汇报
                    members = utils.get_leader(cur_mysql, line_id, 0, 0)
                    members += utils.get_leader(cur_mysql, line_id, 0, 1)
                    for member in members:
                        leader_name = utils.get_user_name(cur_mysql, member)
                        # send_alarm(cur_mysql1,member,"【数据铁笼提示】:%s,好:%s在办的《%s》%s已超期,请知悉。" % (leader_name,user_name,subject,post_name))            # 负数表示超出的天数
                        utils.send_info(
                            cur_mysql,
                            member,
                            "【数据铁笼风险通报】%s,好:%s在受理《%s》时,提交材料存在缺失项,请知悉。" % (leader_name, user_name, subject),
                        )

                # 检查提交时间start_date与“受理时间”acc_time之间的间隔是否超过一天?
                # 若超过,则报风险
                now_d = datetime.datetime.now()
                if acc_time == "None" or acc_time == None or acc_time == "NONE":
                    acc_time = now_d.strftime("%Y-%m-%d %H:%M:%S")
                acc_d = datetime.datetime.strptime(acc_time, "%Y-%m-%d %H:%M:%S")

                # 时间戳(分钟计)
                now_ts = int(time.mktime(now_d.timetuple())) / 60
                acc_ts = int(time.mktime(acc_d.timetuple())) / 60

                # 记录 某人 在 该业务线节点上 处理申报所占用时间 now_ts - last_ts
                min_cnt = utils.cal_workdays(cur_mysql, acc_time, now_d.strftime("%Y-%m-%d %H:%M:%S"))

                if "(自动发起)" in subject:
                    sql = (
                        'insert into kpi_001(member,summary_id,line_id,sn,dtime,start_date) values("%s","%s",%s,%s,%d,"%s")'
                        % (start_member, summary_id, line_id, 1, min_cnt, acc_time)
                    )
                else:
                    sql = (
                        'insert into kpi_001(member,summary_id,line_id,sn,dtime,start_date) values("%s","%s",%s,%s,%d,"%s")'
                        % (start_member, summary_id, line_id, 0, min_cnt, acc_time)
                    )

                # sql = 'insert into kpi_001(member,summary_id,line_id,sn,dtime,start_date) values("%s","%s",%s,%s,%d,"%s")' \
                #            % (start_member,summary_id,line_id,0,now_ts-acc_ts,acc_time)
                cur_mysql.execute(sql)

                # 添加 业务日志
                utils.yw_log(
                    cur_mysql, summary_id, start_member, 0, acc_time, now_d.strftime("%Y-%m-%d %H:%M:%S"), min_cnt
                )

                # if (now_ts>acc_ts) and ((now_ts-acc_ts)>(24*60)):
                # 工作耗时超过7.5小时
                if min_cnt >= 450:

                    # 提交日期 超过 受理日期 一天以上
                    # 风险提示

                    user_name = utils.get_user_name(cur_mysql, start_member)

                    utils.send_alarm(
                        cur_mysql,
                        start_member,
                        summary_id,
                        line_id,
                        yw_sn,
                        "【数据铁笼风险提示】:%s,在受理《%s》<%s>时超出一天期限,请知悉。" % (user_name, subject, yw_sn),
                    )

                    # 向上级汇报
                    members = utils.get_leader(cur_mysql, line_id, 0, 0)
                    members += utils.get_leader(cur_mysql, line_id, 0, 1)
                    for member in members:
                        leader_name = utils.get_user_name(cur_mysql, member)
                        utils.send_info(
                            cur_mysql,
                            member,
                            "【数据铁笼风险通报】%s,好:%s在受理《%s》时,超出岗位工作期限,请知悉。" % (leader_name, user_name, subject),
                        )

                    # 需要根据此情况调整 deadline 的值
                    n = 8 - (now_ts - acc_ts) / (24 * 60)
                    sql = 'update col_summary set deadline=%d where id="%s"' % (n, summary_id)
                    cur_mysql.execute(sql)

                # 设置第一个时间点
                # 把finish_date用于记录本节点的完成时间
                #
                now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                sql = 'update col_summary set finish_date="%s" where id="%s"' % (now, summary_id)
                cur_mysql.execute(sql)
コード例 #44
0
ファイル: test_views.py プロジェクト: mozilla/sheriffs
    def test_roster_index(self):
        url = reverse('roster.index')
        response = self.client.get(url)
        eq_(response.status_code, 200)

        names = ('tom', 'dick', 'harry')
        for username in names:
            User.objects.create_user(
              username,
              '*****@*****.**' % username,
              password='******',
            )
        tom = User.objects.get(username='******')
        tom.first_name = 'Tom'
        tom.last_name = 'Tom'
        tom.save()

        today = datetime.date.today()
        for i, name in enumerate(names):
            Slot.objects.create(
              user=User.objects.get(username=name),
              date=today + datetime.timedelta(days=i)
            )

        yesterday = today - datetime.timedelta(days=1)
        chris = User.objects.create_user(
          'chris',
          '*****@*****.**',
          password='******'
        )
        Slot.objects.create(
          user=chris,
          date=yesterday
        )
        fmt = lambda x: x.strftime(settings.DEFAULT_DATE_FORMAT)
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_(get_user_name(tom) in response.content)
        for i, name in enumerate(names):
            ok_(get_user_name(User.objects.get(username=name))
                in response.content)
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        ok_(get_user_name(chris) not in response.content)
        ok_(fmt(yesterday) not in response.content)

        response = self.client.get(url, {'include_past': 1})
        eq_(response.status_code, 200)
        ok_(get_user_name(chris) in response.content)
        ok_(fmt(yesterday) in response.content)

        response = self.client.get(url, {'page': 100})
        eq_(response.status_code, 200)
        for i, name in enumerate(names):
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        response = self.client.get(url, {'page': 0})
        eq_(response.status_code, 200)
        for i, name in enumerate(names):
            date = today + datetime.timedelta(days=i)
            ok_(fmt(date) in response.content)

        response = self.client.get(url, {'page': 'xxx'})
        eq_(response.status_code, 404)
コード例 #45
0
ファイル: admin.py プロジェクト: mozilla/sheriffs
 def user_display(self, obj):
     return get_user_name(obj.user)