Пример #1
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.')
Пример #2
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")
Пример #3
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")
Пример #4
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)
Пример #5
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
Пример #6
0
    def test_save(self):
        cust = Customer()
        cust.name = "test name"
        cust.zipcode = 666
        cust.save()

        self.assertEquals(cust.id, 1)
Пример #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 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"
Пример #9
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()
Пример #10
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)
Пример #11
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)
Пример #12
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()
Пример #13
0
    def delete(self, **write_concern):
        from customer.models import Customer, Machine
        # 删除客户对应模块信息
        Customer.objects(modules__contains=self).update(pull__modules=self)

        # 删除机器对应模块信息
        Machine.objects(modules__contains=self).update(pull__modules=self)

        # 调用父类删除方法
        super(Module, self).delete()
Пример #14
0
def update_customer_remark(customer: Customer, remark: str):
    """
    更改客户备注
    :param customer:
    :param remark:
    :return:
    """
    customer.remark = remark
    customer.save()
    return True, ""
Пример #15
0
    def delete(self, **write_concern):
        from customer.models import Customer, Machine

        # 删除客户对应模块信息
        Customer.objects(modules__contains=self).update(pull__modules=self)

        # 删除机器对应模块信息
        Machine.objects(modules__contains=self).update(pull__modules=self)

        # 调用父类删除方法
        super(Module, self).delete()
Пример #16
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
     
Пример #17
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)
Пример #18
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
Пример #19
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
Пример #20
0
    def put(self, customer_id, address_id):
        """
        switch primary address

        :param customer_id: customer to update
        :param address_id: address to become primary
        :return: address object
        """

        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        address = customer.get_addresses().filter(
            address_id=address_id).first()

        if address is None:
            return jsonify({"error": ADDRESS_NOT_FOUND}), 404

        address.make_primary()

        response = {"result": "ok", "address": address_obj(address)}
        return jsonify(response), 200
Пример #21
0
    def post(self, customer_id):
        """
        creates a new customer address. Overrides primary if is_primary included in request

        :param customer_id: customer whose address to be added to
        :return: address object
        """

        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        error = best_match(
            Draft4Validator(address_schema).iter_errors(request.json))
        if error:
            return jsonify({"error": error.message}), 400

        if request.json.get("is_primary") is not None:
            if request.json.get("is_primary").lower() == "true":
                response = {
                    "result":
                    "ok",
                    "address":
                    address_obj(
                        customer.add_address(request=request, is_primary=True))
                }
                return jsonify(response), 201

        return jsonify(
            address_obj(customer.add_address(request=request,
                                             is_primary=False))), 201
Пример #22
0
    def post(self, customer_id):
        """
        creates a new email

        query_parameters: is_primary

        :param customer_id: customer to be updated
        :return: customer object
        """
        if request.json.get("email") is None:
            return jsonify({"error": EMAIL_IS_REQUIRED_FIELD}), 403

        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        is_primary = False
        if request.args.get("is_primary") is not None:
            if request.args.get("is_primary").lower() == "true":
                is_primary = True

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        try:
            customer.add_email(new_email=request.json.get("email"),
                               is_primary=is_primary)
        except DuplicateDataError:
            response = {
                "result": "already exists",
                "customer": customer_obj(customer)
            }
            return jsonify(response), 303

        response = {"result": "ok", "customer": customer_obj(customer)}
        return jsonify(response), 201
Пример #23
0
    def delete(self, customer_id):
        """
        deletes an email

        query_parameters: is_primary

        :param customer_id: customer to be updated
        :return: customer object
        """
        if request.json.get("email") is None:
            return jsonify({"error": EMAIL_IS_REQUIRED_FIELD}), 403

        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        deleted_email = customer.delete_email(
            email_to_delete=request.json.get("email"))

        if deleted_email is None:
            response = {
                "result": "not found",
                "customer": customer_obj(customer)
            }
            return jsonify(response), 404

        response = {"result": "ok", "customer": customer_obj(customer)}
        return jsonify(response), 204
