コード例 #1
0
ファイル: views.py プロジェクト: kylieCat/mail-shop
def add_customer(request):
    form = CustomerForm(request.POST)
    if all([form.is_valid(), request.POST]):
        new_user = form.save()
        new_user.save()
        return redirect('customer_view', customer_id=new_user.pk)
    context = {
        'form': form,
    }
    return render(request, 'customers/customer_form.html', context)
コード例 #2
0
ファイル: views.py プロジェクト: im-auld/mail-shop
def add_customer(request):
    form = CustomerForm(request.POST)
    if all([form.is_valid(), request.POST]):
        new_user = form.save()
        new_user.save()
        return  redirect('customer_view', customer_id=new_user.pk)
    context = {
        'form': form,
    }
    return render(request, 'customers/customer_form.html', context)
コード例 #3
0
	def test_custom_validation_rejects_customer_that_already_exists(self):
		form = CustomerForm(data={
			'name': "MyNewCustomer",
			'companies': [self.company.pk,],
			'list': self.list.pk,
			'fname': 'position',
			'reviewed_by': None,
		})
		
		self.assertFalse(form.is_valid())
		self.assertTrue(form.has_error(NON_FIELD_ERRORS, code="customerexists"))
コード例 #4
0
def new_customer():
    form = CustomerForm()

    if form.validate_on_submit():
        customer = Customer(name=form.name.data)
        db.session.add(customer)
        db.session.commit()
        flash('Customer Record Created')
        return redirect(url_for('core_bp.index'))

    return render_template('/customers/register.html', form=form)
コード例 #5
0
	def test_custom_validation_accepts_new_customer(self):
		new_company = CompanyFactory()
		form = CustomerForm(data={
			'name': "MyUniqueCustomer",
			'companies': [new_company.pk,],
			'list': self.list.pk,
			'fname': 'position',
			'reviewed_by': None,
		})
		
		self.assertTrue(form.is_valid())
コード例 #6
0
 def post(self, request):
     form = CustomerForm(request.POST)
     if form.is_valid():
         email = form.cleaned_data['email']
         password = form.cleaned_data['password1']
         new_user = User.objects.create_user(email=email,
                                             username=email,
                                             password=password)
         new_user.save()
         return HttpResponseRedirect(reverse(viewname='signup'))
     else:
         return render(request,
                       template_name=self.template_name,
                       context={self.context_object_name: form})
コード例 #7
0
ファイル: blueprint.py プロジェクト: kentaro0919/billing
def create():
    """doc."""
    if request.method == 'POST':
        form = CustomerForm(request.form)
        if form.validate():
            customer = form.save_customer(Customer())
            db.session.add(customer)
            db.session.commit()
            flash('customer "%s" created successfully.' %
                  customer.title, 'success')
            return redirect(url_for('customers.detail', slug=customer.slug))
    else:
        form = CustomerForm()

    return render_template('customers/create.html', form=form)
コード例 #8
0
ファイル: views.py プロジェクト: 2l1k/Salamat1
def me(request):
    """
    User's home.
    """
    user = request.user
    profile = user.profile
    if request.method == 'POST':
        form = CustomerForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/me/')

    return render(request, 'customers/cabinet.html', {
        'profile': profile,
        'tab': int(request.GET.get('tab', 1))
    })
コード例 #9
0
ファイル: blueprint.py プロジェクト: kentaro0919/billing
def edit(slug):
    """doc."""
    customer = Customer.query.filter(Customer.slug == slug).first_or_404()
    if request.method == 'POST':
        form = CustomerForm(request.form, obj=customer)
        if form.validate():
            customer = form.save_customer(customer)
            db.session.add(customer)
            db.session.commit()
            flash('customer "%s" created successfully.' %
                  customer.title, 'success')
            return redirect(url_for('customers.detail', slug=customer.slug))
    else:
        form = CustomerForm(obj=customer)

    return render_template('customers/edit.html', customer=customer, form=form)
コード例 #10
0
class CustomerManagement:
    _form = None
    _instance = None
    _request = None
    _store = None

    def __init__(self, request, store):
        self._request = request
        self._store = store

    def validate_form(self):
        self._form = CustomerForm(self._request.POST, self._request.FILES)
        if self._form.is_valid():
            customer = self._form.save(store=self._store)
            # save to elasticsearch
            extra_data = {}
            if customer.phone_number is not None:
                extra_data.update({"phone_number": customer.phone_number})
            if customer.address is not None:
                extra_data.update({"address": customer.address})
            if customer.email is not None:
                extra_data.update({"email": customer.email})
            elasticsearch.index_customer(customer_id=customer.id,
                                         customer_code=customer.customer_code,
                                         customer_name=customer.customer_name,
                                         group_type=customer.group_type,
                                         store_id=customer.store.id,
                                         **extra_data)
            self._instance = customer
            return self._instance
        else:
            raise FormInvalidException()

    def get_errors(self):
        errors = []
        for field in self._form:
            for error in field.errors:
                errors.append({'id': field.auto_id, 'error': error})
        return errors

    def search_customer_by_key(self, key):
        es_result = elasticsearch.search_customer(key, store_id=self._store.id)
        return {
            "num_of_results": es_result["hits"]["total"]["value"],
            "list_customers":
            [hit["_source"] for hit in es_result["hits"]["hits"]]
        }
