示例#1
0
def create_customer(
    user_id: int,
    shop_id: int,
    consume_amount: float = 0,
    consume_count: int = 0,
    point: float = 0,
    remark: str = "",
):
    """
    创建客户
    :param user_id:
    :param shop_id:
    :param consume_amount:
    :param consume_count:
    :param point:
    :param remark:
    :return:
    """
    customer = Customer(
        shop_id=shop_id,
        user_id=user_id,
        consume_amount=consume_amount,
        consume_count=consume_count,
        point=point,
        remark=remark,
    )
    customer.save()
    return customer
示例#2
0
    def handle(self, *args, **options):
        email = input('Set email: ')
        password = input('Set password: '******'Company name: ')
        if not email or not password or not company_name:
            raise ValueError('Please, set correct input values.')
        try:
            validators.validate_email(email)
        except exceptions.ValidationError:
            print("Enter valid email address.")
        try:
            with transaction.atomic():

                # create user from input info
                email = email.lower()
                customer = Customer(email=email)
                customer.set_password(password)
                customer.save()

                # create User's profile and set all needed info regarding redshift output storage
                profile, created = Profile.objects.get_or_create(
                    user=customer, defaults={"company_name": company_name})
                profile.rs_username = profile.username_generator()
                profile.rs_password = profile.password_generator()
                profile.save()

                # prepare DB in redshift output storage for newly created user
                self.prepare_rs_db(user_info=profile)
        except IntegrityError:
            print("User or profile entry already exists.")
示例#3
0
def save_profile(backend, user, response, *args, **kwargs):

    if backend.name == 'facebook':

        try:
            customer = user.get_customer()
        except:
            customer = None
        if customer is None:
            user.is_customer = True
            user.save()
            customer = Customer(user_id=user.id)
            try:
                customer.birthday = datetime.datetime.strptime(
                    response['birthday'], '%m/%d/%Y').strftime('%Y-%m-%d')
            except:
                pass
            try:
                url = "http://graph.facebook.com/%s/picture?type=large" \
                    % response["id"]
                if url:
                    from urllib.request import urlopen, HTTPError
                    from django.template.defaultfilters import slugify
                    from django.core.files.base import ContentFile
                    avatar = urlopen(url)
                    customer.profile_picture.save(
                        slugify(user.username + " social") + '.jpg',
                        ContentFile(avatar.read()))
            except HTTPError:
                pass
            customer.save()
            Activity.push(user, 201,
                          user.username + ' is register with facebook')
        Activity.push(user, 101,
                      user.username + ' log in as customer with facebook.')
示例#4
0
def index(request):
    if (request.method == "GET"):
        all_objects = [*User.objects.all(), *Customer.objects.all()]
        customerJson = serializers.serialize('json', all_objects)

        # print(customerJson)
        customerJson = json.loads(customerJson)
        for customer in customerJson:
            print(customer)

        return HttpResponse(status=200)

    elif (request.method == "POST"):
        body = json.loads(request.body.decode('utf-8'))

        name = body['username']
        country = body['country']
        phone = body['phone']

        #test fields
        if not name or not country or not phone:
            return HttpResponse("Some Are Fields not satisfied\n", status=400)

        #assume that a user is a customer
        user = User(username=name)
        user.save()

        #test country check
        if not checkCountry(body['country']):
            return HttpResponse("Country not found\n", status=400)

        cus = Customer(user=user, country=country, phone=phone)
        cus.save()

        return HttpResponse("Saved \n")