Пример #24
0
    def put(self, customer_id):
        """
        marks email address as primary

        :param customer_id: customer to be updated
        :return: customer object
        """
        if request.json.get("email") is None:
            return jsonify({"error": EMAIL_IS_REQUIRED_FIELD}), 403

        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        new_primary_email = customer.make_email_primary(
            new_primay_email=request.json.get("email"))

        if new_primary_email is None:
            response = {
                "result": "not found",
                "customer": customer_obj(customer)
            }
            return jsonify(response), 404

        response = {"result": "ok", "customer": customer_obj(customer)}
        return jsonify(response), 200
Пример #25
0
def init(request):
    def getSpeed(n,start,stop):
        return str(math.floor(n/(stop-start)))
    html = ""
    n_articles = 1000
    n_customers = 1000

    start = time.time()
    articles = Article.init(n_articles)
    stop = time.time()
    html += getSpeed(n_articles,start,stop) + " articles/s"
    html += "<br><br>"

    start = time.time()
    customers = Customer.init(n_customers)
    stop = time.time()
    html += getSpeed(n_customers,start,stop) + " customers/s"
    html += "<br><br>"

    start = time.time()
    Rent.init(articles, customers)
    stop = time.time()
    html += getSpeed(n_articles * n_customers,start,stop) + " rents/s"

    return HttpResponse(html)
Пример #26
0
    def get(self, customer_id):
        """
        return primary address or list of all addresses

        :param customer_id: to return list of addresses for
        :return: addresses
        """
        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        if request.args.get("is_primary"):
            if request.args.get("is_primary").lower() == "true":
                response = {
                    "result": "ok",
                    "address": address_obj(customer.get_primary_address())
                }
                return jsonify(response), 200

        return paginated_results(
            objects=customer.get_addresses(),
            collection_name='address',
            request=request,
            per_page=self.PER_PAGE,
            serialization_func=addresses_obj_for_pagination), 200
Пример #27
0
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if not form.is_valid():
            return render(request, 'signup.html', {'form': form})
        else:
            # fetch data from inputs of form
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            telephone = form.cleaned_data.get('telephone')
            address = form.cleaned_data.get('address')
            User.objects.create_user(username=email,
                                     password=password,
                                     email=email,
                                     first_name=first_name,
                                     last_name=last_name)
            user = authenticate(email=email, password=password)
            login(request, user)
            customer = Customer(user=user, tel=telephone, address=address)
            customer.save()
            return redirect('/')

    else:
        return render(request, 'signup.html', {'form': SignUpForm()})
Пример #28
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)
    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)
Пример #30
0
def add_customer_info():
    '''添加客户基本信息'''

    user_id = g.user_id
    # 获取请求的json数据,返回字典
    req_dict = request.get_json()
    name = req_dict.get("name")
    contacts = req_dict.get("contacts")
    phone = req_dict.get("phone")

    # 效验参数
    if not all([name, contacts, phone]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    try:
        customer = Customer.query.filter(Customer.name == name,
                                         Customer.isdelete == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")
    if customer:
        customer.contacts = contacts
        customer.tel = phone
        customer.isdelete = False
    else:
        customer = Customer(name=name,
                            contacts=contacts,
                            tel=phone,
                            user=user_id)

    try:
        db.session.add(customer)
        db.session.commit()
    except IntegrityError as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAEXIST, errmsg="该客户已存在")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")

    data = customer.to_base_dict()

    return jsonify(errno=RET.OK, errsmg="添加成功", data=data)
Пример #31
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')
Пример #32
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()
Пример #33
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)
Пример #34
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)
Пример #35
0
    def create(self, request):
        
        serializer = CustomerSerializer(data=request.data)

        if serializer.is_valid():
            customer = Customer()
            customer.name = serializer['name'].value
            customer.zipcode = serializer['zipcode'].value

            #Call BOB Api
            r = requests.get(BOB_API_URL.format(customer.zipcode))
            if r.status_code == 200 and r.json()['results']:
                print("ZipCode found")
                ret = r.json()['results'][0]
                customer.street = ret['street']
                customer.state = ret['state']
                customer.city = ret['city']
            else:
                print("zipCode not found on BOB_API")


            self.perform_create(customer)

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Пример #36
0
def load(request):
    """
    版本列表
    :param request:
    :return:
    """
    client = pysvn.Client()
    logger.info("load svn")

    for program in ALL_SVN_LIST:
        dir = getLocalDir(program)
        url = client.info(dir).data['url']
        logger.info("program:[%s],url:[%s]" % (program, url))
        # trunk
        info = None
        try:
            info = BranchInfo.objects().get(programName=program, branchTag="trunk")
        except:
            pass
        if info is None:
            info = BranchInfo()
            info.programName = program
            info.branchTag = "trunk"
            info.createDate = "999999"
            info.save()

        branches = []
        branches.extend(getBranches(client, url, "branches"))
        try:
            branches.extend(getBranches(client, url, "tags"))
        except Exception as e:
            pass
        for x in branches:
            info = None
            try:
                info = BranchInfo.objects().get(programName=program, branchTag=x)
            except:
                pass
            if info is None:
                info = BranchInfo()
                info.programName = program
                info.branchTag = x
                customerTag = getCustomerTag(x)
                customer = Customer.objects(tag=customerTag)
                if len(customer) > 0:
                    info.customerTag = customerTag
                info.createDate = getCreateDate(x)
                info.save()
    return redirect("/programBranch/list/", locals())