コード例 #11
0
ファイル: views.py プロジェクト: davoshack/crm
def save_employee(request):
    # taller grabar formulario
    f = CustomerForm(request.POST)
    if f.is_valid():
        c = f.save()
        return redirect(c.company.get_absolute_url())
    else:
        data = {}
        # paso 1 - buscar la empresa!!
        company = get_object_or_404(Company, id=id_company)
        data['company'] = company
        # paso 2 - traer los clientes   
        data['customers'] = company.employees.all()

        #paso 3 - agregar formulario para agregar un nuevo cliente
        data['c_form'] = CustomerForm()
        return render_to_response('company.html', data, context_instance=RequestContext(request))
コード例 #12
0
ファイル: views.py プロジェクト: airtonix/django-simple-shop
def checkout(request, template_name="shop/checkout.html"):
    cart = get_shopping_cart(request)
    if cart.items_count() == 0:
        return redirect('shop_cart')
    customer = get_customer(request)

    c_form = CustomerForm(prefix='customer', instance=customer)
    s_form = AddressForm(prefix='shipping', instance=getattr(customer, 'shipping_address', None))
    b_form = AddressForm(prefix='billing', instance=getattr(customer, 'billing_address', None))
    
    if request.method == 'POST':
        c_form = CustomerForm(request.POST, prefix='customer', instance=customer)
        commit = True
        if c_form.is_valid():
            customer = c_form.save(commit=False)
            
            s_form = AddressForm(request.POST, prefix='shipping', instance=customer.shipping_address)
            if s_form.is_valid():
                customer.shipping_address = s_form.save(commit=False)
                if customer.same_address:
                    customer.billing_address = customer.shipping_address
                else:
                    b_form = AddressForm(request.POST, prefix='billing', instance=customer.billing_address)
                    if b_form.is_valid():
                        customer.billing_address = b_form.save(commit=False)
                    else:
                        commit = False
            else:
                commit = False
            if commit:
                customer.save()

                if not cart.customer:
                    cart.customer = customer
                cart.status = STATUS_CONFIRMED
                cart.save()
                
                return redirect('shop_confirmation')
    
    return render_to_response(template_name, {
                                'cart': cart,
                                'customerform': c_form,
                                'shippingform': s_form,
                                'billingform': b_form,
                                }, context_instance=RequestContext(request))
コード例 #13
0
ファイル: views.py プロジェクト: davoshack/crm
def company(request, id_company):
    data = {}
    # paso 1 - buscar la empresa!!
    company = get_object_or_404(Company, id=id_company)
    data['company'] = company
    # paso 2 - traer los clientes   
    data['customers'] = company.employees.all()

    #paso 3 - agregar formulario para agregar un nuevo cliente
    if request.method == 'POST':
        cf= CustomerForm(request.POST or None)
        if cf.is_valid():
            c = cf.save()
            cf = CustomerForm()
    else:
        cf= CustomerForm(initial={'company':company})
    data['c_form'] = cf
    return render_to_response('company.html', data, context_instance=RequestContext(request))
コード例 #14
0
ファイル: views.py プロジェクト: binu456m/billing
def create_customer_popup(request):

    if request.method == "POST":
        #get current shop
        shop = get_current_shop(request)
        form = CustomerForm(request.POST, request=request)

        if form.is_valid():

            #create customer_id
            customer_id = 1
            customer_obj = Customer.objects.filter(
                shop=shop).order_by("-date_added")[:1]
            if customer_obj:
                for customer in customer_obj:
                    customer_id = customer.customer_id + 1

            #create farmer
            data = form.save(commit=False)
            data.creator = request.user
            data.updater = request.user
            data.customer_id = customer_id
            data.shop = shop
            data.save()

            response_data = {
                'status': 'true',
                'message': "Customer %s Created Successfully" % (data.name),
            }

            response = HttpResponse(json.dumps(response_data),
                                    content_type='application/javascript')
            return response

        else:
            errors = generate_form_errors(form, formset=False)
            response_data = {
                'status': 'false',
                'message': errors,
            }
            response = HttpResponse(json.dumps(response_data),
                                    content_type='application/javascript')
            return response
