示例#1
0
文件: views.py 项目: MarHelen/FBAuth
    This is the main view function.
    If the user is authorized, page with his/her name will be shown
    If the user isn't, the page with 2 buttons: login and signup will be shown.
    Function recieves parameter new_user, as a message or type of login.
    """
    logger.debug("From login view, new_user = %s", new_user)
=======
    #new_user = kwargs.get('new_user')
    logger.debug("I'm in login view, new_user = %s", new_user)
>>>>>>> be3fa6a7a31323f468e726ce99057468b8f27dda
    message = 'Welcome to application!'
    if new_user:
        if new_user == 1: #new one
            message = 'Wellcome to our app! Thanks for registration'
        else: 
            if new_user == 2: #loggined
                message = "Successfully logged in"
            else:
                message = new_user
    context = RequestContext(request, {
         'request': request, 'user': request.user, 'message' : message})
    return render_to_response('login.html', context_instance=context)

@login_required(login_url='/')
def logout(request):
    """
    This is a view function for simple django logout,
    it's shown, when user was assotiated on the login page.
    """
    auth_logout(request)
    return redirect('/')
示例#2
0
def logoutView(request):
    logout(request)
    return render_to_response('logout_template.html', {},
                              RequestContext(request))
示例#3
0
def displayApplicants(request):
    data = dict(applicant_list=Applicant.objects.all())
    return render_to_response(
        'user_templates/display_applicants_template.html', data,
        RequestContext(request))
示例#4
0
 def preview_get(self, request):
     "Displays the form"
     f = self.form(auto_id=self.get_auto_id(), initial=self.get_initial(request))
     return render_to_response(self.form_template,
         self.get_context(request, f),
         context_instance=RequestContext(request))
示例#5
0
def home(request):
    return render_to_response('partners_index.html', {},
                              context_instance=RequestContext(request))
def menuItem_detail(request, menuItem_id):
    template_var = {}

    NONE_ROW = [None] * 7
    template_var['menuItem'] = menuItem = MenuItem.objects.get(pk=menuItem_id)
    org = menuItem.org
    details = menuItem.details.all()
    template_var['max_item'] = OrgProfile.objects.get(org=org).max_item

    if request.method == "GET":
        template_var['datas'] = simplejson.dumps(
            details.exists()
            and [(detail.good_id, detail.good.name, detail.weight,
                  detail.goods_unit and detail.goods_unit.unit
                  or None, detail.good.get_unit_price(detail.goods_unit)[0],
                  detail.good.get_unit_price(detail.goods_unit)[0] *
                  detail.weight, detail.pk)
                 for detail in details] or [NONE_ROW])
    else:
        try:

            auto_reduce = request.POST['auto_reduce']
            if auto_reduce == 'false':
                menuItem.sync_type = 0
            else:
                menuItem.sync_type = 1
            menuItem.save()

            details_data = []
            details_data_error = []
            details_data_error_count = 0
            exists_key = []
            formset_data_str = request.POST.get('data')

            if formset_data_str:
                formset_data = simplejson.loads(formset_data_str)
                i = 0
                for detail in formset_data:
                    if detail[1] == "null":
                        detail[1] = None
                    detail_data_error = []
                    if detail != NONE_ROW:
                        detail_data_error = [
                            (i == 0 and 1 or i) for i in [0, 2]
                            if (not detail[i] or detail[i] < 0)
                        ]

                        if not detail_data_error:
                            details_data.append(detail)
                            if detail[6]:
                                exists_key.append(detail[6])
                        else:
                            details_data_error_count += 1

                    details_data_error.append(detail_data_error)
        except:
            print traceback.print_exc()

        if not details_data_error_count:  #details_data and
            try:
                all_key = list(details.values_list('id', flat=True))
                delete_key = set(all_key) - set(exists_key)
                details.filter(id__in=list(delete_key)).delete()

                total_price = 0
                for dd in details_data:
                    try:
                        good = Goods.objects.get(pk=dd[0])
                        unit = dd[3] and (dd[3] == good.unit.unit and good.unit
                                          or Unit.objects.filter(
                                              good_id=dd[0],
                                              unit=dd[3])[0]) or None

                        num = good.change_nums(dd[5], unit)

                        if dd[6]:
                            detail = MenuItemDetail.objects.get(pk=dd[6])
                            detail.good = good
                            detail.weight = dd[2]
                            detail.goods_unit = unit
                            detail.save()
                        else:
                            detail = MenuItemDetail.objects.create(
                                org=org,
                                menuItem=menuItem,
                                good=good,
                                weight=dd[2],
                                goods_unit=unit)

                        total_price += dd[5]
                    except:

                        print traceback.print_exc()
                        continue

                menuItem.cost = total_price
                if total_price:
                    menuItem.percent1 = menuItem.cost and (
                        menuItem.price -
                        menuItem.cost) * 100.0 / menuItem.cost or 0
                    menuItem.percent2 = menuItem.price and (
                        menuItem.price -
                        menuItem.cost) * 100.0 / menuItem.price or 0
                else:
                    menuItem.percent1 = 0
                    menuItem.percent2 = 0

                menuItem.profit = menuItem.price - menuItem.cost
                menuItem.save()

                if request.is_ajax():
                    details = menuItem.details.all()
                    datas = [{
                        'name':
                        detail.good.name,
                        'unit':
                        detail.goods_unit and detail.goods_unit.unit or None,
                        'weight':
                        detail.weight,
                        'price':
                        detail.good.price
                    } for detail in details]
                    '''
                    @创建更新菜品物品同步记录
                    @date:2017/4/13

                    '''
                    if not datas:
                        edit_log = EditGoodsMenuLog.objects.create(
                            org=org,
                            menu_id=menuItem_id,
                            menu_name=menuItem.item_name,
                            created_user=request.user,
                            is_cleaned=1)
                    else:
                        edit_log = EditGoodsMenuLog.objects.create(
                            org=org,
                            menu_id=menuItem_id,
                            menu_name=menuItem.item_name,
                            created_user=request.user)
                    log_detail_list = []

                    for data in datas:
                        log_detail_list.append(
                            EditGoodsMenuLogDetail(log_id=edit_log,
                                                   item_name=data['name'],
                                                   unit=data['unit'],
                                                   num=data['weight'],
                                                   price=data['price'],
                                                   total_price=data['price'] *
                                                   data['weight']))

                    EditGoodsMenuLogDetail.objects.bulk_create(log_detail_list)

                    return HttpResponse(simplejson.dumps({
                        'success':
                        1,
                        'seq':
                        int(request.GET['seq']),
                        'cost':
                        menuItem.cost,
                        'profit':
                        menuItem.profit,
                        'percent1':
                        round(menuItem.percent1, 2),
                        'percent2':
                        round(menuItem.percent2, 2),
                        'datas':
                        datas
                    }),
                                        mimetype='application/json')

            except:
                print traceback.print_exc()
        else:

            if request.is_ajax():
                return HttpResponseBadRequest(simplejson.dumps(
                    {'details_data_error': details_data_error}),
                                              mimetype='application/json')

    return render_to_response('simple/menuItem_detail.html',
                              template_var,
                              context_instance=RequestContext(request))
def in_out_simple(request, org_id):
    template_var = {}
    try:
        template_var['org'] = org = Organization.objects.get(slug=org_id)
    except:
        template_var['org'] = org = Organization.objects.get(pk=org_id)

    gid = request.GET.get('gid')
    template_var['good'] = good = Goods.objects.get(org=org, pk=gid)

    if request.method == "GET":
        template_var['suppliers'] = Supplier.objects.filter(org=org, status=1)
        template_var['departments'] = ConDepartment.objects.filter(org=org,
                                                                   status=1)
        template_var['customers'] = Customer.objects.filter(org=org, status=1)

        units = good.units
        if units:
            template_var['units'] = units

        response = render_to_response('simple/in_out_simple.html',
                                      template_var,
                                      context_instance=RequestContext(request))
        transaction.commit()
        return response

    else:
        try:
            invoice_type = int(
                request.POST.get('in_invoice_type')
                or request.POST.get('out_invoice_type'))
            nums = float(
                request.POST.get('in_nums') or request.POST.get('out_nums'))
            unit_id = request.POST.get('in_unit') or request.POST.get(
                'out_unit')
            try:
                price = float(
                    request.POST.get('in_price')
                    or request.POST.get('out_price'))
            except ValueError:
                price = 0
            remark = request.POST.get('remark')

            supplier_cus = request.POST.get('supplier_cus')
            customer_cus = request.POST.get('customer_cus')
            department_cus = request.POST.get('department_cus')

            tag = request.GET.get('tag')

            if invoice_type == 1000 or invoice_type == 1001:
                #权限判断
                if not request.user.has_org_perm(org, 'depot.caigouruku_add'):
                    return HttpResponse(simplejson.dumps({
                        'success':
                        0,
                        'message':
                        _(u'处理失败,没有权限')
                    }),
                                        mimetype='application/json')

            warehouse = Warehouse.objects.filter(org=org)[0]

            invoice = Invoice.objects.create(
                org=org,
                warehouse_root=warehouse,
                event_date=datetime.date.today(),
                invoice_type=invoice_type,
                charger=request.user,
                user=request.user,
                remark=remark,
                content_object=request.user,
                invoice_code=Invoice.get_next_invoice_code())

            if unit_id:
                unit = Unit.objects.get(pk=unit_id)
                num = good.change_nums(nums, unit)
            else:
                unit = None
                num = nums

            if invoice_type == 1001:
                supplier, created = Supplier.objects.get_or_create(
                    org=org,
                    name=supplier_cus,
                    defaults={'abbreviation': get_abbreviation(supplier_cus)})
                invoice.content_object = supplier

            elif invoice_type == 2000:
                supplier, created = Supplier.objects.get_or_create(
                    org=org,
                    name=supplier_cus,
                    defaults={'abbreviation': get_abbreviation(supplier_cus)})
                invoice.content_object = supplier

            elif invoice_type == 2001:
                department, created = ConDepartment.objects.get_or_create(
                    org=org,
                    name=department_cus,
                    defaults={
                        'abbreviation': get_abbreviation(department_cus)
                    })
                invoice.content_object = department
            elif invoice_type == 2002:
                customer, created = Supplier.objects.get_or_create(
                    org=org,
                    name=customer_cus,
                    defaults={'abbreviation': get_abbreviation(customer_cus)})
                invoice.content_object = customer

            if invoice_type in (1000, 1001, 2000, 2001):
                InvoiceDetail.objects.create(
                    invoice=invoice,
                    good=good,
                    batch_code=InvoiceDetail.get_next_detail_code(),
                    warehouse_root=invoice.warehouse_root,
                    warehouse=warehouse,
                    num1=nums,
                    unit1=unit,
                    price=price,
                    total_price=nums * price,
                    num=num,
                    last_nums=num,
                    avg_price=num and (nums * price) / num or 0)
                #更新成本价
                if unit and unit.good:
                    unit.price = price
                    unit.save()
                else:
                    good.price = price
                    good.save()

                invoice.total_price = nums * price
            elif invoice_type == 2002:
                InvoiceDetail.objects.create(
                    invoice=invoice,
                    good=good,
                    batch_code=InvoiceDetail.get_next_detail_code(),
                    warehouse_root=invoice.warehouse_root,
                    warehouse=warehouse,
                    num1=nums,
                    unit1=unit,
                    price=price,
                    total_price=nums * price,
                    num=num,
                    last_nums=num,
                    avg_price=num and (nums * price) / num or 0,
                    chenben_price=good.chengben_price * num)

                if unit and unit.good:
                    unit.sale_price = price
                    unit.save()
                else:
                    good.sale_price = price
                    good.save()

                invoice.total_price = nums * price
                invoice.sale_price = good.chengben_price * num

            invoice.save()

            try:
                res = invoice.confirm(request.user)
                if res != 2:
                    transaction.rollback()
                    invoice.delete()
                    return HttpResponse(simplejson.dumps({
                        'success':
                        0,
                        'message':
                        _(u'处理失败,是否数量不足,请先入库')
                    }),
                                        mimetype='application/json')
            except Exception, e:
                invoice.delete()
                transaction.rollback()
                print traceback.print_exc()
                return HttpResponse(simplejson.dumps({
                    'success': 0,
                    'message': e.message
                }),
                                    mimetype='application/json')

            good = Goods.objects.get(pk=gid)
            transaction.commit()
            return HttpResponse(simplejson.dumps({
                'success':
                1,
                'invoice_type':
                invoice_type,
                'good_nums':
                good.nums,
                'tag':
                tag,
                'unit':
                unit and unit.unit or '',
                'nums':
                nums,
                'price':
                price,
                'date':
                invoice.event_date.strftime('%Y-%m-%d'),
                'good_id':
                good.id
            }),
                                mimetype='application/json')

        except Exception, e:
            transaction.rollback()
            print traceback.print_exc()
            return HttpResponse(simplejson.dumps({
                'success': 0,
                'message': e.message
            }),
                                mimetype='application/json')
示例#8
0
def delneveshte(request):
    return render_to_response('pin/delneveshte2.html',context_instance=RequestContext(request))
示例#9
0
def view(request):
    return render_to_response('task/sales/view.html',
                              dict(),
                              context_instance=RequestContext(request))
示例#10
0
def activity_report(request):
    if not request.user.is_authenticated() or not request.user.is_staff:
        raise PermissionDenied
    return render_to_response(TEMPLATE_ROOT + 'wechat/report.html', 
                              {'REPORT_TITLE': u'微信用户消息统计'},
                              context_instance=RequestContext(request))
示例#11
0
def edit(request, post_id):
    try:
        post = Post.objects.get(pk=int(post_id))
        if post.user.id != request.user.id:
            return HttpResponseRedirect('/pin/')

        if request.method == "POST":
            post_values = request.POST.copy()
            tags = post_values['tags']
            post_values['tags']=tags[tags.find("[")+1:tags.find("]")]
            form = PinUpdateForm(post_values, instance=post)
            if form.is_valid():
                model = form.save(commit=False)
                
                model.save()
                
                form.save_m2m()
                
                return HttpResponse('با موفقیت به روزرسانی شد.')
        else:
            form = PinUpdateForm(instance=post)
        
        if request.is_ajax():
            return render_to_response('pin/_edit.html',{'form': form, 'post':post}, context_instance=RequestContext(request))
        else:
            return render_to_response('pin/edit.html',{'form': form, 'post':post}, context_instance=RequestContext(request))
    except Post.DoesNotExist:
        return HttpResponseRedirect('/pin/')
示例#12
0
def main(request):
    c = RequestContext(request, {"main_page": "start/start.htm"})
    return render_to_response('index.htm', c)
示例#13
0
def start(request):
    c = RequestContext(request, {})
    renderTemplate = "start/start.htm"
    return render_to_response(renderTemplate, c)
示例#14
0
def character_class_detail(request,
                           character_class_slug,
                           rulebook_slug=None,
                           rulebook_id=None):
    # fetch the class
    character_class = get_object_or_404(CharacterClass.objects.select_related(
        'character_class_variant', 'character_class_variant__rulebook'),
                                        slug=character_class_slug)

    assert isinstance(character_class, CharacterClass)

    # fetch primary variant, this is independent of rulebook selected
    try:
        primary_variant = CharacterClassVariant.objects.select_related(
            'rulebook',
            'rulebook__dnd_edition',
        ).filter(character_class=character_class, ).order_by(
            '-rulebook__dnd_edition__core', '-rulebook__published')[0]
    except Exception:
        primary_variant = None

    # if rulebook is supplied, select find this variant
    if rulebook_slug and rulebook_id:
        # use canonical link in head as this is more or less duplicated content
        use_canonical_link = True
        selected_variant = get_object_or_404(
            CharacterClassVariant.objects.select_related(
                'rulebook', 'character_class', 'rulebook__dnd_edition'),
            character_class__slug=character_class_slug,
            rulebook__pk=rulebook_id)

        # possible malformed/changed slug
        if rulebook_slug != selected_variant.rulebook.slug:
            return permanent_redirect_object(request, selected_variant)

        # selected variant is primary! Redirect to canonical url
        if selected_variant == primary_variant:
            return permanent_redirect_view(
                request,
                character_class_detail,
                kwargs={'character_class_slug': character_class_slug})
    else:
        # this is canonical, no need to specify it
        use_canonical_link = False
        selected_variant = primary_variant

    other_variants = [
        variant for variant in
        character_class.characterclassvariant_set.select_related(
            'rulebook', 'rulebook__dnd_edition', 'character_class').all()
        if variant != selected_variant
    ]

    if selected_variant:
        required_races = selected_variant.required_races.select_related(
            'race', 'race__rulebook').all()
        required_skills = selected_variant.required_skills.select_related(
            'skill').all()
        required_feats = selected_variant.required_feats.select_related(
            'feat', 'feat__rulebook').all()
        display_3e_warning = is_3e_edition(
            selected_variant.rulebook.dnd_edition)
    else:
        required_races = ()
        required_skills = ()
        required_feats = ()
        display_3e_warning = False

    return render_to_response(
        'dnd/character_classes/character_class_detail.html',
        {
            'character_class': character_class,
            'request': request,
            'i_like_it_url': request.build_absolute_uri(),
            'inaccurate_url': request.build_absolute_uri(),
            'selected_variant': selected_variant,
            'required_races': required_races,
            'required_skills': required_skills,
            'required_feats': required_feats,
            'other_variants': other_variants,
            'use_canonical_link': use_canonical_link,
            'display_3e_warning': display_3e_warning,
        },
        context_instance=RequestContext(request),
    )
示例#15
0
def home(request):

    context = RequestContext(request, {'user': request.user})
    return render_to_response('home.html', context_instance=context)
示例#16
0
def elastic_results(request, pk):
    """
    This view handles the results page.
    """
    try:
        url = DynamicElasticityOutputUrl.objects.get(pk=pk)
    except:
        raise Http404

    taxcalc_vers_disp = get_version(url, 'taxcalc_vers', TAXCALC_VERSION)
    webapp_vers_disp = get_version(url, 'webapp_vers', WEBAPP_VERSION)

    context_vers_disp = {'taxcalc_version': taxcalc_vers_disp,
                         'webapp_version': webapp_vers_disp}

    model = url.unique_inputs
    if model.tax_result:
        output = model.tax_result
        first_year = model.first_year
        created_on = model.creation_date
        tables = elast_results_to_tables(output, first_year)
        hostname = os.environ.get('BASE_IRI', 'http://www.ospc.org')
        microsim_url = hostname + "/taxbrain/" + str(url.unique_inputs.micro_sim.pk)

        context = {
            'locals':locals(),
            'unique_url':url,
            'taxcalc_version':taxcalc_vers_disp,
            'webapp_version':webapp_vers_disp,
            'tables':tables,
            'created_on':created_on,
            'first_year':first_year,
            'microsim_url':microsim_url
        }

        return render(request, 'dynamic/elasticity_results.html', context)

    else:

        job_ids = model.job_ids
        jobs_to_check = model.jobs_not_ready
        if not jobs_to_check:
            jobs_to_check = normalize(job_ids)
        else:
            jobs_to_check = normalize(jobs_to_check)

        try:
            jobs_ready = dropq_compute.dropq_results_ready(jobs_to_check)
        except JobFailError as jfe:
            print jfe
            return render_to_response('taxbrain/failed.html')

        if any([j == 'FAIL' for j in jobs_ready]):
            failed_jobs = [sub_id for (sub_id, job_ready) in
                           zip(jobs_to_check, jobs_ready) if job_ready == 'FAIL']

            #Just need the error message from one failed job
            error_msgs = dropq_compute.dropq_get_results([failed_jobs[0]], job_failure=True)
            error_msg = error_msgs[0]
            val_err_idx = error_msg.rfind("Error")
            error = ErrorMessageTaxCalculator()
            error_contents = error_msg[val_err_idx:].replace(" ","&nbsp;")
            error.text = error_contents
            error.save()
            model.error_text = error
            model.save()
            return render(request, 'taxbrain/failed.html', {"error_msg": error_contents})


        if all([job == 'YES' for job in jobs_ready]):
            model.tax_result = dropq_compute.elastic_get_results(normalize(job_ids))
            model.creation_date = datetime.datetime.now()
            model.save()
            return redirect(url)

        else:
            jobs_not_ready = [sub_id for (sub_id, job_ready) in
                                zip(jobs_to_check, jobs_ready) if not job_ready == 'YES']
            jobs_not_ready = denormalize(jobs_not_ready)
            model.jobs_not_ready = jobs_not_ready
            model.save()
            if request.method == 'POST':
                # if not ready yet, insert number of minutes remaining
                exp_comp_dt = url.exp_comp_datetime
                utc_now = datetime.datetime.utcnow()
                utc_now = utc_now.replace(tzinfo=pytz.utc)
                dt = exp_comp_dt - utc_now
                exp_num_minutes = dt.total_seconds() / 60.
                exp_num_minutes = round(exp_num_minutes, 2)
                exp_num_minutes = exp_num_minutes if exp_num_minutes > 0 else 0
                if exp_num_minutes > 0:
                    return JsonResponse({'eta': exp_num_minutes}, status=202)
                else:
                    return JsonResponse({'eta': exp_num_minutes}, status=200)

            else:
                print "rendering not ready yet"
                context = {'eta': '100'}
                context.update(context_vers_disp)
                return render_to_response('dynamic/not_ready.html', context, context_instance=RequestContext(request))
def caipin(request, org_id):
    template_var = {}
    try:
        template_var['org'] = org = Organization.objects.get(slug=org_id)
    except:
        template_var['org'] = org = Organization.objects.get(pk=org_id)

    if request.method == "POST":
        try:
            action = request.POST['action']
            if action == "sync_menuitem":
                inv_sync = cache.get("inv_sync_%s" % (org_id, ))
                if inv_sync is None:
                    cache.set("inv_sync_%s" % (org_id, ), 1, 60 * 5)
                else:
                    return HttpResponse(simplejson.dumps(
                        {'message': _(u'同步请求已发送,稍候请刷新查看更新数据')}),
                                        mimetype='application/json')
                try:

                    r = requests.post(
                        CENTER_URL + "/capi/sync_menuitem_stock/",
                        data={
                            'guid':
                            org.org_guid,
                            'host':
                            getattr(conf.settings, 'DEFAUT_URL',
                                    'http://stock.sandypos.com').strip('/')
                        },
                        timeout=300)
                    print 'sync menu_item by save info,guid:%s,status:%s' % (
                        org.org_guid, r.status_code)
                    if not r.text:
                        return HttpResponse(simplejson.dumps(
                            {'message': _(u'云端似乎没有您的收银注册记录')}),
                                            mimetype='application/json')
                except:
                    print traceback.print_exc()

                return HttpResponse(simplejson.dumps(
                    {'message': _(u'同步请求已发送,稍候请刷新查看更新数据')}),
                                    mimetype='application/json')

            elif action == "delete":
                tag = request.POST['tag']
                mid = request.POST['mid']

                menuItem = MenuItem.objects.get(pk=mid)
                menuItem.status = 0
                menuItem.save()

                return HttpResponse(simplejson.dumps({
                    'success': 1,
                    'tag': int(tag)
                }),
                                    mimetype='application/json')
        except:
            print traceback.print_exc()
    else:
        template_var['keyword'] = request.GET.get('keyword', '')
        template_var['categorys'] = CategoryPos.objects.filter(
            org=org, processing=0).values_list('id', 'parent_id',
                                               'name')  #simplejson.dumps()

    return render_to_response("simple/caipin.html",
                              template_var,
                              context_instance=RequestContext(request))
示例#18
0
def behavior_results(request, pk):
    """
    This view handles the partial equilibrium results page.
    """
    try:
        url = DynamicBehaviorOutputUrl.objects.get(pk=pk)
    except:
        raise Http404

    taxcalc_vers_disp = get_version(url, 'taxcalc_vers', TAXCALC_VERSION)
    webapp_vers_disp = get_version(url, 'webapp_vers', WEBAPP_VERSION)

    context_vers_disp = {'taxcalc_version': taxcalc_vers_disp,
                         'webapp_version': webapp_vers_disp}

    model = url.unique_inputs
    if model.tax_result:

        output = model.tax_result
        first_year = model.first_year
        created_on = model.creation_date
        if 'fiscal_tots' in output:
            # Use new key/value pairs for old data
            output['aggr_d'] = output['fiscal_tots']
            output['aggr_1'] = output['fiscal_tots']
            output['aggr_2'] = output['fiscal_tots']
            del output['fiscal_tots']

        tables = taxcalc_results_to_tables(output, first_year)
        tables["tooltips"] = {
            'distribution': DISTRIBUTION_TOOLTIP,
            'difference': DIFFERENCE_TOOLTIP,
            'payroll': PAYROLL_TOOLTIP,
            'income': INCOME_TOOLTIP,
            'base': BASE_TOOLTIP,
            'reform': REFORM_TOOLTIP,
            'bins': INCOME_BINS_TOOLTIP,
            'deciles': INCOME_DECILES_TOOLTIP
        }
        is_registered = True if request.user.is_authenticated() else False
        hostname = os.environ.get('BASE_IRI', 'http://www.ospc.org')
        microsim_url = hostname + "/taxbrain/" + str(model.micro_sim.pk)

        # TODO: Fix the java script mapping problem.  There exists somewhere in
        # the taxbrain javascript code a mapping to the old table names.  As
        # soon as this is changed to accept the new table names, this code NEEDS
        # to be removed.
        tables['fiscal_change'] = add_summary_column(tables.pop('aggr_d'))
        tables['fiscal_currentlaw'] = add_summary_column(tables.pop('aggr_1'))
        tables['fiscal_reform'] = add_summary_column(tables.pop('aggr_2'))
        tables['mY_dec'] = tables.pop('dist2_xdec')
        tables['mX_dec'] = tables.pop('dist1_xdec')
        tables['df_dec'] = tables.pop('diff_itax_xdec')
        tables['pdf_dec'] = tables.pop('diff_ptax_xdec')
        tables['cdf_dec'] = tables.pop('diff_comb_xdec')
        tables['mY_bin'] = tables.pop('dist2_xbin')
        tables['mX_bin'] = tables.pop('dist1_xbin')
        tables['df_bin'] = tables.pop('diff_itax_xbin')
        tables['pdf_bin'] = tables.pop('diff_ptax_xbin')
        tables['cdf_bin'] = tables.pop('diff_comb_xbin')
        json_table = json.dumps(tables)

        context = {
            'locals':locals(),
            'unique_url':url,
            'tables': json_table,
            'created_on': created_on,
            'first_year': first_year,
            'is_registered': is_registered,
            'is_behavior': True,
            'microsim_url': microsim_url,
            'results_type': "behavioral"
        }
        context.update(context_vers_disp)
        return render(request, 'taxbrain/results.html', context)

    else:

        job_ids = model.job_ids
        jobs_to_check = model.jobs_not_ready
        if not jobs_to_check:
            jobs_to_check = normalize(job_ids)
        else:
            jobs_to_check = normalize(jobs_to_check)

        try:
            jobs_ready = dropq_compute.dropq_results_ready(jobs_to_check)
        except JobFailError as jfe:
            print jfe
            return render_to_response('taxbrain/failed.html')

        if all([job == 'YES' for job in jobs_ready]):
            results = dropq_compute.dropq_get_results(normalize(job_ids))
            model.tax_result = results
            model.creation_date = datetime.datetime.now()
            model.save()
            return redirect('behavior_results', url.pk)
        else:
            jobs_not_ready = [sub_id for (sub_id, job_ready) in
                                zip(jobs_to_check, jobs_ready) if not job_ready == 'YES']
            jobs_not_ready = denormalize(jobs_not_ready)
            model.jobs_not_ready = jobs_not_ready
            model.save()
            if request.method == 'POST':
                # if not ready yet, insert number of minutes remaining
                exp_comp_dt = url.exp_comp_datetime
                utc_now = datetime.datetime.utcnow()
                utc_now = utc_now.replace(tzinfo=pytz.utc)
                dt = exp_comp_dt - utc_now
                exp_num_minutes = dt.total_seconds() / 60.
                exp_num_minutes = round(exp_num_minutes, 2)
                exp_num_minutes = exp_num_minutes if exp_num_minutes > 0 else 0
                if exp_num_minutes > 0:
                    return JsonResponse({'eta': exp_num_minutes}, status=202)
                else:
                    return JsonResponse({'eta': exp_num_minutes}, status=200)

            else:
                print "rendering not ready yet"
                context = {'eta': '100'}
                context.update(context_vers_disp)
                return render_to_response('dynamic/not_ready.html', context, context_instance=RequestContext(request))
def import_from_pos(request, org_id):
    template_var = {}
    try:
        template_var['org'] = org = Organization.objects.get(slug=org_id)
    except:
        template_var['org'] = org = Organization.objects.get(pk=org_id)

    if request.method == "GET":
        template_var['categorys'] = Category.objects.filter(
            org=org).values_list('id', 'parent_id', 'name')
        template_var['categorys_pos'] = CategoryPos.objects.filter(
            org=org, processing=0).values_list('id', 'parent_id', 'name')

        return render_to_response('simple/import_from_pos.html',
                                  template_var,
                                  context_instance=RequestContext(request))
    else:
        from_pos_category_list = request.POST.get('from_pos_category').split(
            ',')
        print isinstance(from_pos_category_list, list)
        for categoryPos_id in from_pos_category_list:
            print 'abcd'
            try:

                category = Category.objects.get(pk=request.POST['to_category'])
                categoryPos = CategoryPos.objects.get(pk=int(categoryPos_id))
                auto_reduce = int(request.POST['auto_reduce'])
                keep_tree = int(request.POST['keep_tree'])

                menuItems = MenuItem.objects.filter(
                    categoryPos__in=categoryPos.get_descendants(
                        include_self=True))

                if keep_tree:
                    child_categoryPos = categoryPos.get_descendants(
                        include_self=True)
                    main_category, created = Category.objects.get_or_create(
                        parent=category,
                        name=categoryPos.name,
                        org=org,
                        defaults={'user': request.user})

                    for categoryPos in child_categoryPos:
                        scategory, created = Category.objects.get_or_create(
                            parent=(categoryPos.id == int(categoryPos_id))
                            and category or main_category,
                            name=categoryPos.name,
                            org=org,
                            defaults={'user': request.user})

                        _menuItems = menuItems.filter(categoryPos=categoryPos)
                        for _menuItem in _menuItems:
                            unit = None
                            if _menuItem.unit:
                                unit, created = Unit.objects.get_or_create(
                                    unit=_menuItem.unit,
                                    good__isnull=True,
                                    org=org)
                            goods, created = Goods.objects.get_or_create(
                                name=_menuItem.item_name,
                                category=scategory,
                                org=org,
                                defaults={
                                    'unit':
                                    unit,
                                    'abbreviation':
                                    get_abbreviation(_menuItem.item_name),
                                    'sale_price_ori':
                                    _menuItem.price,
                                    'sale_price':
                                    _menuItem.price,
                                    'last_modify_user':
                                    request.user
                                })

                            if auto_reduce:
                                MenuItemDetail.objects.get_or_create(
                                    org=org,
                                    menuItem=_menuItem,
                                    good=goods,
                                    weight=1,
                                    goods_unit=goods.unit)

                                weight = 1
                                good_unit = goods.unit
                                standard_weight = goods.change_nums(
                                    weight, good_unit)

                                _menuItem.cost = standard_weight * goods.refer_price
                                _menuItem.profit = _menuItem.price - _menuItem.cost
                                _menuItem.percent1 = _menuItem.cost and (
                                    _menuItem.price - _menuItem.cost
                                ) * 100.0 / _menuItem.cost or 0
                                _menuItem.percent2 = _menuItem.price and (
                                    _menuItem.price - _menuItem.cost
                                ) * 100.0 / _menuItem.price or 0
                                _menuItem.sync_type = 1
                                _menuItem.save()
                else:
                    for _menuItem in menuItems:
                        unit = None
                        if _menuItem.unit:
                            unit, created = Unit.objects.get_or_create(
                                unit=_menuItem.unit,
                                good__isnull=True,
                                org=org)
                        goods, created = Goods.objects.get_or_create(
                            name=_menuItem.item_name,
                            category=category,
                            org=org,
                            defaults={
                                'unit':
                                unit,
                                'abbreviation':
                                get_abbreviation(_menuItem.item_name),
                                'sale_price':
                                _menuItem.price,
                                'last_modify_user':
                                request.user
                            })

                        if auto_reduce:
                            MenuItemDetail.objects.get_or_create(
                                org=org,
                                menuItem=_menuItem,
                                good=goods,
                                weight=1,
                                goods_unit=goods.unit)

                            weight = 1
                            good_unit = goods.unit
                            standard_weight = goods.change_nums(
                                weight, good_unit)

                            _menuItem.cost = standard_weight * goods.refer_price
                            _menuItem.profit = _menuItem.price - _menuItem.cost
                            _menuItem.percent1 = _menuItem.cost and (
                                _menuItem.price -
                                _menuItem.cost) * 100.0 / _menuItem.cost or 0
                            _menuItem.percent2 = _menuItem.price and (
                                _menuItem.price -
                                _menuItem.cost) * 100.0 / _menuItem.price or 0
                            _menuItem.sync_type = 1
                            _menuItem.save()

                Category.objects.partial_rebuild(
                    Category.objects.filter(org=org)[0].tree_id)
            except Exception, e:
                print traceback.print_exc()
                return HttpResponse(simplejson.dumps({
                    'success': 0,
                    'message': e.message
                }),
                                    mimetype='application/json')
        return HttpResponse(simplejson.dumps({
            'success': 1,
            'category_id': category.id
        }),
                            mimetype='application/json')
示例#20
0
def myevents(request):
    if request.user.is_authenticated():
        events = Event.objects.filter(uid=request.user.get_user_id()).order_by('-created_on')
        context = RequestContext(request, {"events": events})
    return render_to_response('myevents.html', context)
示例#21
0
def output_detail(request, pk):
    """
    This view is the single page of diplaying a progress bar for how
    close the job is to finishing, and then it will also display the
    job results if the job is done. Finally, it will render a 'job failed'
    page if the job has failed.
    """

    try:
        url = OutputUrl.objects.get(pk=pk)
    except OutputUrl.DoesNotExist:
        raise Http404

    model = url.unique_inputs

    taxcalc_vers_disp = get_version(url, 'taxcalc_vers', TAXCALC_VERSION)
    webapp_vers_disp = get_version(url, 'webapp_vers', WEBAPP_VERSION)

    context_vers_disp = {'taxcalc_version': taxcalc_vers_disp,
                         'webapp_version': webapp_vers_disp}
    if model.tax_result:
        # try to render table; if failure render not available page
        try:
            context = get_result_context(model, request, url)
        except Exception as e:
            print('Exception rendering pk', pk, e)
            traceback.print_exc()
            edit_href = '/taxbrain/edit/{}/?start_year={}'.format(
                pk,
                model.first_year or START_YEAR  # sometimes first_year is None
            )
            not_avail_context = dict(edit_href=edit_href,
                                     **context_vers_disp)
            return render(
                request,
                'taxbrain/not_avail.html',
                not_avail_context)

        context.update(context_vers_disp)
        return render(request, 'taxbrain/results.html', context)
    elif model.error_text:
        return render(request, 'taxbrain/failed.html',
                      {"error_msg": model.error_text.text})
    else:
        job_ids = model.job_ids

        try:
            jobs_ready = dropq_compute.results_ready(job_ids)
        except JobFailError as jfe:
            print(jfe)
            return render_to_response('taxbrain/failed.html')
        print(job_ids)
        if any(j == 'FAIL' for j in jobs_ready):
            failed_jobs = [sub_id for (sub_id, job_ready)
                           in zip(job_ids, jobs_ready)
                           if job_ready == 'FAIL']

            # Just need the error message from one failed job
            error_msgs = dropq_compute.get_results([failed_jobs[0]],
                                                   job_failure=True)
            if error_msgs:
                error_msg = error_msgs[0]
            else:
                error_msg = "Error: stack trace for this error is unavailable"
            val_err_idx = error_msg.rfind("Error")
            error = ErrorMessageTaxCalculator()
            error_contents = error_msg[val_err_idx:].replace(" ", "&nbsp;")
            error.text = error_contents
            error.save()
            model.error_text = error
            model.save()
            return render(request, 'taxbrain/failed.html',
                          {"error_msg": error_contents})

        if all(j == 'YES' for j in jobs_ready):
            results = dropq_compute.get_results(job_ids)
            model.tax_result = results
            model.creation_date = timezone.now()
            model.save()
            context = get_result_context(model, request, url)
            context.update(context_vers_disp)
            return render(request, 'taxbrain/results.html', context)

        else:
            if request.method == 'POST':
                # if not ready yet, insert number of minutes remaining
                exp_comp_dt = url.exp_comp_datetime
                utc_now = timezone.now()
                dt = exp_comp_dt - utc_now
                exp_num_minutes = dt.total_seconds() / 60.
                exp_num_minutes = round(exp_num_minutes, 2)
                exp_num_minutes = exp_num_minutes if exp_num_minutes > 0 else 0
                if exp_num_minutes > 0:
                    return JsonResponse({'eta': exp_num_minutes}, status=202)
                else:
                    return JsonResponse({'eta': exp_num_minutes}, status=200)

            else:
                context = {'eta': '100'}
                context.update(context_vers_disp)
                return render_to_response(
                    'taxbrain/not_ready.html',
                    context,
                    context_instance=RequestContext(request)
                )
示例#22
0
def home(request):
    context = RequestContext(request)
    return render_to_response('home.html', context)
示例#23
0
 def render_template(self, template_string, context=None):
     response = RequestContext(HttpRequest(), context)
     return Template(template_string).render(response).strip()
示例#24
0
def customer_dashboard(request, on_index=None):
    """Customer dashboard gives the following information

        * No of Campaigns for logged in user
        * Total phonebook contacts
        * Total Campaigns contacts
        * Amount of contact reached today
        * Disposition of calls via pie chart
        * Call records & Duration of calls are shown on graph by days/hours

    **Attributes**:

        * ``template`` - frontend/dashboard.html
        * ``form`` - DashboardForm
    """
    logging.debug('Start Dashboard')
    # All campaign for logged in User
    campaign_id_list = Campaign.objects.values_list('id', flat=True)\
        .filter(user=request.user).order_by('id')
    campaign_count = campaign_id_list.count()

    # Contacts count which are active and belong to those phonebook(s) which is
    # associated with all campaign
    pb_active_contact_count = Contact.objects\
        .filter(phonebook__campaign__in=campaign_id_list, status=CONTACT_STATUS.ACTIVE)\
        .count()

    total_of_phonebook_contacts =\
        Contact.objects.filter(phonebook__user=request.user).count()

    form = DashboardForm(request.user)
    logging.debug('Got Campaign list')

    total_record = dict()
    total_duration_sum = 0
    total_call_count = 0
    total_answered = 0
    total_not_answered = 0
    total_busy = 0
    total_cancel = 0
    total_congestion = 0
    total_failed = 0
    search_type = SEARCH_TYPE.D_Last_24_hours  # default Last 24 hours
    selected_campaign = ''

    if campaign_id_list:
        selected_campaign = campaign_id_list[0]  # default campaign id

    # selected_campaign should not be empty
    if selected_campaign:
        if request.method == 'POST':
            form = DashboardForm(request.user, request.POST)
            selected_campaign = request.POST['campaign']
            search_type = request.POST['search_type']

        end_date = datetime.today()
        start_date = calculate_date(search_type)

        # date_length is used to do group by starting_date
        if int(search_type
               ) >= SEARCH_TYPE.B_Last_7_days:  # all options except 30 days
            date_length = 13
            if int(search_type) == SEARCH_TYPE.C_Yesterday:  # yesterday
                now = datetime.now()
                start_date = datetime(now.year, now.month, now.day, 0, 0, 0,
                                      0) - relativedelta(days=1)
                end_date = datetime(now.year, now.month, now.day, 23, 59, 59,
                                    999999) - relativedelta(days=1)
            if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                date_length = 16
        else:
            date_length = 10  # Last 30 days option

        select_data = {
            "starting_date":
            "SUBSTR(CAST(starting_date as CHAR(30)),1,%s)" % str(date_length)
        }

        # This calls list is used by pie chart
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                duration__isnull=False,
                user=request.user,
                starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date', 'disposition')\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall')

        for i in calls:
            total_call_count += i['starting_date__count']
            if (i['disposition'] == VOIPCALL_DISPOSITION.ANSWER
                    or i['disposition'] == 'NORMAL_CLEARING'):
                total_answered += i['starting_date__count']
            elif (i['disposition'] == VOIPCALL_DISPOSITION.BUSY
                  or i['disposition'] == 'USER_BUSY'):
                total_busy += i['starting_date__count']
            elif (i['disposition'] == VOIPCALL_DISPOSITION.NOANSWER
                  or i['disposition'] == 'NO_ANSWER'):
                total_not_answered += i['starting_date__count']
            elif (i['disposition'] == VOIPCALL_DISPOSITION.CANCEL
                  or i['disposition'] == 'ORIGINATOR_CANCEL'):
                total_cancel += i['starting_date__count']
            elif (i['disposition'] == VOIPCALL_DISPOSITION.CONGESTION
                  or i['disposition'] == 'NORMAL_CIRCUIT_CONGESTION'):
                total_congestion += i['starting_date__count']
            else:
                #VOIP CALL FAILED
                total_failed += i['starting_date__count']

        # following calls list is without disposition & group by call date
        calls = VoIPCall.objects\
            .filter(callrequest__campaign=selected_campaign,
                duration__isnull=False,
                user=request.user,
                starting_date__range=(start_date, end_date))\
            .extra(select=select_data)\
            .values('starting_date').annotate(Sum('duration'))\
            .annotate(Avg('duration'))\
            .annotate(Count('starting_date'))\
            .order_by('starting_date')

        logging.debug('Aggregate VoIPCall (2)')

        mintime = start_date
        maxtime = end_date
        calls_dict = {}
        calls_dict_with_min = {}

        for data in calls:
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                ctime = datetime(int(data['starting_date'][0:4]),
                                 int(data['starting_date'][5:7]),
                                 int(data['starting_date'][8:10]),
                                 int(data['starting_date'][11:13]), 0, 0, 0)
                if int(search_type) >= SEARCH_TYPE.E_Last_12_hours:
                    ctime = datetime(int(data['starting_date'][0:4]),
                                     int(data['starting_date'][5:7]),
                                     int(data['starting_date'][8:10]),
                                     int(data['starting_date'][11:13]),
                                     int(data['starting_date'][14:16]), 0, 0)
            else:
                ctime = datetime(int(data['starting_date'][0:4]),
                                 int(data['starting_date'][5:7]),
                                 int(data['starting_date'][8:10]), 0, 0, 0, 0)
            if ctime > maxtime:
                maxtime = ctime
            elif ctime < mintime:
                mintime = ctime

            # all options except 30 days
            if int(search_type) >= SEARCH_TYPE.B_Last_7_days:
                calls_dict[int(ctime.strftime("%Y%m%d%H"))] =\
                    {
                        'call_count': data['starting_date__count'],
                        'duration_sum': data['duration__sum'],
                        'duration_avg': float(data['duration__avg']),
                    }

                calls_dict_with_min[int(ctime.strftime("%Y%m%d%H%M"))] =\
                    {
                        'call_count': data['starting_date__count'],
                        'duration_sum': data['duration__sum'],
                        'duration_avg': float(data['duration__avg']),
                    }
            else:
                # Last 30 days option
                calls_dict[int(ctime.strftime("%Y%m%d"))] =\
                    {
                        'call_count': data['starting_date__count'],
                        'duration_sum': data['duration__sum'],
                        'duration_avg': float(data['duration__avg']),
                    }

        logging.debug('After Call Loops')

        dateList = date_range(mintime, maxtime, q=search_type)

        for date in dateList:
            inttime = int(date.strftime("%Y%m%d"))

            # last 7 days | yesterday | last 24 hrs
            if int(search_type) == SEARCH_TYPE.B_Last_7_days \
                or int(search_type) == SEARCH_TYPE.C_Yesterday \
                    or int(search_type) == SEARCH_TYPE.D_Last_24_hours:

                for option in range(0, 24):
                    day_time = int(str(inttime) + str(option).zfill(2))

                    graph_day = datetime(int(date.strftime("%Y")),
                                         int(date.strftime("%m")),
                                         int(date.strftime("%d")),
                                         int(str(option).zfill(2)))

                    dt = int(1000 * time.mktime(graph_day.timetuple()))
                    total_record[dt] = {
                        'call_count': 0,
                        'duration_sum': 0,
                        'duration_avg': 0.0,
                    }

                    if day_time in calls_dict.keys():
                        total_record[dt]['call_count'] += calls_dict[day_time][
                            'call_count']
                        total_record[dt]['duration_sum'] += calls_dict[
                            day_time]['duration_sum']
                        total_record[dt]['duration_avg'] += float(
                            calls_dict[day_time]['duration_avg'])

            # last 12 hrs | last 6 hrs | last 1 hrs
            elif (int(search_type) == SEARCH_TYPE.E_Last_12_hours
                  or int(search_type) == SEARCH_TYPE.F_Last_6_hours
                  or int(search_type) == SEARCH_TYPE.G_Last_hour):

                for hour in range(0, 24):
                    for minute in range(0, 60):
                        hr_time = int(
                            str(inttime) + str(hour).zfill(2) +
                            str(minute).zfill(2))

                        graph_day = datetime(int(date.strftime("%Y")),
                                             int(date.strftime("%m")),
                                             int(date.strftime("%d")),
                                             int(str(hour).zfill(2)),
                                             int(str(minute).zfill(2)))

                        dt = int(1000 * time.mktime(graph_day.timetuple()))
                        total_record[dt] = {
                            'call_count': 0,
                            'duration_sum': 0,
                            'duration_avg': 0.0,
                        }

                        if hr_time in calls_dict_with_min.keys():
                            total_record[dt][
                                'call_count'] += calls_dict_with_min[hr_time][
                                    'call_count']
                            total_record[dt][
                                'duration_sum'] += calls_dict_with_min[
                                    hr_time]['duration_sum']
                            total_record[dt]['duration_avg'] += float(
                                calls_dict_with_min[hr_time]['duration_avg'])
            else:
                # Last 30 days option
                graph_day = datetime(int(date.strftime("%Y")),
                                     int(date.strftime("%m")),
                                     int(date.strftime("%d")))
                dt = int(1000 * time.mktime(graph_day.timetuple()))
                total_record[dt] = {
                    'call_count': 0,
                    'duration_sum': 0,
                    'duration_avg': 0,
                }
                if inttime in calls_dict.keys():
                    total_record[dt]['call_count'] += calls_dict[inttime][
                        'call_count']
                    total_record[dt]['duration_sum'] += calls_dict[inttime][
                        'duration_sum']
                    total_record[dt]['duration_avg'] += float(
                        calls_dict[inttime]['duration_avg'])

    logging.debug('After dateList Loops')

    # sorting on date col
    total_record = total_record.items()
    total_record = sorted(total_record, key=lambda k: k[0])

    # lineplusbarwithfocuschart
    final_charttype = "linePlusBarWithFocusChart"
    xdata = []
    ydata = []
    ydata2 = []
    for i in total_record:
        xdata.append(i[0])
        ydata.append(i[1]['call_count'])
        ydata2.append(i[1]['duration_sum'])

    tooltip_date = "%d %b %y %H:%M %p"
    kwargs1 = {}
    kwargs1['bar'] = True
    extra_serie1 = {
        "tooltip": {
            "y_start": "",
            "y_end": " calls"
        },
        "date_format": tooltip_date
    }
    extra_serie2 = {
        "tooltip": {
            "y_start": "",
            "y_end": " sec"
        },
        "date_format": tooltip_date
    }

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls',
        'y1': ydata,
        'extra1': extra_serie1,
        'kwargs1': kwargs1,
        'name2': 'Duration',
        'y2': ydata2,
        'extra2': extra_serie2,
    }

    # Contacts which are successfully called for running campaign
    reached_contact = 0
    if campaign_id_list:
        now = datetime.now()
        start_date = datetime(now.year, now.month, now.day, 0, 0, 0, 0)
        end_date = datetime(now.year, now.month, now.day, 23, 59, 59, 999999)
        reached_contact = Subscriber.objects\
            .filter(campaign_id__in=campaign_id_list,  # status=5,
                    updated_date__range=(start_date, end_date))\
            .count()

    # PieChart
    hangup_analytic_charttype = "pieChart"
    xdata = []
    ydata = []
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata}
    if total_call_count != 0:
        for i in VOIPCALL_DISPOSITION:
            xdata.append(i[0])

        # Y-axis order depend upon VOIPCALL_DISPOSITION
        # 'ANSWER', 'BUSY', 'CANCEL', 'CONGESTION', 'FAILED', 'NOANSWER'
        ydata = [
            percentage(total_answered, total_call_count),
            percentage(total_busy, total_call_count),
            percentage(total_cancel, total_call_count),
            percentage(total_congestion, total_call_count),
            percentage(total_failed, total_call_count),
            percentage(total_not_answered, total_call_count),
        ]

        color_list = [
            COLOR_DISPOSITION['ANSWER'],
            COLOR_DISPOSITION['BUSY'],
            COLOR_DISPOSITION['CANCEL'],
            COLOR_DISPOSITION['CONGESTION'],
            COLOR_DISPOSITION['FAILED'],
            COLOR_DISPOSITION['NOANSWER'],
        ]

        extra_serie = {
            "tooltip": {
                "y_start": "",
                "y_end": " %"
            },
            "color_list": color_list
        }
        hangup_analytic_chartdata = {
            'x': xdata,
            'y1': ydata,
            'extra1': extra_serie
        }

    template = 'frontend/dashboard.html'
    data = {
        'module': current_view(request),
        'form': form,
        'dialer_setting_msg': user_dialer_setting_msg(request.user),
        'campaign_count': campaign_count,
        'total_of_phonebook_contacts': total_of_phonebook_contacts,
        'campaign_phonebook_active_contact_count': pb_active_contact_count,
        'reached_contact': reached_contact,
        'total_duration_sum': total_duration_sum,
        'total_call_count': total_call_count,
        'total_answered': total_answered,
        'total_not_answered': total_not_answered,
        'total_busy': total_busy,
        'total_cancel': total_cancel,
        'total_congestion': total_congestion,
        'total_failed': total_failed,
        'answered_color': COLOR_DISPOSITION['ANSWER'],
        'busy_color': COLOR_DISPOSITION['BUSY'],
        'not_answered_color': COLOR_DISPOSITION['NOANSWER'],
        'cancel_color': COLOR_DISPOSITION['CANCEL'],
        'congestion_color': COLOR_DISPOSITION['CONGESTION'],
        'failed_color': COLOR_DISPOSITION['FAILED'],
        'VOIPCALL_DISPOSITION': VOIPCALL_DISPOSITION,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_chartcontainer': 'piechart_container',
        'hangup_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'lineplusbarwithfocuschart_container',
        'final_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        }
    }
    if on_index == 'yes':
        return data
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
示例#25
0
def userActions(request):
    return render_to_response('user_templates/user_home.html', {},
                              RequestContext(request))
示例#26
0
def home(request):
    return render_to_response('cookbook.html',
                              context_instance=RequestContext(request))
示例#27
0
def viewApplication(request):
    data = dict()
    applicant = Applicant.objects.get(pk=request.user.pk)
    application = applicant.get_application()
    problem_with_application = False
    data['extra_comments'] = ''
    data['extra_onready_js'] = ''
    # Fill context dict with status reports and relevant actions
    data['online_application_status'] = COMPLETE_CELL
    data['online_application_actions'] = NO_ACTION
    # Transcripts
    data['transcripts_status'] = INCOMPLETE_CELL
    data['transcripts_actions'] = NO_ACTION
    if application.transcript_status == 0:
        data['transcripts_status'] = COMPLETE_CELL
        data['extra_comments'] += "Transcript Complete"
    elif application.transcript_status == 6:
        problem_with_application = True
    else:
        transcripts_button = "transcripts_detail_button"
        data['transcripts_actions'] = details_button(transcripts_button)
        detail_content = "Transcripts not yet received by Graduate School."
        data['extra_onready_js'] += details_js(transcripts_button,
                                               detail_content)
    # GRE scores
    data['gre_scores_status'] = INCOMPLETE_CELL
    data['gre_scores_actions'] = NO_ACTION
    if application.gre_status == 0:
        data['gre_scores_status'] = COMPLETE_CELL
        data['extra_comments'] += "GRE Complete"
    elif application.gre_status == 6:
        problem_with_application = True
    else:
        gre_button = "gre_detail_button"
        data['gre_scores_actions'] = details_button(gre_button)
        detail_content = "GRE scores not yet received by Graduate School."
        data['extra_onready_js'] += details_js(gre_button, detail_content)
    # TOEFL scores
    data['toefl_scores_status'] = INCOMPLETE_CELL
    data['toefl_scores_actions'] = NO_ACTION
    if application.toefl_status == 0:
        data['toefl_scores_status'] = COMPLETE_CELL
        data['extra_comments'] += "TOEFL Complete"
    elif application.toefl_status == 6:
        problem_with_application = True
    elif application.toefl_status == 5:
        data['toefl_scores_status'] = NA_CELL
    # References
    data['references_status'] = INCOMPLETE_CELL
    data['references_actions'] = NO_ACTION
    num_references = len(Reference.objects.filter(attached_to=application))
    if num_references < 3:
        data['references_status'] = INCOMPLETE_CELL
        button_id = "references_detail_button"
        data[
            'references_actions'] = '''<a class="btn btn-primary" href="/add_reference/"><i class="icon-pencil icon-white"></i> Add Reference</a> ''' + details_button(
                button_id)
        data['extra_comments'] += "References Incomplete"
        details_content = "References requested: " + str(
            num_references
        ) + "/3.<br/>You must receive recommendations from 3 references."
        data['extra_onready_js'] += details_js(button_id, details_content)
    else:
        references = Reference.objects.filter(attached_to=application)
        references_pending = False
        for reference in references:
            if not reference.complete:
                references_pending = True
        if references_pending:
            data['extra_comments'] += "References Pending"
            data['references_status'] = PENDING_CELL
            button_id = "references_detail_button"
            data['references_actions'] = details_button(button_id)
            details_content = "Awaiting replies from references."
            data['extra_onready_js'] += details_js(button_id, details_content)
        else:
            data['extra_comments'] += "References Complete"
            data['references_status'] = COMPLETE_CELL
    # Resume
    data['resume_status'] = INCOMPLETE_CELL
    data['resume_actions'] = NO_ACTION
    if application.resume:
        data['resume_status'] = COMPLETE_CELL
        data[
            'resume_actions'] = '''<a class='btn' href='/upload_resume/'><i class='icon-retweet'></i> Resubmit</a>'''
    if not application.resume:
        data[
            'resume_actions'] = '''<a class='btn btn-primary' href='/upload_resume/'><i class='icon-file icon-white'></i> Upload Resume</a>'''
    # Letter of intent
    data['letter_status'] = INCOMPLETE_CELL
    data['letter_actions'] = NO_ACTION
    if application.letter_of_intent:
        data['letter_status'] = COMPLETE_CELL
        data[
            'letter_actions'] = '''<a class='btn' href='/upload_letter/'><i class='icon-retweet'></i> Resubmit</a>'''
    if not application.letter_of_intent:
        data[
            'letter_actions'] = '''<a class='btn btn-primary' href='/upload_letter/'><i class='icon-file icon-white'></i> Upload Letter of Intent</a>'''

    if problem_with_application:
        messages.error(
            request,
            "There is a problem with your application. Please contact the CSSE Graduate Officer."
        )
    return render_to_response(
        'applicant_templates/view_application_template.html', data,
        RequestContext(request))
示例#28
0
def tagInstance(request, instance):
    '''
    Set a new instance tag, or delete a tag.
    '''
    try:
        # get instance
        instance = Instance.objects.get(name=instance)
    except ObjectDoesNotExist:
        raise Http404()

    # get cluster
    cluster = instance.cluster

    # get cache key
    cache_key = "cluster:%s:instance:%s:user:%s" % (
        cluster.slug, instance.name, request.user.username)
    # check if the object has been cached
    res = cache.get(cache_key)
    if res is None:
        # if not, we must see if the user requested
        # the change, has permissions to do so.
        res = False
        if (request.user.is_superuser or request.user in instance.users
                or set.intersection(set(request.user.groups.all()),
                                    set(instance.groups))):
            res = True
        cache.set(cache_key, res, 90)
        if not res:
            t = get_template("403.html")
            return HttpResponseForbidden(
                content=t.render(RequestContext(request)))

    if request.method == 'POST':
        users = []
        for user in instance.users:
            users.append("u_%s" % user.pk)
        groups = []
        for group in instance.groups:
            groups.append("g_%s" % group.pk)
        existingugtags = users + groups
        form = tagsForm(request.POST)
        if form.is_valid():
            newtags = form.cleaned_data['tags']
            newtags = newtags.split(',')
            common = list(set(existingugtags).intersection(set(newtags)))
            deltags = list(set(existingugtags) - set(common))

            if len(deltags) > 0:
                # we have tags to delete
                oldtodelete = prepare_tags(deltags)
                jobid = instance.cluster.untag_instance(
                    instance.name, oldtodelete)
                if not jobid:
                    return HttpResponse(json.dumps({
                        'result': 'failure',
                        'reason': jobid
                    }),
                                        mimetype='application/json')
            newtagstoapply = prepare_tags(newtags)

            if len(newtagstoapply) > 0:
                instance.cluster.tag_instance(instance.name, newtagstoapply)

            res = {'result': 'success'}
            return HttpResponse(json.dumps(res), mimetype='application/json')
        else:
            return render(request, 'tagging/itags.html', {
                'form': form,
                'users': users,
                'instance': instance
            })
    elif request.method == 'GET':
        form = tagsForm()
        users = []
        for user in instance.users:
            userd = {}
            userd['text'] = user.username
            userd['id'] = "u_%s" % user.pk
            userd['type'] = "user"
            users.append(userd)
        for group in instance.groups:
            groupd = {}
            groupd['text'] = group.name
            groupd['id'] = "g_%s" % group.pk
            groupd['type'] = "group"
            users.append(groupd)
        return render(request, 'tagging/itags.html', {
            'form': form,
            'users': users,
            'instance': instance
        })
示例#29
0
def viewProfile(request):
    data = dict()
    applicant = Applicant.objects.get(pk=request.user.pk)
    profile = applicant.get_gwaap_profile()
    application = applicant.get_application()
    if request.method == "POST":
        # Check for updates to selected fields, update if necessary
        if profile.street1 != request.POST['street1']:
            profile.street1 = request.POST['street1']
        if profile.street2 != request.POST['street2']:
            profile.street2 = request.POST['street2']
        if profile.city != request.POST['city']:
            profile.city = request.POST['city']
        if profile.province != request.POST['province']:
            profile.province = request.POST['province']
        if profile.state != request.POST['state']:
            profile.state = request.POST['state']
        if profile.country != request.POST['country']:
            profile.country = request.POST['country']
        if profile.zip_code != request.POST['zip_code']:
            profile.zip_code = request.POST['zip_code']
        if applicant.email != request.POST['email']:
            applicant.email = request.POST['email']  # validate?
        if profile.phone != request.POST['phone']:
            profile.phone = request.POST['phone']
        profile.save()
        applicant.save()
        messages.info(request, "Profile information updated.")
    # start
    data['applicant'] = applicant
    data['profile'] = profile
    data['application'] = application
    data['form_first_name'] = form_field(applicant.first_name)
    data['form_last_name'] = form_field(applicant.last_name)
    data['form_middle_name'] = form_field(profile.middle_name)
    # <hr/>
    data['form_street1'] = form_field(profile.street1, False, "street1")
    data['form_street2'] = form_field(profile.street2, False, "street2")
    data['form_city'] = form_field(profile.city, False, "city")
    data['form_province'] = form_field(profile.province, False, "province")
    data['form_state'] = form_field(profile.state, False, "state")
    data['form_country'] = form_field(profile.country, False, "country")
    data['form_zip_code'] = form_field(profile.zip_code, False, "zip_code")
    # <hr/>
    data['form_email'] = form_field(applicant.email, False, "email")
    data['form_phone'] = form_field(profile.phone, False, "phone")
    data['form_birthday'] = form_field(profile.birthday)
    data['form_gender'] = form_field(profile.gender)
    data['form_country_birth'] = form_field(profile.country_birth)
    data['form_citizenship'] = form_field(profile.citizenship)
    # <hr/>
    data['form_ref_number'] = form_field(profile.ref_number)
    data['form_date_apply'] = form_field(profile.date_apply)
    # <hr/>
    data['form_enter_qtr'] = form_field(profile.enter_qtr)
    data['form_enter_year'] = form_field(profile.enter_year)
    data['form_degree'] = form_field(profile.degree)
    data['form_major'] = form_field(profile.major)
    # <hr/>
    data['form_gre_taken'] = form_field(profile.gre_taken)
    data['form_o_gre_v'] = form_field(profile.o_gre_v)
    data['form_o_gre_q'] = form_field(profile.o_gre_q)
    data['form_o_gre_a'] = form_field(profile.o_gre_a)
    data['form_o_gre_w'] = form_field(profile.o_gre_w)
    data['form_toefl_taken'] = form_field(profile.toefl_taken)
    data['form_o_toefl_score'] = form_field(profile.o_toefl_score)
    return render_to_response('applicant_templates/profile_info_template.html',
                              data, RequestContext(request))
示例#30
0
def index( request ):
    return render_to_response( 'base.html', context_instance=RequestContext(request))