Пример #37
0
def logPost(request):
    """
    提交日志信息
    :param request:
    :return:
    """
    if request.method == "GET":
        customer = Customer.objects()
        serverMonitorLogType = ServerMonitorLogType.objects()
        serverMonitorModule = ServerMonitorModule.objects()
        return render_to_response("serverMonitor/logPost.html", locals(), context_instance=RequestContext(request))
    elif request.method == "POST":
        response = {"success": True, "error": "上传成功!"}
        try:
            #获取参数
            cus_name = request.POST.get('cus_name', None)
            customer = Customer.objects.get(pk=cus_name)
            log_type = request.POST.get('log_type', None)
            log_type = ServerMonitorLogType.objects.get(pk=log_type)
            monitor_type = request.POST.get('monitor_type', None)
            module_type = request.POST.get('module_type', None)
            module = ServerMonitorModule.objects.get(module=module_type)
            detail = request.POST.get('detail', None)
            url = request.POST.get('url', None)
            create_time = datetime.datetime.now()
            create_user = User.objects.get(pk=request.user.id)

            # 保存监控日志信息
            logInfo = ServerMonitorLog()
            logInfo.cus = customer
            logInfo.log_type = log_type
            logInfo.monitor_type = int(monitor_type)
            logInfo.module_type = module
            logInfo.detail = detail
            logInfo.create_time = create_time
            logInfo.cus_uuid = customer.machines[0].code
            logInfo.create_user = create_user

            logInfo.attachment_url = url
            logInfo.save()
            return HttpResponse(json.dumps(response), mimetype="application/json")

        except Exception as e:
            response["success"] = False
            response["error"] = "系统异常![%s]" % str(e)
            logger.error(response["error"] + getTraceBack())
            return HttpResponse(json.dumps(response), mimetype="application/json")
Пример #38
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})
Пример #39
0
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})
Пример #40
0
 def get(self, requests, customer_id):
     if Customer.exists(customer_id):
         return Response(utils.get_customer_profiles(customer_id), status.HTTP_200_OK)
     else:
         return Response({}, status.HTTP_404_NOT_FOUND)