コード例 #15
0
ファイル: views.py プロジェクト: nijotz/thesourcecoffee
def signup(request, template="customers/account_signup.html"):

    stripe_key = settings.STRIPE_PUBLIC_KEY

    subscription_form = SubscriptionForm(request.POST or None)
    customer_form = CustomerForm(request.POST or None)

    if request.method == "POST" and subscription_form.is_valid() and \
        customer_form.is_valid():

        with transaction.commit_on_success():
            save = transaction.savepoint()
            try:
                customer = customer_form.save(commit=False)
                customer.update_card(request.POST['stripeToken'])
                subscription = subscription_form.save(commit=False)
                subscription.customer = customer
                customer.save()
                subscription.save()
                transaction.savepoint_commit(save)

                if not customer.user.is_active:
                    send_verification_mail(request, customer.user, "signup_verify")
                    info(request, _("A verification email has been sent with "
                                    "a link for activating your account."))
                    return redirect(request.GET.get("next", "/"))
                else:
                    info(request, _("Successfully signed up"))
                    auth_login(request, customer.user)
                    return login_redirect(request)

            except Exception as e:
                error(request, e)
                transaction.savepoint_rollback(save)

    context = {
        'customer_form': customer_form,
        'subscription_form': subscription_form,
        'stripe_key': stripe_key,
    }

    return render(request, template, context)
コード例 #16
0
ファイル: views.py プロジェクト: sLeeNguyen/sales-support
    def get(self, request, store_name, *args, **kwargs):
        try:
            StoreManagement.valid_store_user(store_name, request.user)
        except UserNotInStoreException:
            raise Http404()

        request.session['orders'] = [{'id': 1, 'data': []}]
        customer_form = CustomerForm()
        context = {'oid': 1, 'form': customer_form, 'store_name': store_name}
        return render(request,
                      template_name='sales/sales.html',
                      context=context)
コード例 #17
0
ファイル: views.py プロジェクト: janzhou123/inventory_hub
def update(request, customer_id):
    customer = get_object_or_404(Customer, pk=customer_id)
    initial_data = {
        'city': customer.city.name,
    }

    if request.method == 'POST':
        contacts = customer.contact_list.post_dict(request.POST)
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            updated_customer = form.save()
            msg = updated_customer.contact_list.update_contacts(contacts)
            if msg:
                messages.warning(request, msg)
            messages.success(request, 'Customer updated')
    else:
        try:
            contacts = customer.contact_list.get_dict()
        except AttributeError:
            customer.save()
            contacts = {}
        form = CustomerForm(initial=initial_data, instance=customer)

    data = {
        'contacts': contacts,
        'customer': customer,
        'form': form,
    }

    return render_to_response(
        'customers/update.html',
        data,
        context_instance=RequestContext(request)
    )
コード例 #18
0
ファイル: views.py プロジェクト: janzhou123/inventory_hub
def create(request):
    if request.method == 'POST':
        contacts = ContactList.post_dict(request.POST)
        form = CustomerForm(request.POST)
        if form.is_valid():
            customer = form.save()
            msg = customer.contact_list.update_contacts(contacts)
            if msg:
                messages.warning(request, msg)
            History.created_history(customer, request.user)
            messages.success(request, 'Customer created.')
            return redirect('customers:update', customer.pk)
    else:
        contacts = {}
        form = CustomerForm()

    data = {
        'contacts': contacts,
        'form': form,
    }

    return render_to_response(
        'customers/create.html',
        data,
        context_instance=RequestContext(request),
    )
コード例 #19
0
 def validate_form(self):
     self._form = CustomerForm(self._request.POST, self._request.FILES)
     if self._form.is_valid():
         customer = self._form.save(store=self._store)
         # save to elasticsearch
         extra_data = {}
         if customer.phone_number is not None:
             extra_data.update({"phone_number": customer.phone_number})
         if customer.address is not None:
             extra_data.update({"address": customer.address})
         if customer.email is not None:
             extra_data.update({"email": customer.email})
         elasticsearch.index_customer(customer_id=customer.id,
                                      customer_code=customer.customer_code,
                                      customer_name=customer.customer_name,
                                      group_type=customer.group_type,
                                      store_id=customer.store.id,
                                      **extra_data)
         self._instance = customer
         return self._instance
     else:
         raise FormInvalidException()
コード例 #20
0
def edit_form(request,Customer_usn):
    Customer=Customer.objects.get(usn=Customer_usn)
    if request.method == "POST":
        form=CustomerForm(request.POST,instance=Customer)
        if form.is_valid():
            form.save()
            msg_html = render_to_string('email_template.html', {'Customer': Customer})
            send_mail('hotel Management System','hey','*****@*****.**',(Customer.email,),html_message=msg_html)
            return HttpResponse('<script type="text/javascript">window.close();window.opener.parent.location.reload() ;</script>')
    else:
        form=CustomerForm(instance=Customer)
    return render_to_response('edit_form.html',{"form":form,"Customer":Customer},context_instance=RequestContext(request))