示例#5
0
def welcome(request):
    if request.method == "POST":
        user = User.objects.get(username=request.user.username)
        license_number = request.POST.get("license_number")
        fname = request.POST.get("fname")
        lname = request.POST.get("lname")
        number = request.POST.get("number")
        city = request.POST.get("city")
        nickname = request.POST.get("nickname")
        about = request.POST.get("about")
        address = request.POST.get("address")
        user.first_name = fname
        user.last_name = lname
        user.number = number
        user.save()
        customer = Customer(user=user,
                            phone=number,
                            city=city,
                            address=address,
                            nickname=nickname,
                            license_number=license_number,
                            about=about,
                            terms_condition=True)
        customer.save()
        message_to_company(email=user.email,
                           message="someone signed up yay!! :)",
                           name=fname,
                           phone=number,
                           subject="Leads Team Rock and Roll")

        Pay.objects.filter(user=user).update(firstname=fname, phone=number)

        return redirect("customer:user_page")
    return render(request, "register/welcome.html")
示例#6
0
    def update_or_create_customer_from_order(self, order, mission_instance):
        buyer_name = order.get("BuyerName")
        buyer_mail = order.get("BuyerEmail")

        if buyer_mail is None or buyer_mail == "":
            return

        customer_instance = Customer.objects.filter(
            contact__first_name_last_name=buyer_name,
            contact__email=buyer_mail).first()

        if customer_instance is None:
            contact = Contact(email=buyer_mail,
                              first_name_last_name=buyer_name)
            contact.save()
            customer_instance = Customer(contact=contact)
            customer_instance.save()
        else:
            customer_instance.email = buyer_mail
            customer_instance.first_name_last_name = buyer_name
            customer_instance.save()

        if mission_instance.customer is None:
            mission_instance.customer = customer_instance
        return customer_instance
示例#7
0
def newSelling(request):
    if request.method == 'POST':
        form = SellingForm(request.POST, request.FILES)
        if form.is_valid():
            package = Package.objects.get(package_id=form.cleaned_data.get('package_id'))
            total_price= package.price + (package.price*7/100)
            # -----------------cusForm-------------------
            cus = Customer(
                cus_id="",
                fname=form.cleaned_data.get('cus_fname'),
                lname=form.cleaned_data.get('cus_lname'),
                address=form.cleaned_data.get('cus_address'),
                province=form.cleaned_data.get('cus_province'),
                zipcode=form.cleaned_data.get('cus_zipcode'),
                id_card=form.cleaned_data.get('cus_id_card'),
                phone=form.cleaned_data.get('cus_phone'),
                email=form.cleaned_data.get('cus_email')
            )
            cus.save()
            this_cus = Customer.objects.latest('id')
            print(this_cus)
            # -------emp---------------
            employee = Employee.objects.get(user=request.user.id)
            # ------------car-----------------
            car = Car(
                car_id="",
                car_number=form.cleaned_data.get('car_number'),
                province=form.cleaned_data.get('car_province'),
                brand=form.cleaned_data.get('car_brand'),
                chassis_number=form.cleaned_data.get('car_chassis_number'),
                model=form.cleaned_data.get('car_model'),
                car_cc=form.cleaned_data.get('car_cc'),
                car_type=form.cleaned_data.get('car_type'),
                sit=form.cleaned_data.get('car_sit'))
            car.save()
            this_car = Car.objects.latest('id')
            print(this_car)
            # ---------------Tranfer-----------------------
            tran = Tranfer(
                emp_id=employee,
                Package_id=package,
                balance=total_price,
                pic_balance=form.cleaned_data['pic_balance'])
            tran.save()
            doc_nbr = uuid.uuid4().hex[:12].upper()
            ins = Insure(doc_nbr=doc_nbr, agent_code=employee,
                         package_id=package,
                         car_id=this_car, car_number=this_car.car_number,
                         cus_id=this_cus,
                         company_order=package.company_name,
                         price=package.price, total_price=total_price,
                         post_date=date.today())
            ins.save()
            your_ins = Insure.objectslatest('id')
            # messages.success(request, f'ได้รับข้อมูลกรมธรรม์แล้ว อยู่ระหว่างการรออนุมัติกรมธรรม์')
            messages.success(request, f'ออกกรมธรรม์สำเร็จแล้ว <a href="/"></a>')
            return HttpResponseRedirect('/')
    else:
        form = SellingForm()
    return render(request, 'insurance/newSelling.html', {'form': form})