Пример #41
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)
Пример #42
0
def quickSearch(request):
    if request.method == "GET":
        search_customer = request.GET.get("customer", None)
        search_manager = request.GET.get("manager", None)
        search_status = request.GET.get("status", None)
        search_module = request.GET.get("module", None)
        search_permission = request.GET.get("permission", None)
        search_perm_num = request.GET.get("num", None)
        search_perm_bool = request.GET.get("bool", None)
        search_config = request.GET.get("config", None)
        is_actual = request.GET.get("isActual", None)
        search_position = request.GET.get("position", None)
        if search_customer:
            if is_actual == "是":
                customers = Customer.objects(is_sys=False).order_by("+tag")
            elif is_actual == "否":
                customers = Customer.objects(is_sys=True).order_by("+tag")
            elif is_actual == "任意":
                customers = Customer.objects().order_by("+tag")

            cus_states = CustomerDeployStatus.objects()
            error = request.GET.get("error", None)
            cus_aftersales = []
            for customer in customers:
                if customer.aftersale in cus_aftersales:
                    continue
                cus_aftersales.append(customer.aftersale)

            results = []
            if search_customer:
                for customer in customers:
                    if search_customer == customer.name:
                        results.append(customer)
            if search_manager and search_manager != "任意":
                for customer in customers:
                    if search_manager == customer.aftersale:
                        if is_actual == "是":
                            if "实盘" in customer.name:
                                results.append(customer)
                        else:
                            results.append(customer)
            if search_status and search_status != "任意":
                for customer in customers:
                    if search_status == customer.customerstatus:
                        if is_actual == "是":
                            if "实盘" in customer.name:
                                results.append(customer)
                        else:
                            results.append(customer)
            if search_module and search_module != "任意":
                for customer in customers:
                    cus_modules = customer.modules
                    for module in cus_modules:
                        if search_module == module.name:
                            if is_actual == "是":
                                if "实盘" in customer.name:
                                    results.append(customer)
                            else:
                                results.append(customer)
            if search_permission and search_permission != "任意":
                for customer in customers:
                    cus_permission = customer.permissions
                    perm_settings = CustomerPermissionSettings.objects()
                    for perm_setting in perm_settings:
                        if perm_setting.name == search_permission[1:]:
                            perm_id = str(perm_setting.id)
                            if str(search_perm_num) == str(cus_permission[perm_id]) or str(search_perm_bool) == str(
                                cus_permission[perm_id]
                            ):
                                if is_actual == "是":
                                    if "实盘" in customer.name:
                                        results.append(customer)
                                else:
                                    results.append(customer)
            if search_config:
                for customer in customers:
                    setting = customer.settings
                    pattern = re.compile(search_config, re.X)
                    match = pattern.search(setting)
                    if match is not None:
                        if is_actual == "是":
                            if "实盘" in customer.name:
                                results.append(customer)
                        else:
                            results.append(customer)

            if is_actual == "是":
                for customer in customers:
                    if "实盘" in customer.name:
                        results.append(customer)
            elif is_actual == "否":
                for customer in customers:
                    results.append(customer)

            if search_position and search_position != "任意":
                for customer in customers:
                    if customer.position == search_position:
                        results.append(customer)

        else:
            customers = Customer.objects().order_by("+tag")
            cus_states = CustomerDeployStatus.objects()
            error = request.GET.get("error", None)
            cus_aftersales = []
            results = []
            for customer in customers:
                if customer.aftersale in cus_aftersales:
                    continue
                    cus_aftersales.append(customer.aftersale)
                    results.append(customer)
        return render_to_response("demo/search_view.html", locals(), context_instance=RequestContext(request))

    elif request.method == "POST":
        response = {"success": False, "error": "", "id": None}
        try:
            response["success"] = True
            response["error"] = "执行成功!"
            return HttpResponse(json.dumps(response), mimetype="application/json")
        except Exception, e:
            response["error"] = "系统异常![%s]" % str(e)
            logger.error(response["error"] + getTraceBack())
            return HttpResponse(json.dumps(response), mimetype="application/json")