コード例 #21
0
def create_order_view(request):
    customer_form = CustomerForm()
    AddressFormset = modelformset_factory(Address,
                                          extra=2,
                                          exclude=['is_default'])
    address_formset = AddressFormset(queryset=Address.objects.none())
    if request.method == "POST":
        customer_form = CustomerForm(request.POST)
        address_formset = AddressFormset(request.POST,
                                         queryset=Address.objects.none())
        if customer_form.is_valid() and address_formset.is_valid():
            # TODO update instead of create if existing
            customer = create_customer_from_forms(customer_form,
                                                  address_formset[0],
                                                  address_formset[1])
            cart = create_or_retrieve_cart(request)
            order = create_order(customer.id, cart.cartitem_set.all())
            return HttpResponseRedirect(
                reverse('orders:detail', args=(order.id, )))

    return render(request, "orders/order_display.html", {
        'customer_form': customer_form,
        'address_formset': address_formset,
    })
コード例 #22
0
ファイル: views.py プロジェクト: airtonix/django-simple-shop
def checkout(request, template_name="shop/checkout.html"):
    cart = get_shopping_cart(request)
    if cart.items_count() == 0:
        return redirect('shop_cart')
    customer = get_customer(request)

    c_form = CustomerForm(prefix='customer', instance=customer)
    s_form = AddressForm(prefix='shipping',
                         instance=getattr(customer, 'shipping_address', None))
    b_form = AddressForm(prefix='billing',
                         instance=getattr(customer, 'billing_address', None))

    if request.method == 'POST':
        c_form = CustomerForm(request.POST,
                              prefix='customer',
                              instance=customer)
        commit = True
        if c_form.is_valid():
            customer = c_form.save(commit=False)

            s_form = AddressForm(request.POST,
                                 prefix='shipping',
                                 instance=customer.shipping_address)
            if s_form.is_valid():
                customer.shipping_address = s_form.save(commit=False)
                if customer.same_address:
                    customer.billing_address = customer.shipping_address
                else:
                    b_form = AddressForm(request.POST,
                                         prefix='billing',
                                         instance=customer.billing_address)
                    if b_form.is_valid():
                        customer.billing_address = b_form.save(commit=False)
                    else:
                        commit = False
            else:
                commit = False
            if commit:
                customer.save()

                if not cart.customer:
                    cart.customer = customer
                cart.status = STATUS_CONFIRMED
                cart.save()

                return redirect('shop_confirmation')

    return render_to_response(template_name, {
        'cart': cart,
        'customerform': c_form,
        'shippingform': s_form,
        'billingform': b_form,
    },
                              context_instance=RequestContext(request))
コード例 #23
0
ファイル: views.py プロジェクト: pvanfas/crm
def edit(request, pk):
    if request.method == "POST":
        instance = get_object_or_404(Customer.objects.filter(pk=pk))
        form = CustomerForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            data = form.save(commit=False)
            data.date_updated = datetime.datetime.now()
            data.updater = request.user
            data.save()

            response_data = {
                "status":
                "true",
                "title":
                "Successfully Updated",
                "message":
                "Customer Successfully Updated.",
                "redirect":
                "true",
                "redirect_url":
                reverse('customers:customer', kwargs={"pk": data.pk})
            }
        else:
            message = generate_form_errors(form, formset=False)

            response_data = {
                "status": "false",
                "stable": "true",
                "title": "Form validation error",
                "message": message
            }

        return HttpResponse(json.dumps(response_data),
                            content_type='application/javascript')
    else:
        instance = get_object_or_404(Customer.objects.filter(pk=pk))
        form = CustomerForm(instance=instance)
        context = {
            "form": form,
            "title": "Edit Customer",
            "redirect": True,
            "url": reverse('customers:edit', kwargs={"pk": instance.pk}),
            "is_need_select_picker": True,
            "is_need_popup_box": True,
            "is_need_custom_scroll_bar": True,
            "is_need_wave_effect": True,
            "is_need_bootstrap_growl": True,
            "is_need_chosen_select": True,
            "is_need_grid_system": True,
            "is_need_datetime_picker": True,
            "is_need_animations": True,
        }

        return render(request, 'customers/entry.html', context)
コード例 #24
0
ファイル: views.py プロジェクト: pvanfas/crm
def create(request):
    if request.method == "POST":
        form = CustomerForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.save(commit=False)
            data.creator = request.user
            data.updater = request.user
            data.auto_id = get_auto_id(Customer)
            data.save()

            response_data = {
                "status":
                "true",
                "title":
                "Successfully Created",
                "message":
                "Customer Successfully Created.",
                "redirect":
                "true",
                "redirect_url":
                reverse('customers:customer', kwargs={"pk": data.pk})
            }
        else:
            message = generate_form_errors(form, formset=False)

            response_data = {
                "status": "false",
                "stable": "true",
                "title": "Form validation error",
                "message": message
            }

        return HttpResponse(json.dumps(response_data),
                            content_type='application/javascript')
    else:
        form = CustomerForm()
        context = {
            "form": form,
            "title": "Create Customer",
            "redirect": True,
            "url": reverse('customers:create'),
            "is_need_select_picker": True,
            "is_need_popup_box": True,
            "is_need_custom_scroll_bar": True,
            "is_need_wave_effect": True,
            "is_need_bootstrap_growl": True,
            "is_need_chosen_select": True,
            "is_need_grid_system": True,
            "is_need_datetime_picker": True,
            "is_need_animations": True,
        }

        return render(request, 'customers/entry.html', context)