示例#8
0
def signUpView(request):
    # Checking If the User is already Logged In
    if (request.user.is_authenticated):
        checkAndRedirect(request.user)
    if (request.method == 'POST'):
        form = forms.SignUpForm(request.POST)
        if (form.is_valid()):
            # print()
            instance = form.save(commit=False)
            # Only after instance is saved We can access id
            instance.save()

            # Creating Profile Instance for the new user
            profileInstance = models.Profile(user=instance)
            profileInstance.save()

            # Creating Customer Instance for the new user
            customerInstance = Customer(user=instance)
            customerInstance.save()

            user = authenticate(request,
                                username=form.cleaned_data['username'],
                                password=form.cleaned_data['password1'])
            if (user):
                login(request, user)
                return HttpResponseRedirect(reverse('customer:landing'))
    else:
        form = forms.SignUpForm()

    context = {
        'form': form,
        'cartc': 0,
    }
    return render(request, 'accounts/signup.html', context)
示例#9
0
    def test_save(self):
        cust = Customer()
        cust.name = "test name"
        cust.zipcode = 666
        cust.save()

        self.assertEquals(cust.id, 1)
示例#10
0
 def add_customer(cls, *, phone: str, name: str, sex: str):  # 如何防止重复
     try:
         _ = CustomerProxy(phone)
     except CustomerDoesNotExistError:
         Checker.phone(phone).name(name).sex(sex)
         customer = Customer()
         customer.cus_name, customer.cus_phone, customer.cus_sex = name, phone, sex
         customer.save()
示例#11
0
def given_are_the_following_Customers_in_the_Database(step):
    raw_input("")
    try:
        for customer_dict in step.hashes:
            customer = Customer(**customer_dict)
            customer.save()
    except Exception, e:
        assert False, "An Exception was raised"
示例#12
0
def webhook(request):
    '''
        Webhook view for outlook, this is called when new notification is recieved from outlook
    '''
    content = ''
    if "validationToken" in request.GET:
        content = request.GET.get("validationToken")
    else:
        jsondata = request.body.decode("utf-8")
        notificaiton = json.loads(jsondata)
        if "value" in notificaiton and len(notificaiton["value"]) > 0:
            if "resourceData" in notificaiton["value"][0]:
                message_id = notificaiton["value"][0]["resourceData"]["id"]
                # Getting the cache
                if "subscriptionId" in notificaiton["value"][0]:
                    subscription_id = notificaiton["value"][0][
                        "subscriptionId"]
                    #result = _get_token_from_cache_with_subscription_id(request)
                    cache, outlook_cache = _get_outlook_cache_for_subscription_id(
                        subscription_id)
                    if cache and outlook_cache:

                        result = _get_token_from_cache(cache,
                                                       outlook_cache.user_id)

                        if "error" in result:
                            print("ERROR in Webhook")

                        current_token = result["access_token"]
                        mail = outlook_requests.fetch_message_by_message_id(
                            message_id, current_token)

                        if not "error" in mail:
                            customer_details = scrapper.scrap_customer_info_from_form(
                                mail)
                            # try:
                            creator_id = outlook_cache.user_id
                            creator = User.objects.filter(id=creator_id)
                            if (len(customer_details.keys())):
                                if (len(creator)):
                                    customer_details["creator"] = creator[0]

                                new_customer = Customer(**customer_details)
                                new_customer.save()
                                requirement = Requirement(
                                    customer=new_customer, status="CREATED")
                                requirement.save()
                                credit_card = CreditCard(customer=new_customer)
                                credit_card.save()
                                outlook_cache.new_message = True
                                outlook_cache.save()
                            # except:
                            #     pass
                        else:
                            print(mail["error"])

    return HttpResponse(content=content, content_type="text/plain", status=200)
