Example #1
0
def sub_share_template(request, user_id):
    user_id, subobj = get_realcustomer_and_obj(request, user_id)
    if request.method == "POST":
        status = int(request.POST.get('status', '0'))
        if status == 1:  # 共享
            template_id = int(request.POST.get('id', "0"))
            ShareTemplte.objects.get_or_create(template_id=template_id,
                                               user_id=user_id)
            messages.add_message(request, messages.SUCCESS, _(u'共享模板成功'))
        if status == 2:  # 撤销
            template_id = int(request.POST.get('id', "0"))
            ShareTemplte.objects.filter(template_id=template_id,
                                        user_id=user_id).delete()
            messages.add_message(request, messages.SUCCESS, _(u'撤销共享模板成功'))
        if status == 3:  # 批量共享
            ids = (request.POST.get('ids', False)).split(',')
            for template_id in ids:
                ShareTemplte.objects.get_or_create(template_id=template_id,
                                                   user_id=user_id)
            messages.add_message(request, messages.SUCCESS, _(u'批量共享模板成功'))
        if status == 4:  # 批量撤销
            ids = (request.POST.get('ids', False)).split(',')
            ShareTemplte.objects.filter(user_id=user_id,
                                        template_id__in=ids).delete()
            messages.add_message(request, messages.SUCCESS, _(u'批量撤销共享模板成功'))
        return HttpResponseRedirect(
            reverse("sub_share_template", args=(user_id, )))
    return render(request,
                  template_name='setting/sub_share_template.html',
                  context={
                      "subobj": subobj,
                      "user_id": user_id,
                  })
Example #2
0
def export_fail_addr_statistics(request):
    data = request.GET
    errtype = data.get('errtype', '')
    errdate = data.get('errdate', '')
    task_name = data.get('task_name', '')
    user_id = request.GET.get('user_id', '').strip()
    customer_id, subobj = get_realcustomer_and_obj(request, user_id)
    if errdate:
        lists = [(u'email', )
                 ] if request.user.lang_code == 'en-us' else [(u'邮箱地址', )]
        res = StatError.objects.filter(
            customer_id=customer_id, send_date=errdate).filter(
                error_type__in=errtype.split(',')).values_list('recipient')
        lists.extend(res)
        return ExcelResponse(lists, 'mail', encoding='gbk')
    if task_name:
        stats = StatTask.objects.filter(customer_id=customer_id,
                                        task_ident=task_name).values_list(
                                            'id', flat=True)
        list = StatError.objects.filter(customer_id=customer_id,
                                        task_id__in=stats).order_by('id')
        errtype_list = errtype.split(',')
        lists = []
        for err in errtype_list:
            if err not in ERRTYPE_VALS: continue
            res = list.filter(error_type=err).values_list('recipient')
            count = res.count()
            sheetname = u'{}({})'.format(ERRTYPE_VALS[err], count)
            lists.append((sheetname, count, res))
        lists.sort(key=lambda x: x[1], reverse=True)
        max_count = lists[0][1] if lists else 0
        return MultiSheetExcelResponse(lists,
                                       max_count,
                                       'mail',
                                       encoding='gbk')
Example #3
0
def mail_statistics_export(request):
    date_start = request.GET.get('date_start', '')
    date_end = request.GET.get('date_end', '')
    if not date_start and not date_end:
        raise Http404
    user_id = request.GET.get('user_id', '').strip()
    user_id, subobj = get_realcustomer_and_obj(request, user_id)
    return statistics_caches.mail_statistics_export(user_id, date_start,
                                                    date_end)