コード例 #25
0
ファイル: views.py プロジェクト: binu456m/billing
def create_customer(request):
    if request.method == "POST":
        form = CustomerForm(request.POST, request=request)

        if form.is_valid():

            #get current shop
            shop = get_current_shop(request)

            #create customer_id
            customer_id = 1
            customer_obj = Customer.objects.filter(
                shop=shop).order_by("-date_added")[:1]
            if customer_obj:
                for customer in customer_obj:
                    customer_id = customer.customer_id + 1

            #create farmer
            data = form.save(commit=False)
            data.creator = request.user
            data.updater = request.user
            data.customer_id = customer_id
            data.shop = shop
            data.save()

            request.session['message'] = 'Form Submitted successfully'
            return HttpResponseRedirect(
                reverse('customers:view_customer', kwargs={'pk': data.pk}))

        else:
            errors = generate_form_errors(form, formset=False)
            context = {
                "form": form,
                "title": "Error",
                "errors": errors,
                "customers_active": "active"
            }

        return render(request, 'customers/entry_customer.html', context)

    else:
        form = CustomerForm()

        context = {
            "form": form,
            "title": "Create Customer",
            "url": reverse('customers:create_customer'),
            "redirect": True,
            "customers_active": "active"
        }
        return render(request, 'customers/entry_customer.html', context)
コード例 #26
0
ファイル: views.py プロジェクト: fogcitymarathoner/rma
def assign_customer_to_site_new_customer(request, id):

    if request.method == 'GET':
        site = Customer.objects.get(pk=id)
        site_rmas = Rma.objects.filter(customer=site)
        customer_name_form = CustomerForm()
        site_form = CustomerSiteIdNameForm(instance=site)
        return render(request,
                      'operations/edit_site_new_customer.html', {
                          'site': site,
                          'customer_name_form': customer_name_form,
                          'site_form': site_form,
                          'site_rmas': site_rmas
                      },
                      context_instance=RequestContext(request))

    if request.method == 'POST':
        site = Customer.objects.get(pk=id)
        error_count = 0
        customer_name_form = CustomerForm(request.POST)
        site_form = CustomerSiteIdNameForm(request.POST, instance=site)
        site_rmas = Rma.objects.filter(customer=site)
        if site_form.is_valid() is not True:
            error_count += 1
        if customer_name_form.is_valid() is not True:
            error_count += 1

        if error_count > 0:
            return render(request,
                          'operations/edit_site_new_customer.html', {
                              'site': site,
                              'customer_name_form': customer_name_form,
                              'site_form': site_form,
                              'site_rmas': site_rmas,
                          },
                          context_instance=RequestContext(request))
        else:
            new_customer = customer_name_form.save()
            new_customer_site = Customer()
            new_customer_site.name = site_form.cleaned_data['name']
            new_customer_site.customer = new_customer
            new_customer_site.save()

            return HttpResponseRedirect(
                reverse('view_customer_site_to_reassign',
                        kwargs={'id': new_customer_site.id}))
コード例 #27
0
ファイル: views.py プロジェクト: binu456m/billing
def edit_customer(request, pk):
    instance = get_object_or_404(
        Customer.objects.filter(pk=pk, is_deleted=False))

    if request.method == "POST":
        response_data = {}
        form = CustomerForm(request.POST,
                            instance=instance,
                            request=request,
                            edit=True)

        if form.is_valid():

            #update customer
            data = form.save(commit=False)
            data.updater = request.user
            data.date_updated = datetime.datetime.now()
            data.save()

            request.session['message'] = 'Form Edited successfully'
            return HttpResponseRedirect(
                reverse('customers:view_customer', kwargs={'pk': data.pk}))
        else:
            errors = generate_form_errors(form, formset=False)
            context = {
                "form": form,
                "title": "Update Customer",
                "customers_active": "active"
            }

        return render(request, 'customers/entry_customer.html', context)

    else:
        form = CustomerForm(instance=instance)

        context = {
            "form": form,
            "title": "Edit customer : " + instance.name,
            "instance": instance,
            "customers_active": "active"
        }
        return render(request, 'customers/entry_customer.html', context)