示例#13
0
  def post(self, request, format=None):
    if not request.data or 'token' not in request.data or 'email' not in request.data:
      return Response('Credentials not provided', status=status.HTTP_400_BAD_REQUEST)

    raw_token = request.data['token']
    email = request.data['email']

    """
    Steps:
    1. Verify the token and user
    2. Create new token manually and pass back
    """
    token_parts = raw_token.split('.')
    if len(token_parts) != 3:
      return Response('Invalid token', status=status.HTTP_400_BAD_REQUEST)

    encoded_header = token_parts[0]
    encoded_payload = token_parts[1]
    signature = token_parts[2]

    decoded_header = json.loads(base64_decode(encoded_header))
    decoded_payload = json.loads(base64_decode(encoded_payload))

    validate_outlook_token_header(decoded_header)
    validate_outlook_token_lifetime(decoded_payload)
    validate_outlook_token_audience(decoded_payload)
    validate_outlook_token_version(decoded_payload)
    unique_identifier = vaildate_outlook_token_signature_and_get_unique_identifier(raw_token, decoded_payload)
    """
    Once the unique is obtained. Create User and Outlook User instances
    """
    try:
      user = User.objects.get(email=email)
      outlook_user = OutlookUser.objects.get(unique_identifier=unique_identifier)
      customer = user.customer_profile
    except User.DoesNotExist:
      user = User.objects.create_user(email)
      
      # Save user's name
      first_name = request.data.get('first_name', '')
      last_name = request.data.get('last_name', '')
      user.first_name = first_name
      user.last_name = last_name
      user.save()
      
      outlook_user = OutlookUser(unique_identifier=unique_identifier, user=user)
      outlook_user.save()
      customer = Customer(user=user)
      customer.save()
    except OutlookUser.DoesNotExist:
      return Response('Invalid Outlook credentials', status=status.HTTP_403_FORBIDDEN)
    except Exception as e:
      return Response(e, status=status.HTTP_403_FORBIDDEN)

    jwt_token = get_user_jwt_token(user)

    return Response({'token': jwt_token, 'id': customer.id}, status.HTTP_200_OK)
示例#14
0
 def create(self, validated_data):
     customer = Customer(
         email=validated_data['email'],
         nickname=validated_data['nickname'],
         shipping_address=validated_data['shipping_address'],
     )
     customer.set_password(validated_data['password'])
     customer.save()
     return customer
示例#15
0
 def save_new_customer(self, billing_form, delivery_form):
     contact = Contact()
     billing_address = billing_form.save()
     delivery_address = delivery_form.save()
     contact.billing_address = billing_address
     contact.delivery_address = delivery_address
     contact.save()
     customer = Customer()
     customer.contact = contact
     customer.save()
示例#16
0
def update_customer_remark(customer: Customer, remark: str):
    """
    更改客户备注
    :param customer:
    :param remark:
    :return:
    """
    customer.remark = remark
    customer.save()
    return True, ""
示例#17
0
def customer_create(request):
    params = json.loads(request.body.decode("utf-8"))
    data = {}

    blacklist = Blacklist.objects.all()
    for man in blacklist:
        nameRatio = fuzz.partial_ratio(man.name, params['name'])
        nationRatio = fuzz.partial_ratio(man.nationality, params['nation'])
        addrRatio = fuzz.partial_ratio(man.address, params['address'])
        print(nameRatio, addrRatio, nationRatio)
        if (nameRatio > 70 or addrRatio > 80
                or (nameRatio + nationRatio) > 170):
            log = AlertLog()
            log.name = params['name']
            log.operate = '開戶'
            log.reason = '疑似為高風險或黑名單人物'
            log.save()
            return common_response(data, message='黑名單人物')

    try:
        with transaction.atomic():
            distrcit = District.objects.get(id=params['district']['id'])
            customer = Customer()
            customer.name = params['name']
            customer.roc_id = params['roc_id']
            customer.gender = params['gender']
            customer.birthday = params['birthday']
            customer.cell_phone = params['cell_phone']
            customer.address = params['address']
            customer.district = distrcit
            customer.password = get_sha256_value(params['cell_phone'])
            customer.email = params['email']
            customer.save()
            data['id'] = customer.id

            # 產生帳戶號碼
            code = generate_16_digits_code()
            exist_codes = [account.code for account in Account.objects.all()]
            while code in exist_codes:
                code = generate_16_digits_code()

            # 新增帳戶
            account = Account()
            account.code = code
            account.customer = Customer.objects.get(id=customer.id)

            # 預設第1筆(新台幣)
            currency_list = Currency.objects.filter(id=1)
            if len(currency_list) != 0:
                account.currency = currency_list[0]
            account.save()

        return common_response(data)
    except Exception as e:
        return common_response(data, message=str(e))