Example #4
0
def sub_share_template_ajax(request, user_id):
    user_id, subobj = get_realcustomer_and_obj(request, user_id)
    data = request.GET
    order_column = data.get('order[0][column]', '')
    order_dir = data.get('order[0][dir]', '')
    search = data.get('search[value]', '')
    colums = ['id', 'id', 'name', 'created', 'updated']
    lists = SendTemplate.objects.filter(user=request.user).filter(
        result__in=['green', 'yellow', 'red_pass']).filter(isvalid=True)
    if search:
        lists = lists.filter(name__icontains=search)
    if order_column and int(order_column) < len(colums):
        if order_dir == 'desc':
            lists = lists.order_by('-%s' % colums[int(order_column)])
        else:
            lists = lists.order_by('%s' % colums[int(order_column)])
    try:
        length = int(data.get('length', 1))
    except ValueError:
        length = 1

    try:
        start_num = int(data.get('start', '0'))
        page = start_num / length + 1
    except ValueError:
        start_num = 0
        page = 1
    count = lists.count()
    if start_num >= count:
        page = 1
    paginator = Paginator(lists, length)
    try:
        lists = paginator.page(page)
    except (EmptyPage, InvalidPage):
        lists = paginator.page(paginator.num_pages)

    rs = {
        "sEcho": 0,
        "iTotalRecords": count,
        "iTotalDisplayRecords": count,
        "aaData": []
    }
    re_str = '<td.*?>(.*?)</td>'
    number = length * (page - 1) + 1
    for d in lists.object_list:
        t = TemplateResponse(request, 'setting/sub_share_template_ajax.html', {
            'd': d,
            'number': number,
            'user_id': user_id,
        })
        t.render()
        rs["aaData"].append(re.findall(re_str, t.content, re.DOTALL))
        number += 1
    return HttpResponse(json.dumps(rs, ensure_ascii=False),
                        content_type="application/json")
Example #5
0
def get_mail_statistics_time(request, date_type, date_start, date_end,
                             user_id):
    date_type = date_type if date_type in ('today', 'yesterday', 'this_week',
                                           'last_week', 'this_month', 'custom',
                                           'subaccount') else 'today'
    customer_id = request.user.id
    today = datetime.date.today()
    fmt = "%Y-%m-%d"
    subobj = None
    if date_type == 'today':
        stat_date_s = stat_date_e = today.strftime(fmt)
    elif date_type == 'yesterday':
        stat_date_s = stat_date_e = (today -
                                     datetime.timedelta(days=1)).strftime(fmt)
    elif date_type == 'this_week':
        monday = today - datetime.timedelta(today.weekday())
        sunday = today + datetime.timedelta(6 - today.weekday())
        stat_date_s, stat_date_e = monday.strftime(
            '%Y-%m-%d'), sunday.strftime(fmt)
    elif date_type == 'last_week':
        l_monday = today - datetime.timedelta(today.weekday() + 7)
        l_sunday = today - datetime.timedelta(today.weekday() + 1)
        stat_date_s, stat_date_e = l_monday.strftime(
            '%Y-%m-%d'), l_sunday.strftime(fmt)
    elif date_type == 'this_month':
        first_day = datetime.date(day=1, month=today.month, year=today.year)
        _, last_day_num = calendar.monthrange(today.year, today.month)
        last_day = datetime.date(day=last_day_num,
                                 month=today.month,
                                 year=today.year)
        stat_date_s, stat_date_e = first_day.strftime(
            '%Y-%m-%d'), last_day.strftime(fmt)
    elif date_type == 'custom':
        if not date_start:
            date_start = datetime.date(day=1,
                                       month=today.month,
                                       year=today.year).strftime(fmt)
        if not date_end:
            _, last_day_num = calendar.monthrange(today.year, today.month)
            date_end = datetime.date(day=last_day_num,
                                     month=today.month,
                                     year=today.year).strftime(fmt)
        stat_date_s, stat_date_e = date_start, date_end
    elif date_type == 'subaccount' and user_id:
        customer_id, subobj = statistics_tools.get_realcustomer_and_obj(
            request, user_id)
        stat_date_e, stat_date_s = today.strftime(fmt), (
            today - datetime.timedelta(days=90)).strftime(fmt)
    else:
        stat_date_s = stat_date_e = today.strftime(fmt)
        customer_id = ''
    return customer_id, subobj, stat_date_s, stat_date_e
Example #6
0
def batch_statistics(request):
    action_type = request.GET.get('action_type', 'batch').strip()
    date_start = request.GET.get('date_start', '')
    date_end = request.GET.get('date_end', '')
    user_id = request.GET.get('user_id', '').strip()
    customer_id, subobj = get_realcustomer_and_obj(request, user_id)
    return render(request,
                  'statistics/batch_statistics.html',
                  context={
                      'action_type': action_type,
                      'date_start': date_start,
                      'date_end': date_end,
                      "subobj": subobj,
                  })