コード例 #28
0
def customer(request):
    customers = Customer.objects.all()

    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            customer = form.save()
            History.created_history(customer, request.user)
            return redirect('quotations:create', customer.pk)
    else:
        form = CustomerForm()

    data = {
        'customers': customers,
        'form': form,
    }

    return render_to_response(
        'quotations/customer.html',
        data,
        context_instance=RequestContext(request),
    )
コード例 #29
0
ファイル: views.py プロジェクト: mag-chang/django_sample_app
def customer_edit(request, customer_id=None):
    """
    顧客を新規作成/編集する
    """

    if customer_id:
        customer = get_object_or_404(Customer, pk=customer_id)
    else:
        customer = Customer()

    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            customer = form.save(commit=False)
            customer.save()
            return redirect('customers:list')
    else:
        form = CustomerForm(instance=customer)

    return render(
        request,
        'customers/edit.html',
        dict(form=form, customer_id=customer_id)
    )
コード例 #30
0
ファイル: views.py プロジェクト: nijotz/thesourcecoffee
def signup(request):

    # Necessary data for page
    stripe_key = settings.STRIPE_PUBLIC_KEY
    subscription_form = SubscriptionForm(request.POST or None)
    customer_form = CustomerForm(request.POST or None)
    gift_form = GiftSubscriptionForm(request.POST or None)
    plans = Plan.objects.jsonify_for_form()
    code_check_url = reverse("gifts_check_code")
    invite_code = request.GET.get("invite_code", "")
    reward_code_form = RewardCodeForm(request.POST or None, initial={"invite_code": invite_code})

    context = {
        "customer_form": customer_form,
        "subscription_form": subscription_form,
        "gift_form": gift_form,
        "reward_code_form": reward_code_form,
        "stripe_key": stripe_key,
        "plans": plans,
        "gift_purchase": request.POST.get("gift_purchase"),
        "code_check_url": code_check_url,
        "gift_code": request.POST.get("code"),
    }

    # Shortcut for initial page load
    if request.method != "POST":
        return context

    # Validate forms, handle gift if necessary
    if subscription_form.is_valid():
        if subscription_form.cleaned_data["amount"] == "0.125":
            plan = Plan.objects.get(trial=True)
        else:
            plan = Plan.objects.get(
                amount=subscription_form.cleaned_data["amount"], interval=subscription_form.cleaned_data["interval"]
            )
        context["plan"] = plan
    else:
        return context

    if context.get("gift_purchase") and gift_form.is_valid():
        return gift_purchase(request, context)

    if context.get("gift_code") and customer_form.is_valid():
        return gift_redeem(request, context)

    if not customer_form.is_valid():
        return context

    if not reward_code_form.is_valid():
        return context

    # Attempt normal subscription signup
    with transaction.commit_on_success():
        save = transaction.savepoint()
        try:
            customer = customer_form.save(commit=False).customer
            customer.update_card(request.POST["stripeToken"])
            customer.save()

            subscription = Subscription(customer=customer, plan=plan)
            subscription.save()

            transaction.savepoint_commit(save)

            form_invite_code = reward_code_form.cleaned_data["invite_code"]
            if form_invite_code != "" and form_invite_code != None:
                inv_code_instance = InviteCode.objects.filter(code=form_invite_code)
                if inv_code_instance.exists():
                    inv = inv_code_instance.get()
                    inv.customer.grant_reward(customer)

            if not customer.user.is_active:
                send_verification_mail(request, customer.user, "signup_verify")
                info(request, _("A verification email has been sent with " "a link for activating your account."))
                return redirect(request.GET.get("next", "/"))
            else:
                info(request, _("Successfully signed up"))
                auth_login(request, customer.user)
                return redirect(reverse("customers_home"))

        except Exception as e:
            transaction.savepoint_rollback(save)
            error(request, e)

    return context