示例#18
0
 def post(self, request, format = None):
     serializer = CustomerSerializer(data = request.data)
     if serializer.is_valid():
         user = User(first_name = serializer.data['first_name'], \
                     last_name = serializer.data['last_name'],   \
                     username = serializer.data['username'],     \
                     email = serializer.data['email'])
         user.save()
         customer = Customer(user = user, city = serializer.data['city'])
         customer.save()
         return Response(serializer.data, status = status.HTTP_201_CREATED)
     return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
示例#19
0
 def create(self, validated_data):
     customer = Customer(
       name=validated_data['name'],
       mobile_number=validated_data['mobile_number'],
       email=validated_data['email'],
       car_company=validated_data['car_company'],
       car_fuel=validated_data['car_fuel'],
       car_year=validated_data['car_year']
     )
     customer.save()
     return customer
     
示例#20
0
def add_customer_details(request):

    if request.method == 'POST':
        customer = Customer()
        name = request.POST.get('name')
        mail = request.POST.get('email')
        phone_number = request.POST.get('contact')
        address = request.POST.get('comment')
        customer.name = name
        customer.mail = mail
        customer.phone_number = phone_number
        customer.address = address
        customer.save()
    return render(request, 'add_customer_details.html', {})
示例#21
0
 def create(self, validated_data):
     username = validated_data['username']
     email = validated_data['email']
     password = validated_data['password']
     user_obj = User(
         username=username,
         email=email,
     )
     customer_obj = Customer(username=username)
     customer_obj.save()
     service_obj = Service(username=username)
     service_obj.save()
     user_obj.set_password(password)
     user_obj.save()
     return validated_data
 def save(self, customer):
     customer_id = customer.idCustomer
     first_name = customer.name.name
     last_name = customer.name.last_name
     username = f'{first_name}.{last_name}_{uuid.uuid4()}'
     user = User.objects.create_user(
         username=username,
         first_name=first_name,
         last_name=last_name
     )
     customer_db = CustomerDb()
     customer_db.customer_id = customer_id
     customer_db.user = user
     customer_db.person_number = customer.person_number.person_number
     customer_db.contact_number = customer.contact_number.phone_number
     customer_db.save()
    def mutate(self, info, user_data):
        user = get_user_model()(username=user_data.username,
                                email=user_data.email,
                                first_name=user_data.first_name,
                                last_name=user_data.last_name)
        user.set_password(user_data.password)
        user.save()
        customer = Customer(user=user, phone=user_data.phone)
        customer.save()
        address = Address(customer=customer,
                          street=user_data.street,
                          city=user_data.city,
                          country=user_data.country,
                          zip_code=user_data.zip_code)
        address.save()

        return CreateUser(user=customer)
示例#24
0
def createCustomer(request):
    fName = request.POST.get('customerFirstName')
    lastName = request.POST.get('customerLastName')
    Email = request.POST.get('customerEmail')
    Password = request.POST.get('customerPassword')
    query_set = list(Customer.objects.all().filter(email=Email))
    # if returned query set empty -> user not in DB so create the user and add to DB
    if not query_set:
        customer_obj = Customer(firstName=fName,
                                lastName=lastName,
                                email=Email,
                                password=Password)
        customer_obj.save()
        # return control to login-page for new user to login using his/her info
        return render(request, 'customer/login.html')
    else:
        return render(request, 'customer/sign_up.html')