Example #7
0
def ajax_sender_statistics(request):
    data = request.GET
    date_start = data.get('date_start', '')
    date_end = data.get('date_end', '')
    user_id = data.get('user_id', '').strip()
    customer_id, subobj = statistics_tools.get_realcustomer_and_obj(
        request, user_id)
    key = ":django:edmweb:subaccount:ajax_sender_statistics:sender:{user_id}:{date_start}:{date_end}:".format(
        user_id=customer_id,
        date_start=date_start.replace("-", ""),
        date_end=date_end.replace("-", ""),
    )
    content = cache.get(key, None)
    if not content:
        order_column = data.get('order[0][column]', '')
        order_dir = data.get('order[0][dir]', '')
        search = data.get('search[value]', '')
        cr = connections['mm-ms'].cursor()
        sql = u'''
        SELECT COUNT(DISTINCT sender) FROM stat_sender
        WHERE customer_id={0} AND date BETWEEN '{1}' AND '{2}'
        '''.format(customer_id, date_start, date_end)
        cr.execute(sql)
        rows = cr.fetchall()
        count = rows[0][0] if rows[0][0] else 0

        try:
            length = int(data.get('length', 1))
        except ValueError:
            length = 1

        try:
            start_num = int(data.get('start', '0'))
        except ValueError:
            start_num = 0

        order_by_str = ''
        colums = [
            'stat.task_date', 'core.company', 'stat.sender', 'stat.send_count',
            'stat.lastip'
        ]
        if order_column and int(order_column) < len(colums):
            if order_dir == 'desc':
                order_by_str = u'order by %s desc' % colums[int(order_column)]
            else:
                order_by_str = u'order by %s asc' % colums[int(order_column)]

        sql = u'''
        SELECT core.customer_id, core.username, core.company,
                stat.task_date, stat.sender,
                stat.send_count, stat.lastip
        FROM (
             SELECT customer_id, username, company FROM core_customer WHERE customer_id={0}
        ) core
        LEFT JOIN (
            SELECT s.customer_id, s.date AS task_date, s.sender,
                    SUM(s.count) AS send_count,   -- 发送数量
                    s.lastip
            FROM stat_sender AS s
            WHERE s.customer_id={0} AND s.date BETWEEN '{1}' AND '{2}'
            GROUP BY s.customer_id, s.date, s.sender, s.lastip
        ) stat ON stat.customer_id = core.customer_id
        WHERE stat.customer_id IS NOT NULL
        {5} LIMIT {3} OFFSET {4};
        '''.format(customer_id, date_start, date_end, length, start_num,
                   order_by_str)
        cr.execute(sql)
        desc = cr.description
        rows = cr.fetchall()
        rs = {
            "sEcho": 0,
            "iTotalRecords": count,
            "iTotalDisplayRecords": count,
            "aaData": []
        }
        re_str = '<td.*?>(.*?)</td>'
        field = [col[0] for col in desc]
        for d in rows:
            t = TemplateResponse(request,
                                 'statistics/ajax_sender_statistics.html',
                                 {'d': dict(zip(field, d))})
            t.render()
            rs["aaData"].append(re.findall(re_str, t.content, re.DOTALL))
        content = HttpResponse(json.dumps(rs, ensure_ascii=False),
                               content_type="application/json")
        cache.set(key, content, 300)
    return content