コード例 #31
0
def edit_sale(request, pk):
    current_shop = get_current_shop(request)
    instance = get_object_or_404(Sale.objects.filter(pk=pk, is_deleted=False))
    customer_form = CustomerForm()

    SaleProductFormset = inlineformset_factory(
        Sale,
        SaleProduct,
        can_delete=True,
        extra=0,
        min_num=1,
        validate_min=True,
        exclude=('shop', 'sale'),
        widgets={
            'product':
            autocomplete.ModelSelect2(url='products:product-autocomplete',
                                      attrs={
                                          'data-placeholder':
                                          '*Select Product',
                                          'data-minimum-input-length': 1
                                      }),
            'quantity':
            TextInput(attrs={
                'placeholder': '*Enter quantity',
                'class': 'required form-control'
            }),
            'unit_price':
            TextInput(
                attrs={
                    'placeholder': 'Enter unit price(inc. tax)',
                    'label': '*Unit price',
                    'class': 'required form-control'
                }),
            'output_gst':
            TextInput(attrs={
                'placeholder': 'Output GST',
                'class': 'required form-control'
            }),
            'offer':
            TextInput(attrs={
                'placeholder': 'Enter Discount',
                'class': 'required form-control'
            }),
            'amount':
            TextInput(attrs={
                'placeholder': 'Enter amount',
                'class': 'required form-control'
            }),
            'tax_amount':
            TextInput(attrs={
                'placeholder': 'Tax amount',
                'class': 'required form-control'
            }),
            'total_amount':
            TextInput(
                attrs={
                    'placeholder': 'Enter total amount',
                    'class': 'required form-control'
                }),
        },
        error_messages={
            'product': {
                'required': _("Product field is required."),
            },
            'unit_price': {
                'required': _("Unit Price field is required."),
            },
            'quantity': {
                'required': _("Quantity field is required."),
            },
        })

    if request.method == "POST":
        form = SaleForm(request.POST, instance=instance)
        sale_product_formset = SaleProductFormset(
            request.POST, prefix='sale_product_formset', instance=instance)

        error_messages = ''

        if form.is_valid() and sale_product_formset.is_valid():

            #check product availability
            for f in sale_product_formset:
                product = f.cleaned_data['product']
                quantity = f.cleaned_data['quantity']

                # previous sale quantity taken
                if SaleProduct.objects.filter(pk=f.instance.pk).exists():
                    saleform = SaleProduct.objects.get(pk=f.instance.pk)
                    pre_product = saleform.product
                    pre_quantity = saleform.quantity

                    if pre_product == product:
                        available_stock = Product.objects.get(
                            shop=current_shop, pk=product.pk).stock
                        new_stock = available_stock + pre_quantity
                        if new_stock < quantity:
                            error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % (
                                product, available_stock)
                    else:
                        available_stock = Product.objects.get(
                            shop=current_shop, pk=product.pk).stock
                        if available_stock < quantity:
                            error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % (
                                product, available_stock)

                else:
                    available_stock = 0

                    #check product availability
                    if product:
                        available_stock = Product.objects.get(
                            shop=current_shop, pk=product.pk).stock
                    if available_stock < quantity:
                        error_messages += "%s is out of stock. Only %s unit(s) exists. </br >" % (
                            product, available_stock)
            if not error_messages:

                #update item
                data = form.save(commit=False)
                data.updater = request.user
                data.date_updated = datetime.datetime.now()
                data.save()

                if sale_product_formset.deleted_forms:
                    for deleted_form in sale_product_formset.deleted_forms:
                        new_stock = deleted_form.instance.product.stock + deleted_form.instance.quantity
                        Product.objects.filter(
                            pk=deleted_form.instance.product.pk,
                            is_deleted=False).update(stock=new_stock)

                #save SaleProduct
                for form in sale_product_formset:
                    product = form.cleaned_data['product']
                    unit_price = form.cleaned_data['unit_price']
                    quantity = form.cleaned_data['quantity']
                    offer = form.cleaned_data['offer']
                    output_gst = form.cleaned_data['output_gst']
                    tax_amount = form.cleaned_data['tax_amount']
                    amount = form.cleaned_data['amount']

                    # previous sale quantity taken
                    if SaleProduct.objects.filter(
                            pk=form.instance.pk).exists():
                        saleform = SaleProduct.objects.get(pk=form.instance.pk)
                        pre_product = saleform.product
                        pre_quantity = saleform.quantity

                        if pre_product == product:
                            current_stock = Product.objects.get(
                                pk=product.pk, shop=current_shop).stock
                            Product.objects.filter(pk=product.pk,
                                                   shop=current_shop).update(
                                                       stock=current_stock +
                                                       pre_quantity - quantity)
                        else:
                            current_stock = pre_product.stock
                            Product.objects.filter(
                                pk=pre_product.pk,
                                shop=current_shop).update(stock=current_stock +
                                                          pre_quantity)
                            current_product_stock = product.stock
                            product.stock = current_product_stock - quantity
                            product.save()

                    else:
                        current_stock = Product.objects.get(
                            pk=product.pk, shop=current_shop).stock
                        Product.objects.filter(
                            pk=product.pk,
                            shop=current_shop).update(stock=current_stock -
                                                      quantity)

                #update sale product fomset forms
                sale_product_formset.save()

                request.session['message'] = 'Form Submitted successfully'
                return HttpResponseRedirect(
                    reverse('sales:view_sale', kwargs={'pk': data.pk}))

            else:
                context = {
                    "form": form,
                    "customer_form": customer_form,
                    "title": "Edit Sale : " + instance.sale_id,
                    "sale_product_formset": sale_product_formset,
                    "errors": error_messages,
                    "sales_active": "active"
                }
                return render(request, 'sales/entry_sale.html', context)

        else:
            error_messages = generate_form_errors(form, formset=False)
            error_messages += generate_form_errors(sale_product_formset,
                                                   formset=True)
            context = {
                "form": form,
                "customer_form": customer_form,
                "title": "Edit Sale : " + instance.sale_id,
                "sale_product_formset": sale_product_formset,
                "errors": error_messages,
                "sales_active": "active"
            }
            return render(request, 'sales/entry_sale.html', context)

    else:
        form = SaleForm(instance=instance)
        sale_product_formset = SaleProductFormset(
            prefix='sale_product_formset', instance=instance)
        for field in sale_product_formset:
            field.fields['product'].queryset = Product.objects.filter(
                shop=current_shop, is_deleted=False)

        context = {
            "form": form,
            "customer_form": customer_form,
            "sale_product_formset": sale_product_formset,
            "title": "Edit Sale : " + instance.sale_id,
            "url": reverse('sales:edit_sale', kwargs={'pk': instance.pk}),
            "sales_active": "active"
        }
        return render(request, 'sales/entry_sale.html', context)