示例#25
0
def st_wh_customer_creation(request):
    endpoint_secret = settings.STRIPE_WHS_PAYMENT_SUCCESS
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None

    try:
        event = stripe.Webhook.construct_event(payload, sig_header,
                                               endpoint_secret)

    except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)

    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return HttpResponse(status=400)

    # Handle the checkout.session.completed event
    if event['type'] == 'customer.created':
        st_customer = event['data']['object']

        # Retrieve Orders
        orders = CustomerOrder.objects.filter(
            st_customer_id=st_customer.get("id"))

        # Retrieve the customer
        customer = Customer.objects.filter(
            email=st_customer.get("email"),
            stripe_customer_id=st_customer.get("id")).first()

        if not customer:
            for order in orders:
                tg_customer = Customer(
                    email=st_customer.get("email"),
                    stripe_customer_id=st_customer.get("id"),
                )
                tg_customer.save()

                order.customer = tg_customer
                order.save()

            return HttpResponse(status=200)

        else:
            return HttpResponse(status=400)
示例#26
0
def createCustomer(request):
    try:
        form = ApiHelper.getData(request)

        # username = form['username'] if 'username' in form else ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))

        password = form['password'] if 'password' in form else '123'
        first_name = form['first_name']
        last_name = form['last_name']
        female = False if form['female'] == 'false' else True
        phone_number = form['phone_number']
        username = phone_number  #form['username']
        date_of_birth = dt_class.strptime(
            form['date_of_birth'],
            '%Y-%m-%d') if 'date_of_birth' in form else None
        address = form['address'] if 'address' in form else None

        account = createAccount(username, None, password)

        if not account:
            return JsonResponse({
                'code': 100,
                'data': 'Tên tài khoản đã tồn tại!'
            })

        user_created = User.objects.filter(username="******").first()

        customer = Customer(
            first_name=first_name,
            last_name=last_name,
            female=female,
            phone_number=phone_number,
            date_of_birth=date_of_birth,
            address=address,
            account=account,
            created_date=timezone.now(),
            created_by=user_created,
        )
        customer.save()

        return ApiHelper.Response_ok("Success")
    except Exception as e:
        print(e)
        # print(traceback.format_exc())
        return ApiHelper.Response_error()
示例#27
0
 def post(self, request, format=None):
     serializer = CustomerSerializer(data=request.data)
     if serializer.is_valid():
         logger.info('Creating user %s started' %
                     serializer.data['username'])
         user = User(first_name = serializer.data['first_name'], \
                     last_name = serializer.data['last_name'],   \
                     username = serializer.data['username'],     \
                     email = serializer.data['email'])
         user.set_password(serializer.data['password'])
         user.save()
         customer = Customer(user=user,
                             city=serializer.data['city'],
                             phone=serializer.data['phone'])
         customer.save()
         create_confirmations(customer)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#28
0
def addCustomer(request):
    customer_id = request.POST.get('customer_id')
    customer_name = request.POST.get('customer_name')
    customer_mobile = request.POST.get('customer_mobile')
    customer_email = request.POST.get('customer_email')
    customer_username = request.POST.get('customer_username')
    customer_password = request.POST.get('customer_password')
    customer_address = request.POST.get('customer_address')
    customer_pwd_hash = make_password(customer_password)
    add_customer = Customer(customer_id=customer_id,
                            customer_name=customer_name,
                            customer_mobile=customer_mobile,
                            customer_email=customer_email,
                            customer_username=customer_username,
                            customer_password=customer_pwd_hash,
                            customer_address=customer_address)
    add_customer.save()
    return showCustomer(request)
