class Specialist(Account): @method_decorator(user_passes_test(role_admin_check())) def list(self, request, specialist_id): api = api() # Traer data para el listado data = api.get(slug='account_status/specialists/' + specialist_id, token=request.session['token']) vars_page = self.generate_header(custom_title=title_page)
class Administrator(Actor): vars_page = { 'btn_administrators_class': 'active', 'name_create_URL': 'dashboard:actor-administrators-create', } @method_decorator(user_passes_test(role_admin_check())) def list(self, request): actual_page = get_actual_page(request) arg = {"page": actual_page} obj_api = api() data = obj_api.get(slug='administrators/', arg=arg, token=request.session['token']) custom_column = { "last_name": { 'type': 'concat', 'data': {'username', 'last_name'} }, "detail": { 'type': 'detail', 'data': { 'href': 'dashboard:actor-administrators-detail', 'key': 'id' } } } lastnames_title = "{} {} {}".format(_("surnames"), _("and"), _("names")) header_table = { lastnames_title: "last_name", _("code"): "code", _("email"): "email_exact", _("RUC"): "ruc", _("category"): "", _("specialty"): "", _("detail"): "detail" } table = convert(data, header=header_table, actual_page=actual_page, custom_column=custom_column) vars_page = self.generate_header( custom_title=_('administrators').title()) return render(request, 'admin/actor/administratorsList.html', { 'table': table, 'vars_page': vars_page })
class AccountStatusSeller(AccountStatus): @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de estado de cuenta de vendedores, donde se debera filtrar para buscar las ventas de un vendedor en especifico. """ table = data_user = "" obj_api = api() token = request.session['token'] title_page = _('Seller').title() form_filters = AccountStatusSellerFormFilters(initial=request.GET, token=token) if form_filters.is_valid(): filters = form_filters.cleaned_data pk = filters['seller'] if pk: actual_page = None tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters['from_date']) filters['until_date'] = tools.date_format_to_db(date=filters['until_date']) if filters['show_sum_column']: filters['page_size'] = 0 else: actual_page = get_actual_page(request) # Traer data para el listado data = obj_api.get(slug='account_status/sellers/' + pk, arg=filters, token=token) # Columnas personalizadas, tienen mayor prioriedad que los campos que retornan de la api custom_column = { "purchase__fee__date": {'type': 'date', 'data': ('purchase__fee__date',)}, "fee_accumulated": {'type': 'format_price', 'data': ('fee_accumulated',)}, "purchase__fee__fee_amount": {'type': 'format_price', 'data': ('purchase__fee__fee_amount',)}, "purchase__total_amount": {'type': 'format_price', 'data': ('purchase__total_amount',)}, "amount_accumulated": {'type': 'format_price', 'data': ('amount_accumulated',)}, "pending_payment": {'type': 'eval', 'data': ('float(r["purchase__total_amount"]) - float(r["fee_accumulated"])',), 'next': {'type': 'format_price'}}, "count_products_c": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])<=1',), 'next': {'type': 'concat', 'data': ('count_products',)}}, "fee_accumulated_c": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])<=1',), 'next': {'type': 'concat', 'data': ('fee_accumulated',)}}, "purchase__fee__fee_amount_c": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])<=1',), 'next': {'type': 'concat', 'data': ('purchase__fee__fee_amount',)}}, "amount_accumulated_c": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])<=1',), 'next': {'type': 'concat', 'data': ('amount_accumulated',)}}, "count_products_q": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])>1',), 'next': {'type': 'concat', 'data': ('count_products',)}}, "fee_accumulated_q": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])>1',), 'next': {'type': 'concat', 'data': ('fee_accumulated',)}}, "purchase__fee__fee_amount_q": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])>1',), 'next': {'type': 'concat', 'data': ('purchase__fee__fee_amount',)}}, "amount_accumulated_q": {'type': 'if_eval', 'data': ('int(r["purchase__fee_number"])>1',), 'next': {'type': 'concat', 'data': ('amount_accumulated',)}}, "purchase_fee_amount": {'type': 'concat', 'data': ('purchase__fee__fee_amount',)}, "purchase__fee__reference_number": {'type': 'concat', 'data': ( 'purchase__fee__fee_order_number', '/', 'purchase__fee_number')}, } # Cabecera principal, los titulos de la columna seran sobrepuestos si pasa el list de cabecera multiple header_table = [(_("date"), "purchase__fee__date"), (_("type"), "is_billable"), ( _("number"), "purchase__code"), (_("code"), "purchase__client__code"), (_("nick"), "purchase__client__nick"), ( _("name"), "purchase__product__name"), (_("query amount"), "purchase__query_amount"), ( _("mounth of duration"), "purchase__product__expiration_number"), ( _("price"), "purchase__total_amount"), (_("Payments Made"), "purchase_fee_amount"), ( _("Pending payment"), "pending_payment"), ( _("advance"), "purchase__fee__reference_number"), ( "", "count_products_c"), ("", "fee_accumulated_c"), ("", "purchase__fee__fee_amount_c"), ("", "amount_accumulated_c"), ( "", "count_products_q"), ("", "fee_accumulated_q"), ("", "purchase__fee__fee_amount_q"), ("", "amount_accumulated_q"), ( "", "count_products"), ("", "fee_accumulated"), ("", "purchase__fee__fee_amount"), ("", "amount_accumulated")] # Multiples header, una lista por cada nivel de la cabecera multi_header = [ [ (_('date'), {'rowspan': '4'}), (_('reference of sale'), {'rowspan': '3', 'colspan': '2'}), (_('customer reference'), {'rowspan': '3', 'colspan': '2'}), (_('description of plans'), {'rowspan': '3', 'colspan': '3'}), (_('sales productivity'), {'rowspan': '3', 'colspan': '4'}), (_('Composition of the Sale by Form of Payment'), {'rowspan': '1', 'colspan': '12'}), ], [ (_('Cash'), {'colspan': '4'}), (_('Credit'), {'colspan': '4'}), (_('Totals'), {'colspan': '4'}), ], [ (_('units'), {'colspan': '2'}), (_('amount'), {'colspan': '2'}), (_('units'), {'colspan': '2'}), (_('amount'), {'colspan': '2'}), (_('units'), {'colspan': '2'}), (_('amount'), {'colspan': '2'}), ], [ (_('type'), {}), (_('number'), {}), (_('code'), {}), (_('Nick'), {}), (_('name'), {}), (_('N° of queries'), {}), (_('mounth of duration'), {}), (_('Price'), {}), (_('Payments Made'), {}), (_('Pending payment'), {}), (_("reference fee"), {}), (_('quantity'), {}), (_('accumulated'), {}), (_('paid out'), {}), (_('accumulated'), {}), (_('quantity'), {}), (_('accumulated'), {}), (_('paid out'), {}), (_('accumulated'), {}), (_('quantity'), {}), (_('accumulated'), {}), (_('paid out'), {}), (_('accumulated'), {}), ], ] if filters['show_sum_column']: # Lista con los valores para el footer de la tabla, posterior al cargado de la data footer = [ { 'purchase__total_amount': {'type': 'acum', 'id': 'purchase__id', 'value': 'purchase__total_amount', 'format_price': True}, 'purchase_fee_amount': {'type': 'acum', 'id': 'purchase__fee__id', 'value': 'purchase__fee__fee_amount', 'format_price': True}, 'pending_payment': {'type': 'eval', 'data': 'float(f[0]["_purchase__total_amount"])-float(f[0]["_purchase_fee_amount"])', 'format_price': True}, }, { 'purchase_fee_amount': {'type': 'eval', 'data': 'float(f[0]["_purchase_fee_amount"])/float(f[0]["_purchase__total_amount"])', 'format_price': True}, 'pending_payment': {'type': 'eval', 'data': '1-float(f[1]["_purchase_fee_amount"])', 'format_price': True}, } ] else: footer = None table = convert(data, header=header_table, actual_page=actual_page, custom_column=custom_column, multi_header=multi_header, footer=footer) data_user = obj_api.get(slug='sellers/' + pk, token=token) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/account_status/account_status_seller.html', {'vars_page': vars_page, 'table': table, 'form_filters': form_filters, 'data_user': data_user})
class Seller(Actor): _list = 'dashboard:actor-sellers-list' _delete = 'dashboard:actor-sellers-delete' _detail = 'dashboard:actor-sellers-detail' _create = 'dashboard:actor-sellers-create' _edit = 'dashboard:actor-sellers-edit' _list_clients = 'dashboard:actor-clients-list' vars_page = { 'btn_sellers_class': 'active', 'name_create_URL': _create, 'add_actor': True } @method_decorator(user_passes_test(role_admin_check())) def list(self, request): obj_api = api() actual_page = get_actual_page(request) token = request.session['token'] title_page = _('sellers').title() filters = {} form_filters = SellerFormFilters(request.GET) if form_filters.is_valid(): filters = form_filters.cleaned_data # Traer data para el listado data = obj_api.get(slug='sellers/', arg=filters, token=token) # Definimos columnas adicionales/personalizadas custom_column = { "last_name": { 'type': 'concat', 'data': ('last_name', 'first_name'), 'separator': ' ' }, "detail": { 'type': 'detail', 'data': { 'url': self._detail, 'key': 'id' } }, "advance": { 'type': 'concat', 'data': ('', ''), 'separator': '' }, #"advance": {'type': 'concat', 'data': ('count_plans_seller','quota'), 'separator': '/'}, "ubigeo": { 'type': 'concat', 'data': { 'address': ('department_name', 'province_name', 'district_name') }, 'separator': '/' }, "seeclients": { 'type': 'link', 'data': { 'url': self._list_clients, 'arguments': { 'seller': 'id' }, 'text': _('see clients') } }, } # Atributos para aplicar a la columna RUC attributes_column = {"ruc": {"class": "numeric"}} # Coloca los nombres de las cabeceras y a que columna van asociada, customColum tendra prioriedad lastnames_title = "{} {} {}".format(_("surnames"), _("and"), _("names")) header_table = [(lastnames_title, "last_name"), (_("code"), "code"), (_("email"), "email_exact"), (_("RUC"), "ruc"), (_('see portfolio'), "seeclients"), (_("ubigeo"), "ubigeo"), (_("quota"), "quota"), (_("advance"), "advance"), (_("number of plans sold"), "count_plans_seller"), (_("number of queries"), "count_queries"), (_("detail"), "detail")] table = convert(data, header=header_table, actual_page=actual_page, custom_column=custom_column, attributes_column=attributes_column) # Titulo de la vista y variables de la Clase vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/actor/sellersList.html', { 'table': table, 'vars_page': vars_page, 'form_filters': form_filters }) @method_decorator(user_passes_test(role_admin_check())) def detail(self, request, pk): obj_api = api() data = obj_api.get(slug='sellers/' + pk, token=request.session['token']) # Si la data del usuario no es valida if type(data) is not dict or 'id' not in data: raise Http404() # Titulo de la vista y variables de la Clase title_page = "{} - {}".format(_('Seller').title(), _('detail').title()) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/actor/sellersDetail.html', { 'data': data, 'vars_page': vars_page }) @method_decorator(user_passes_test(role_admin_check())) def create(self, request): """Metodo para crear Vendedores.""" obj_api = api() token = request.session["token"] # Si llega envio por POST se valida contra el SpecialistForm if request.method == 'POST': form = self.generate_form_seller(data=request.POST, files=request.FILES) if form.is_valid(): # Tomamos todo el formulario para enviarlo a la API data = form.cleaned_data data.update({ "address": { "street": data["street"], "department": data["department"], "province": data["province"], "district": data["district"], }, "username": data["email_exact"] }) result = obj_api.post(slug='sellers/', token=token, arg=data) if result and 'id' in result: if 'photo' in request.FILES: photo = {'photo': request.FILES['photo']} obj_api.put(slug='upload_photo/' + str(result['id']), token=token, files=photo) # Process success if 'img_document_number' in request.FILES: img_document_number = { 'img_document_number': request.FILES['img_document_number'] } obj_api.put(slug='upload_document/' + str(result['id']), token=token, files=img_document_number) # Process success return HttpResponseRedirect(reverse(self._list)) else: # Mostrar Errores en Form form.add_error_custom( add_errors=result ) # Agregamos errores retornados por la app para este formulario return render(request, 'admin/actor/sellersForm.html', {'form': form}) else: # Crear formulario de especialistas vacio, se traeran # datos de selecion como Categorias y Departamentos. form = self.generate_form_seller() title_page = _('create seller').title() vars_page = self.generate_header(custom_title=title_page) sellers_form = reverse(self._create) return render(request, 'admin/actor/sellersForm.html', { 'vars_page': vars_page, 'form': form, 'sellers_form': sellers_form }) def generate_form_seller(self, data=None, files=None, seller=None, form_edit=None): """ Funcion para generar traer formulario de especialistas :param data: objeto POST o dict de valores relacional :param specilist: dict que contiene los valores iniciales del usuario :param form_edit: Bolean para saber si sera un formulario para editar usuario :return: objeto Form de acuerdo a parametros """ department = province = None # Validamos que el listado este en la respuesta # si no cumple las validaciones por Default el valor sera None # Si el usuario tiene department, traemos provincia if seller and 'address' in seller and type( seller['address'] ) is dict and 'department' in seller['address']: department = seller['address']['department'] if seller and 'address' in seller and type( seller['address']) is dict and 'province' in seller['address']: province = seller['address']['province'] return SellerForm(data=data, files=files, department=department, province=province, initial=seller, form_edit=form_edit) @method_decorator(user_passes_test(role_admin_check())) def edit(self, request, pk): obj_api = api() token = request.session['token'] if request.method == 'POST': form = self.generate_form_seller(data=request.POST, form_edit=True, files=request.FILES) # check whether it's valid: if form.is_valid(): # Tomamos todo el formulario para enviarlo a la API data = form.cleaned_data data.update({ "address": { "street": data["street"], "department": data["department"], "province": data["province"], "district": data["district"], } }) # return JsonResponse(data) result = obj_api.put(slug='sellers/' + pk, token=token, arg=data) if result and 'id' in result: # Agregando foto del Usuario if 'photo' in request.FILES: photo = {'photo': request.FILES['photo']} obj_api.put(slug='upload_photo/' + pk, token=token, files=photo) # Se agrega documento del usuario if 'img_document_number' in request.FILES: img_document_number = { 'img_document_number': request.FILES['img_document_number'] } obj_api.put(slug='upload_document/' + pk, token=token, files=img_document_number) return HttpResponseRedirect(reverse(self._list)) else: # Mostrar Errores en Form form.add_error_custom( add_errors=result ) # Agregamos errores retornados por la app para este formulario return render(request, 'admin/actor/sellersForm.html', {'form': form}) else: seller = obj_api.get(slug='sellers/' + pk, token=token) form = self.generate_form_seller(seller=seller, form_edit=True) title_page = _('edit seller').title() vars_page = self.generate_header(custom_title=title_page) sellers_form = reverse(self._edit, args=(pk, )) return render(request, 'admin/actor/sellersForm.html', { 'vars_page': vars_page, 'form': form, 'sellers_form': sellers_form })
class Client(Actor): _list = 'dashboard:actor-clients-list' _delete = 'dashboard:actor-clients-delete' _detail = 'dashboard:actor-clients-detail' _create = 'dashboard:actor-clients-create' _edit = 'dashboard:actor-clients-edit' vars_page = { 'btn_clients_class': 'active', 'name_create_URL': _create, 'add_actor': False } @method_decorator(user_passes_test(role_admin_check())) def list(self, request): obj_api = api() actual_page = get_actual_page(request) token = request.session['token'] if 'page' in request.GET: filters = {'page': request.GET['page']} else: filters = {} # Traer data para el listado # data = obj_api.get(slug='clients/?page=2', arg=filters, token=token) data = obj_api.get(slug='clients/', arg=filters, token=token) # Definimos columnas adicionales/personalizadas custom_column = { "detail": { 'type': 'detail', 'data': { 'url': self._detail, 'key': 'id' } }, "business_name": { 'type': 'if_eval', 'data': ('r["business_name"]', ), 'next': { 'type': 'concat', 'data': ('business_name', ) }, 'next_elif': { 'type': 'concat', 'data': ('last_name', ' ', 'first_name') }, } } # Atributos para aplicar a la columna RUC attributes_column = { "ruc": { "class": "numeric" }, "document_number": { "class": "numeric" } } # Coloca los nombres de las cabeceras y a que columna van asociada, customColum tendra prioriedad lastnames_title = "{} / {}".format(_("names"), _("business name")) header_table = [(lastnames_title, "business_name"), (_("alias"), "nick"), (_("code"), "code"), (_("email"), "email_exact"), (_("identification document"), "document_number"), (_("RUC"), "ruc"), (_("querys"), ""), (_("detail"), "detail")] table = convert(data, header=header_table, actual_page=actual_page, custom_column=custom_column, attributes_column=attributes_column) # Titulo de la vista y variables de la Clase title_page = _('clients').title() vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/actor/clientsList.html', { 'table': table, 'vars_page': vars_page }) @method_decorator(user_passes_test(role_admin_check())) def detail(self, request, pk): obj_api = api() data = obj_api.get(slug='clients/' + pk, token=request.session['token']) # Si la data del usuario no es valida if type(data) is not dict or 'id' not in data: raise Http404() # Titulo de la vista y variables de la Clase title_page = "{} - {}".format( _('Cliente').title(), _('detail').title()) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/actor/clientsDetail.html', { 'data': data, 'vars_page': vars_page }) @method_decorator(user_passes_test(role_admin_check())) def create(self, request): pass @method_decorator(user_passes_test(role_admin_check())) def edit(self, request, pk): obj_api = api() token = request.session['token'] if request.method == 'POST': form = self.generate_form_client(data=request.POST, form_edit=True, files=request.FILES) # check whether it's valid: if form.is_valid(): # Tomamos todo el formulario para enviarlo a la API data = form.cleaned_data data.update({ "address": { "street": data["street"], "department": data["department"], "province": data["province"], "district": data["district"], } }) # return JsonResponse(data) result = obj_api.put(slug='clients/' + pk, token=token, arg=data) if result and 'id' in result: # Agregando foto del Usuario if 'photo' in request.FILES: photo = {'photo': request.FILES['photo']} obj_api.put(slug='upload_photo/' + pk, token=token, files=photo) # Se agrega documento del usuario if 'img_document_number' in request.FILES: img_document_number = { 'img_document_number': request.FILES['img_document_number'] } obj_api.put(slug='upload_document/' + pk, token=token, files=img_document_number) return HttpResponseRedirect(reverse(self._list)) else: # Mostrar Errores en Form form.add_error_custom( add_errors=result ) # Agregamos errores retornados por la app para este formulario return render(request, 'admin/actor/clientsForm.html', {'form': form}) else: print(form.errors) print("------------------------------------") else: specilist = obj_api.get(slug='clients/' + pk, token=token) form = self.generate_form_client(specilist=specilist, form_edit=True) title_page = _('edit client').title() vars_page = self.generate_header(custom_title=title_page) specialists_form = reverse(self._edit, args=(pk, )) return render( request, 'admin/actor/clientsForm.html', { 'vars_page': vars_page, 'form': form, 'specialists_form': specialists_form }) def generate_form_client(self, data=None, files=None, specilist=None, form_edit=None): """ Funcion para generar traer formulario de especialistas :param data: objeto POST o dict de valores relacional :param specilist: dict que contiene los valores iniciales del usuario :param form_edit: Bolean para saber si sera un formulario para editar usuario :return: objeto Form de acuerdo a parametros """ department = province = None # Validamos que el listado este en la respuesta # si no cumple las validaciones por Default el valor sera None # Si el usuario tiene department, traemos provincia if specilist and 'address' in specilist and type( specilist['address'] ) is dict and 'department' in specilist['address']: department = specilist['address']['department'] if specilist and 'address' in specilist and type( specilist['address'] ) is dict and 'province' in specilist['address']: province = specilist['address']['province'] return SpecialistForm(data=data, files=files, department=department, province=province, initial=specilist, form_edit=form_edit) @method_decorator(user_passes_test(role_admin_check())) def delete(self, request): pass
class AuthorizationSpecialistMatch(Payment): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ # _detail = 'dashboard:payment-fee-form' _detail = 'dashboard:authorization-specialist-match-detail' _list = 'dashboard:authorization-specialist-match' @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() actual_page = get_actual_page(request) token = request.session['token'] title_page = _('payments').title() + " - " + _( 'match specialist').title() filters = {} table = "" form_filters = PendingPaymentFilter(request.GET) if form_filters.is_valid(): # Agregamos filtros de encontrarse alguno filters = form_filters.cleaned_data filters["status"] = 2 filters["payment_option_specialist"] = 2 # Traer data para el listado data = obj_api.get_all(slug='backend/matchs/', arg=filters, token=token) if data.status_code == 400: form_filters.add_error_custom(add_errors=data.json()) else: header_table = [ (_("date"), "date"), (_("client"), "client"), (_("specialist"), "specialist"), (_("category"), "category"), (_("detail"), "detail"), ] # Definimos columnas adicionales/personalizadas custom_column = { "date": { 'type': 'datetime', 'data': ('date', ) }, "client": { 'type': 'if_eval', 'data': ('r["client"]["business_name"]', ), 'next': { 'type': 'concat', 'data': { 'client': ('business_name', ) } }, 'next_elif': { 'type': 'concat', 'data': { 'client': ('last_name', ' ', 'first_name') } }, }, "specialist": { 'type': 'concat', 'data': { 'specialist': ('last_name', ' ', 'first_name') }, }, "detail": { 'type': 'detail', 'data': { 'url': self._detail, 'key': 'id' } } } table = convert(data.json(), header=header_table, custom_column=custom_column, actual_page=actual_page) # Titulo de la vista y variables de la Clase vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/payment/pending.html', { 'vars_page': vars_page, 'form_filters': form_filters, 'table': table }) @method_decorator(user_passes_test(role_admin_check())) def detail(self, request, pk): obj_api = api() token = request.session['token'] data = obj_api.get_all(slug='backend/matchs/' + pk, token=token) if data.status_code == 200: # Titulo de la vista y variables de la Clase title_page = _('payments').title() + " - " + _('pending').title() vars_page = self.generate_header(custom_title=title_page) data_json = data.json() if request.method == 'POST': result = obj_api.put_all(slug='confirm-discount/{}'.format(pk), token=token) if result and result.status_code == 200: return HttpResponseRedirect(reverse(self._list)) return render(request, 'admin/authorization/specialist_match.html', { 'data': data_json, 'vars_page': vars_page }) else: return HttpResponseRedirect(reverse(self._list))
class PaymentsPending(Payment): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ # _detail = 'dashboard:payment-fee-form' _detail = 'dashboard:payments-pending-detail' _list = 'dashboard:payments-pending' @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() actual_page = get_actual_page(request) token = request.session['token'] title_page = _('payments').title() + " - " + _('pending').title() filters = {} table = "" form_filters = PendingPaymentFilter(request.GET) if form_filters.is_valid(): # Agregamos filtros de encontrarse alguno filters = form_filters.cleaned_data # Traer data para el listado data = obj_api.get_all(slug='sales/payment-pending/', arg=filters, token=token) if data.status_code == 400: form_filters.add_error_custom(add_errors=data.json()) else: lastnames_title = "{} / {}".format(_("names"), _("business name")) header_table = [(_("date"), "pay_before"), (lastnames_title, "business_name"), ("total", "total_amount"), (_("fee").title(), "is_fee"), (_("detail"), "detail")] # Definimos columnas adicionales/personalizadas custom_column = { "detail": { 'type': 'detail', 'data': { 'url': self._detail, 'key': 'id' } }, "business_name": { 'type': 'if_eval', 'data': ('r["client__business_name"]', ), 'next': { 'type': 'concat', 'data': ('client__business_name', ) }, 'next_elif': { 'type': 'concat', 'data': ('client__last_name', ' ', 'client__first_name') }, }, "pay_before": { 'type': 'date', 'data': ('pay_before', ) }, "is_fee": { 'type': 'if_eval', 'data': ('r["is_fee"]', ), 'next': { 'type': 'concat', 'data': (_("yes").title(), ) }, 'next_elif': { 'type': 'concat', 'data': (_("no").title(), ) }, }, } table = convert(data.json(), header=header_table, custom_column=custom_column, actual_page=actual_page) # Titulo de la vista y variables de la Clase vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/payment/pending.html', { 'vars_page': vars_page, 'form_filters': form_filters, 'table': table }) @method_decorator(user_passes_test(role_admin_check())) def detail(self, request, pk): obj_api = api() token = request.session['token'] data = obj_api.get_all(slug='fees/payment-pending/' + pk, token=token) if data.status_code == 200: # Titulo de la vista y variables de la Clase title_page = _('payments').title() + " - " + _('pending').title() vars_page = self.generate_header(custom_title=title_page) data_json = data.json() if request.method == 'POST': form = PendingPaymentForm(data=request.POST) if form.is_valid(): data = form.cleaned_data result = obj_api.post_all(slug='payment/', token=token, arg=data) if result and result.status_code == 201: return HttpResponseRedirect(reverse(self._list)) else: # Mostrar Errores en Form # Agregamos errores retornados por la app para este formulario form.add_error_custom(add_errors=result.json()) else: payment = {} payment['bank'] = 1 payment['monthly_fee'] = data_json['id'] form = PendingPaymentForm(initial=payment) return render(request, 'admin/payment/pending_detail.html', { 'data': data_json, 'vars_page': vars_page, 'form': form }) else: return HttpResponseRedirect(reverse(self._list))
class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() # actual_page = get_actual_page(request) token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): # Agregamos filtros de encontrarse alguno filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db( date=filters['from_date']) filters['until_date'] = tools.date_format_to_db( date=filters['until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {"status": 1} obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {"status": 2} obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data) # Traer data para el listado data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [("", "code_seller"), ("", "name"), ("", "document_type_name"), ("", "document"), ("", ""), ("", ""), ("", "document"), ("", "approve"), ("", "rejected"), ("", "date_join")] # Multiples header, una lista por cada nivel de la cabecera multi_header = [ [ (_("seller code"), { 'rowspan': '2' }), (_('user'), { 'rowspan': '1', 'colspan': '3' }), (_('product'), { 'rowspan': '1', 'colspan': '2' }), (_('user code'), { 'rowspan': '2', 'colspan': '1' }), (_('validation'), { 'rowspan': '1', 'colspan': '2' }), (_('date'), { 'rowspan': '2', 'colspan': '1' }), ], [ (_('name or Social reason'), {}), (_('type document'), {}), (_('document number'), {}), (_('description'), {}), (_('Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {}), ], ] approve_column = { 'type': 'submit', 'data': { 'name': 'approve', 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve')) } } rejected_column = { 'type': 'submit', 'data': { 'name': 'rejected', 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected')) } } custom_column = { "date_join": { 'type': 'date', 'data': ('date_join', ) }, "approve": { 'type': 'if_eval', 'data': ('r["status"]=="0"', ), 'next': approve_column }, "rejected": { 'type': 'if_eval', 'data': ('r["status"]=="0"', ), 'next': rejected_column }, } table = convert(data, header=header_table, multi_header=multi_header, custom_column=custom_column) # Titulo de la vista y variables de la Clase vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', { 'table': table, 'vars_page': vars_page, 'form_filters': form_filters })