Example #8
0
def ajax_batch_statistics(request):
    data = request.GET
    date_start = data.get('date_start', '')
    date_end = data.get('date_end', '')
    user_id = data.get('user_id', '').strip()
    customer_id, subobj = statistics_tools.get_realcustomer_and_obj(
        request, user_id)
    key = ":django:edmweb:subaccount:ajax_batch_statistics:batch:{user_id}:{date_start}:{date_end}:".format(
        user_id=customer_id,
        date_start=date_start.replace("-", ""),
        date_end=date_end.replace("-", ""),
    )
    content = cache.get(key, None)
    if not content:
        order_column = data.get('order[0][column]', '')
        order_dir = data.get('order[0][dir]', '')
        search = data.get('search[value]', '')
        cr = connections['mm-ms'].cursor()
        sql = u'''
        SELECT COUNT(DISTINCT task_ident) FROM stat_task
        WHERE customer_id={0} AND task_date BETWEEN '{1}' AND '{2}'
        '''.format(customer_id, date_start, date_end)
        cr.execute(sql)
        rows = cr.fetchall()
        count = rows[0][0] if rows[0][0] else 0

        try:
            length = int(data.get('length', 1))
        except ValueError:
            length = 1

        try:
            start_num = int(data.get('start', '0'))
        except ValueError:
            start_num = 0

        colums = ['stat.task_date', 'stat.task_ident', 'core.company']
        if order_column and int(order_column) < len(colums):
            if order_dir == 'desc':
                order_by_str = u' order by %s desc' % colums[int(order_column)]
            else:
                order_by_str = u' order by %s asc' % colums[int(order_column)]
        else:
            order_by_str = u' order by stat.task_date desc'

        sql = u'''
        SELECT core.customer_id, core.username, core.company,
                stat.task_date, stat.task_ident, stat.task_id,
                CAST(stat.count_send_exp AS SIGNED) AS count_send_exp,
                CAST(stat.count_send_real AS SIGNED) AS count_send_real,
                CAST(stat.count_fail AS SIGNED) AS count_fail,

                CAST(stat.count_err_1 AS SIGNED) AS count_err_1,
                CAST(stat.count_err_2 AS SIGNED) AS count_err_2,
                CAST(stat.count_err_3 AS SIGNED) AS count_err_3,
                CAST(stat.count_err_5 AS SIGNED) AS count_err_5,

                task.send_maillist, task.send_id
        FROM (
             SELECT customer_id, username, company FROM core_customer WHERE customer_id={0}
        ) core
        LEFT JOIN (
            SELECT customer_id, task_date, task_ident, task_id,
                    SUM(count_send) - SUM(count_error) + SUM(count_err_1) + SUM(count_err_2) + SUM(count_err_3) + SUM(count_err_5) AS count_send_exp, -- 发送量
                    SUM(count_send) - SUM(count_error) AS count_send_real, -- 实际发送
                    SUM(count_err_1) + SUM(count_err_2) + SUM(count_err_3) AS count_fail,-- 投递失败

                    SUM(count_err_1) AS count_err_1,   -- 邮箱不存在
                    SUM(count_err_2) AS count_err_2,   -- 空间不足
                    SUM(count_err_3) AS count_err_3,   -- 用户拒收
                    SUM(count_err_5) AS count_err_5    -- 拒绝投递
            FROM stat_task
            WHERE customer_id={0} AND task_date BETWEEN '{1}' AND '{2}'
            GROUP BY customer_id, task_date, task_ident, task_id
        ) stat ON stat.customer_id = core.customer_id
        LEFT JOIN (
            SELECT user_id AS customer_id, send_id, send_name, send_maillist
            FROM ms_send_list
            WHERE user_id={0} AND send_time BETWEEN '{1} 00:00:00' AND '{2} 23:59:59'
        ) task ON task.customer_id = stat.customer_id AND task.send_name = stat.task_ident
        WHERE stat.customer_id IS NOT NULL
       {5} LIMIT {3} OFFSET {4};
        '''.format(customer_id, date_start, date_end, length, start_num,
                   order_by_str)
        cr.execute(sql)
        desc = cr.description
        rows = cr.fetchall()
        rs = {
            "sEcho": 0,
            "iTotalRecords": count,
            "iTotalDisplayRecords": count,
            "aaData": []
        }
        re_str = '<td.*?>(.*?)</td>'
        field = [col[0] for col in desc]
        for d in rows:
            t = TemplateResponse(request,
                                 'statistics/ajax_batch_statistics.html', {
                                     'd': dict(zip(field, d)),
                                     "subobj": subobj,
                                 })
            t.render()
            rs["aaData"].append(re.findall(re_str, t.content, re.DOTALL))
        content = HttpResponse(json.dumps(rs, ensure_ascii=False),
                               content_type="application/json")
        cache.set(key, content, 300)
    return content