コード例 #32
0
def create_sale(request):
    SaleProductFormset = formset_factory(SaleProductForm,
                                         min_num=1,
                                         validate_min=True,
                                         extra=0)
    current_shop = get_current_shop(request)
    customer_form = CustomerForm()

    if request.method == "POST":

        form = SaleForm(request.POST)

        sale_product_formset = SaleProductFormset(
            request.POST, prefix='sale_product_formset')
        for field in sale_product_formset:
            field.fields['product'].queryset = Product.objects.filter(
                shop=current_shop, is_deleted=False)

        if form.is_valid() and sale_product_formset.is_valid():

            sale_id = 'OFF/1'
            sale_obj = Sale.objects.filter(
                shop=current_shop).order_by("-date_added")[:1]
            if sale_obj:
                for sale in sale_obj:
                    sale_id = 'OFF/' + str(
                        int(re.findall(r'\d+', sale.sale_id)[0]) + 1)

            error_messages = ''
            #check product availability
            for f in sale_product_formset:
                product = f.cleaned_data['product']
                quantity = f.cleaned_data['quantity']

                available_stock = 0

                #check product availability
                if Product.objects.filter(shop=current_shop,
                                          pk=product.pk).exists():
                    available_stock = Product.objects.get(shop=current_shop,
                                                          pk=product.pk).stock
                if available_stock < quantity:
                    error_messages += "%s is out of stock. Only %s unit(s) exists in %s . </br >" % (
                        product, available_stock, current_shop)

            if not error_messages:

                customer = form.cleaned_data['customer']

                #create sale
                data = form.save(commit=False)
                data.creator = request.user
                data.updater = request.user
                data.sale_id = sale_id
                data.shop = current_shop
                data.date_added = datetime.datetime.now()
                data.save()

                #save SaleProduct
                for form in sale_product_formset:
                    product = form.cleaned_data['product']
                    unit_price = form.cleaned_data['unit_price']
                    quantity = form.cleaned_data['quantity']
                    offer = form.cleaned_data['offer']
                    output_gst = form.cleaned_data['output_gst']
                    tax_amount = form.cleaned_data['tax_amount']
                    amount = form.cleaned_data['amount']
                    total_amount = form.cleaned_data['total_amount']
                    SaleProduct(product=product,
                                sale=data,
                                unit_price=unit_price,
                                quantity=quantity,
                                output_gst=output_gst,
                                offer=offer,
                                tax_amount=tax_amount,
                                amount=amount,
                                total_amount=total_amount).save()

                    current_stock = Product.objects.get(
                        pk=product.pk, shop=current_shop).stock
                    updated_stock = current_stock - quantity
                    Product.objects.filter(
                        pk=product.pk,
                        shop=current_shop).update(stock=updated_stock)

                    if updated_stock == 0:
                        create_notification(product, current_shop)

                request.session['message'] = 'Form Submitted successfully'
                return HttpResponseRedirect(
                    reverse('sales:view_sale', kwargs={'pk': data.pk}))
            else:
                context = {
                    "form": form,
                    "customer_form": customer_form,
                    "title": "Create Sale",
                    "sale_product_formset": sale_product_formset,
                    "errors": error_messages,
                    "sales_active": "active"
                }
                return render(request, 'sales/entry_sale.html', context)
        else:
            errors = generate_form_errors(form, formset=False)
            errors += generate_form_errors(sale_product_formset, formset=True)
            context = {
                "form": form,
                "customer_form": customer_form,
                "title": "Create Sale",
                "sale_product_formset": sale_product_formset,
                "errors": errors,
                "sales_active": "active"
            }
            return render(request, 'sales/entry_sale.html', context)

    else:
        form = SaleForm()
        sale_product_formset = SaleProductFormset(
            prefix='sale_product_formset')

        context = {
            "form": form,
            "customer_form": customer_form,
            "title": "Create Sale",
            "sale_product_formset": sale_product_formset,
            "url": reverse('sales:create_sale'),
            "sales_active": "active"
        }
        return render(request, 'sales/entry_sale.html', context)