示例#29
0
文件: views.py 项目: jj116/PiggyBack
    def post(self, request, **kwargs):
        order = Order()
        order.product_name = request.session['productTitle']
        order.product_url = request.session['url']
        order.fee = float(request.session['productCost'])*0.15
        order.status = "Finding a traveller"
        order.creation_time = timezone.now()
        order.save()

        user = User.objects.get(pk=request.user.pk)

        customer = Customer()
        customer.order = order
        customer.user = user
        customer.city = request.session['city']
        customer.save()

        messages.info(request, "Payment successful! We'll notify you when we find a traveller for you!")
        return redirect('HomePage')
示例#30
0
def customer_create(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)

        email = data['email']
        firstname = data['firstname']
        lastname = data['lastname']
        password = data['password']

        customer = Customer(email=email,
                            first_name=firstname,
                            last_name=lastname,
                            password=hashlib.sha256(password).hexdigest(),
                            username=email)
        customer.save()

        serializerCustomer = CustomerSerializer(customer)

        return JsonResponse(serializerCustomer.data, status=201)
def saveCustomerDetailsDB(dataObj):
    try:

        customerDetailsobjs = getCustomerDetailsDB(dataObj['custregmobile'])

        if len(customerDetailsobjs) == 0:

            customerDetailsobj = Customer(
                custregmobile=dataObj['custregmobile'],
                custstatusold=dataObj['custstatusold'],
                custstatus=dataObj['custstatus'],
                custcountrycode=dataObj['custcountrycode'],
                createddt=datetime.datetime.now(),
                updateddt=datetime.datetime.now())

            customerDetailsobj.save()

    except Exception as e:
        logging.error("Error in saving customer details DB " + str(e))
        raise
示例#32
0
def add_customer_view(request):
    form = CustomerForm()
    if request.method == "POST":
        new_customer = Customer(name=request.POST['name'],
                                phone=request.POST['phone'])
        new_customer.save()
        order_obj = Repair_order(customer_id=new_customer)
        order_obj.save()
        base_url = reverse('repair:AddI')  # 1 /addItem/
        query_string = urlencode({
            'phone': request.POST['phone'],
            'order': order_obj.id
        })  # 2 phone=011
        url = '{}?{}'.format(
            base_url, query_string
        )  # concatenate to this form  /addItem/?phone=011&order=1

        return redirect(url)
    else:
        context = {'form': form}
    return render(request, 'repair/addCustomer.html', context)
示例#33
0
def __get_customer_contact(request):
    try:
        customer = Customer.objects.get(email=request.POST['email'])
    except Customer.DoesNotExist:
        customer = Customer(email=request.POST['email'])
        customer.save()
    if request.POST.get('contact_id', False):
        contact = Contact.objects.get(id=request.POST['contact_id'])
    else:
        contact = Contact(
            customer=customer,
            name=request.POST['name'],
            country='USA',  # hardcoded
            state=request.POST.get('state', ''),
            city=request.POST['city'],
            address=request.POST['address'],
            phone=request.POST.get('phone', ''),
            zip=request.POST.get('zip', ''),
            primary=True,
        )
        contact.save()
    return customer, contact
示例#34
0
def createuser(request):
    if request.method == "POST":
        form = CustomerCreationForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = form.save()
            customer = Customer()
            customer.user = user
            customer.address = data['address']
            customer.city = data['city']
            customer.state = data['state']
            customer.zip_code = data['zip_code']
            customer.phone = data['phone']
            customer.save()
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password1'])
            login(request, user)

            return HttpResponseRedirect(reverse('home'))
    else:
        form = CustomerCreationForm()

    return render(request, 'registration/customer_registration.html',
                  {'form': form})
示例#35
0
 def form_valid(self, form):
     new = Customer()
     new.username = form.cleaned_data['username']
     new.set_password(form.cleaned_data['password1'])
     new.save()
     return super(RegisterView, self).form_valid(form)