Пример #43
0
def platform_operate(request):
    """
    平台保存,删除,更新
    :param request:
    :return:
    """
    if request.method == "GET":
        error = "非法请求方式!"
        logger.error(error)
        return render_to_response("item/temp.html", locals(), context_instance=RequestContext(request))
    elif request.method == "POST":
        # cmd in [update, save, delete]
        # cmd in [更新, 保存, 删除]
        response = {"success": False, "error": ""}
        try:
            # 获取参数
            cmd = request.POST.get("cmd", None)
            id = request.POST.get("id", None)

            m_nId = request.POST.get("m_nId", None)
            m_nId = int(m_nId) if m_nId else None

            m_nType = request.POST.get("m_nType", None)
            m_nType = int(m_nType) if m_nType else None

            m_strName = request.POST.get("m_strName", None)
            m_strAbbrName = request.POST.get("m_strAbbrName", None)
            m_strSoName = request.POST.get("m_strSoName", None)
            m_strConfig = request.POST.get("m_strConfig", None)
            m_strLogo = request.POST.get("m_strLogo", None)
            m_strQuoterTag = request.POST.get("m_strQuoterTag", None)
            m_strBrokerTag = request.POST.get("m_strBrokerTag", None)
            m_strfastTag = request.POST.get("m_strfastTag", None)

            if cmd is None:
                response["error"] = "CMD参数不能为空!"
                return HttpResponse(json.dumps(response), mimetype="application/json")

            param_is_none = False
            if not m_nId or not m_nType:
                param_is_none = True

            if (
                (cmd == "delete" and id is None)
                or (cmd == "save" and param_is_none)
                or (cmd == "update" and (param_is_none or id is None))
            ):
                response["error"] = "必要参数为空!"
                return HttpResponse(json.dumps(response), mimetype="application/json")

            # 创建
            if cmd == "save":
                # 判断是否已有
                param_exist = Platform.objects(m_strName=m_strName, m_nType=m_nType)

                if len(param_exist) > 0:
                    response["error"] = "已存在相同平台!请在原基础修改!"
                    return HttpResponse(json.dumps(response), mimetype="application/json")

                platform = Platform()
                platform.m_nId = m_nId
                platform.m_nType = m_nType
                platform.m_strName = m_strName
                platform.m_strAbbrName = m_strAbbrName
                platform.m_strSoName = m_strSoName
                platform.m_strConfig = m_strConfig
                platform.m_strLogo = m_strLogo
                platform.m_strQuoterTag = m_strQuoterTag
                platform.m_strBrokerTag = m_strBrokerTag
                platform.m_strfastTag = m_strfastTag
                platform.save()
                response["id"] = str(platform.id)

            # 更新
            elif cmd == "update":
                # 查找对象
                platform = Platform.objects(pk=id)
                if len(platform) == 0:
                    response["error"] = "未找到可更新对象!"
                    return HttpResponse(json.dumps(response), mimetype="application/json")
                platform = platform[0]
                platform.m_nId = m_nId
                platform.m_nType = m_nType
                platform.m_strName = m_strName
                platform.m_strAbbrName = m_strAbbrName
                platform.m_strSoName = m_strSoName
                platform.m_strConfig = m_strConfig
                platform.m_strLogo = m_strLogo
                platform.m_strQuoterTag = m_strQuoterTag
                platform.m_strBrokerTag = m_strBrokerTag
                platform.m_strfastTag = m_strfastTag
                platform.save()

            # 删除
            elif cmd == "delete":
                # 查找对象
                platform = Platform.objects(pk=id)
                if len(platform) == 0:
                    response["error"] = "未找到可删除对象!"
                    return HttpResponse(json.dumps(response), mimetype="application/json")

                platform = platform[0]
                path = request.path
                is_sys = None
                if path == "/customer/system/list/":
                    is_sys = True
                elif path == "/customer/list/":
                    is_sys = False
                else:
                    is_sys = False

                customers = Customer.objects(is_sys=is_sys).order_by("+tag")
                for customer in customers:
                    cus_modules = customer.modules
                    for module in cus_modules:
                        if module.group == "Broker实盘" or module.group == "Broker模拟":
                            name_list = module.name.split("_")
                            if len(name_list) >= 3:
                                if str(platform.m_nId) == name_list[2]:
                                    response["error"] = "该平台被客户[%s]使用,不能删除!" % str(customer.name)
                                    return HttpResponse(json.dumps(response), mimetype="application/json")

                platform.delete()

            else:
                response["error"] = "CMD指令异常!"
                return HttpResponse(json.dumps(response), mimetype="application/json")

            response["success"] = True
            response["error"] = "执行成功!"
            return HttpResponse(json.dumps(response), mimetype="application/json")
        except Exception as e:
            response["error"] = "系统异常![%s]" % str(e)
            logger.error(response["error"] + getTraceBack())
            return HttpResponse(json.dumps(response), mimetype="application/json")