示例#36
0
文件: views.py 项目: corykitchens/sae
def create_work_order(request):
	if request.method=='GET':
		# Get customer form
		customer_form = CustomerForm()
		ca_form = AddressForm()
		work_order_form = WorkOrderForm()
		vehicle_form = VehicleForm()
		try:
			parts_list = Part.objects.all()
		except Part.DoesNotExist:
			parts_list = []
		return render(request, 'workorder/create_work_order.html', {'customer_form' : customer_form,
																	'ca_form': ca_form,
																	'vehicle_form' : vehicle_form,
																	'work_order_form' : work_order_form,
																	'parts' : parts_list})

	elif request.method=='POST':

		if request.POST['c-first-name']  != '':
			# Returning Customer
			query_vehicle = int(request.POST['vehicle_id'])
			query_first_name = request.POST['first_name']
			query_last_name = request.POST['last_name']

			try:
				c = Customer.objects.get(first_name=query_first_name, last_name=query_last_name)
			except Customer.DoesNotExist:
				HttpResponse('Error querying customer')

			if query_vehicle is not -1:
				try:
					v = Vehicle.objects.get(pk=query_vehicle)
				except Vehicle.DoesNotExist:
					HttpResponse('Error querying vehicle')
			else:
				#New Vehicle
				v = Vehicle(license_plate=request.POST['license_plate'],
									make=request.POST['make'],
									model=request.POST['model'],
									vin = request.POST['vin'],
									year = request.POST['year'])
				v.save()
				c.vehicle.add(v)

			#Work Order
			w = WorkOrder()
			w.odometer = request.POST['odometer']

			w.date_created = timezone.now()
			w.problem_description = request.POST['problem_description']
			w.estimate_initial = 0
			w.estimate_revision = 0
			w.amount_paid = 0
			w.customer = c
			w.status = 'Assigned'
			w.vehicle = v
			w.employee = Employee.objects.get(user=request.user)
			w.save()
			
			service_list = request.POST.getlist('service_type')
			for service in service_list:
				selected_service = ServiceType.objects.get(pk=int(service))
				w.service_type.add(selected_service)
				w.estimate_initial = w.estimate_initial + selected_service.cost
				
			w.estimate_revision = w.estimate_initial
			w.save()

			work_orders = WorkOrder.objects.filter(employee=w.employee)
			employee = Employee.objects.get(user=request.user)
			
			return render(request, 'employee/employee_home.html', {'user': request.user, 'employee': employee,
				 'work_orders' : work_orders})
		else:

			# New customer
			c = Customer()
			c.first_name = request.POST['first_name']
			c.middle_initial = request.POST['middle_initial']
			c.last_name  = request.POST['last_name']
			c.email =	request.POST['email']


			# Customer Address
			ca = CustomerAddress()
			ca.address = request.POST['address']
			ca.city	= request.POST['city']
			ca.state = request.POST['state']
			ca.save()
			c.address = ca
			c.save()
			
			# Vehicle
			v = Vehicle()
			v.license_plate = request.POST['license_plate']
			v.make	= request.POST['make']
			v.model = request.POST['model']
			v.vin	= request.POST['vin']
			v.year = request.POST['year']
			v.save()
			c.vehicle.add(v)

			# Work Order
			w = WorkOrder()
			w.odometer = request.POST['odometer']
			w.date_created = timezone.now()
			w.problem_description = request.POST['problem_description']
			w.estimate_initial = 0
			w.estimate_revision = 0
			w.amount_paid = 0
			w.customer = c
			w.status = 'Assigned'
			w.vehicle = v
			w.employee = Employee.objects.get(user=request.user)
			w.save()

			service_list = request.POST.getlist('service_type')
			for service in service_list:
				selected_service = ServiceType.objects.get(pk=int(service))
				w.service_type.add(selected_service)
				w.estimate_initial = w.estimate_initial + selected_service.cost
				
			w.estimate_revision = w.estimate_initial
			w.save()

			work_orders = WorkOrder.objects.all()
			employee = Employee.objects.get(user=request.user)
			return render(request, 'employee/employee_home.html', {'user': request.user, 'employee': employee,
				 'work_orders' : work_orders})