Exemple #1
0
    def test_multiple_addresses(self):
        """ Tests that the index shows multiple addresses"""
        test = app.test_client(self)
        address_1 = Address(name='Casa Bonita',
                            address='6715 West Colfax Ave',
                            city='Denver',
                            state='CO',
                            zip='80214')
        address_2 = Address(name='Aquarium',
                            address='700 Water Street',
                            city='Denver',
                            state='CO',
                            zip='80211')

        db.session.add(address_1)
        db.session.add(address_2)
        db.session.commit()

        response = test.get('/addresses', content_type='html/text')
        self.assertEqual(response.status_code, 200)

        self.assertIn(b'Casa Bonita', response.data)
        self.assertIn(b'6715 West Colfax Ave', response.data)
        self.assertIn(b'Denver', response.data)
        self.assertIn(b'CO', response.data)
        self.assertIn(b'Delete', response.data)

        self.assertIn(b'Aquarium', response.data)
        self.assertIn(b'700 Water Street', response.data)
        self.assertIn(b'80211', response.data)
Exemple #2
0
 def test_newInvalid(self, testUser, mockGeoResponse):
     with pytest.raises(AddressError):
         Address(line1="1 covey chase dr",
                 city="Charlotte",
                 state_id=1,
                 user_id=1,
                 zip="28210")
 def addresses(self):
     return Address(address1=fake.street_address(),
                    city=fake.city(),
                    state=choice(constants.STATE_CHOICES),
                    zip_code=fake.postcode(),
                    address_description=choice(
                        constants.ADDRESS_DESCRIPTIONS))
Exemple #4
0
def address(request):
    if request.method == 'GET':
        adrid = request.GET.get('id')
        if adrid:
            address = Address.objects.get(pk=adrid)
            data = {
                'address': address
            }
            return render(request, 'user/editaddress.html', context=data)
        else:
            return render(request, 'user/addaddress.html')
    if request.method == 'POST':
        a_name = request.POST.get('username')
        a_phone = request.POST.get('phone')
        a_address = request.POST.get('address')
        adrid = request.POST.get('adrid')
        token = request.POST.get('token')
        user = cache.get(token)
        if adrid:
            address = Address.objects.get(pk=adrid)
            address.a_name = a_name
            address.a_phone = a_phone
            address.a_address = a_address
        else:
            address = Address()
            address.a_name = a_name
            address.a_phone = a_phone
            address.a_address = a_address
            address.a_user_id = user
        address.save()
        data = {
            'status': 200,
            'msg': '保存成功'
        }
        return JsonResponse(data=data)
Exemple #5
0
def generate_object_item_delivery():
    idelivr = ItemDelivery()
    type_d = generate_type_driver()
    idelivr.load = generate_load_transport(type_d)
    idelivr.name = generate_name_item_delivery(type_d)
    # TODO: change to all BR, for a while, just CG.
    lat_o, lng_o = random_lat_lon()
    lat_t, lng_t = random_lat_lon()
    idelivr.lat = lat_o
    idelivr.lng = lng_o
    address = Address()
    address.lat = lat_t
    address.lng = lng_t
    idelivr.address = geolocation_reverse(lat_o, lng_o)
    address.address = geolocation_reverse(lat_t, lng_t)
    address.save()
    idelivr.target = address
    idelivr.save()
    for i in range(generate_stops_number()):
        lat_stop, lng_stop = random_lat_lon()
        stop = Stop()
        stop.lat = lat_stop
        stop.lng = lng_stop
        stop.item_delivery = idelivr
        stop.save()
    idelivr.distance = get_distance_total_idelivery(idelivr)
    idelivr.save()
    idelivr.amount_receivable = Money(
        generate_profit_item_delivery(type_d, idelivr.distance) +
        get_cost_travel(generate_kml_transport(type_d), idelivr.distance,
                        type_d), 'BRL')
    idelivr.save()
    return idelivr
def add_address(request):
    street = json.loads(request.body)['street']
    number = json.loads(request.body)['number']
    complement = json.loads(request.body)['complement']
    neighborhood = json.loads(request.body)['neighborhood']
    city = json.loads(request.body)['city']
    state = json.loads(request.body)['state']
    energy_company = json.loads(request.body)['energyCompany']
    try:
        address = Address(user=request.user,
                          street=street,
                          number=number,
                          complement=complement,
                          neighborhood=neighborhood,
                          city=city,
                          state=state,
                          energy_company=energy_company)
        address.save()

        if address:
            return JsonResponse({
                'success': True,
            })
    except:
        return JsonResponse({
            'success': False,
        })
    return JsonResponse({
        'success': False,
    })
Exemple #7
0
def provider_add():
    """Adds provider to db."""
    form = ProviderAddForm()
    form.populate_choices()
    form_dict = form.data
    if form.validate_on_submit():
        address = Address(unknown=form.address.unknown.data,
                          line1=form.address.line1.data,
                          line2=form.address.line2.data,
                          city=form.address.city.data,
                          state_id=form.address.state.data,
                          zip=form.address.zip.data)
        categories = [Category.query.get(cat) for cat in form.category.data]
        provider = Provider.create(name=form.name.data,
                                   email=form.email.data,
                                   telephone=form.telephone.data,
                                   website=form.website.data,
                                   address=address,
                                   categories=categories)
        address.get_coordinates()
        flash(provider.name + " added.")
        return redirect(url_for("main.index"))
    elif request.method == "POST" and not form.validate():
        flash("Failed to add provider")
        return render_template("provideradd.html",
                               title="Add Provider",
                               form=form,
                               form_dict=form_dict), 422
    if not current_user.email_verified:
        disableForm(form)
        flash("Form disabled. Please verify email to unlock.")
    return render_template("provideradd.html",
                           title="Add Provider",
                           form=form,
                           form_dict=form_dict)
Exemple #8
0
def saveAddress():

    if request.method == 'POST':
        p_uid = request.form.get('uid', None)
        p_consignee = request.form.get('consignee', None)
        p_tel = request.form.get('tel', None)
        p_province = request.form.get('province', None)
        p_city = request.form.get('city', None)
        p_district = request.form.get('district', None)
        p_address = request.form.get('address', None)

        if not p_uid or not p_consignee or not p_tel or not p_province or not p_city or not p_district or not p_address:
            return 'input error'

        newobj = Address(uid=p_uid,
                         consignee=p_consignee,
                         tel=p_tel,
                         province=p_province,
                         city=p_city,
                         district=p_district,
                         address=p_address)
        db.session.add(newobj)
        db.session.commit()

        address = db.session.query(Address).filter_by(uid=p_uid)

        msgs = []
        for msg in address:
            msgs.append(msg)

        jsonAddressList = json.dumps(msgs, cls=AlchemyJsonEncoder)

        return jsonAddressList
    return ''
Exemple #9
0
 def post(self):
     args = self.parser.parse_args()
     town = args.get("town")
     street = args.get("street")
     phone = args.get("phone")
     empty = lambda x: len(x.strip()) == 0
     if empty(town) or empty(street) or empty(phone):
         return {
             "code":
             "500",
             "message":
             "Please provide all the details needed don't leave blanks"
         }, 200
     address = Address(town, street, phone)
     user = User.get_by_id(1)
     if user is None:
         return {
             "code": "404",
             "message": "Please become a valid user",
             "ok": False
         }
     db.users[db.users[user].username].add_address(address)
     return {
         "code": "231",
         "message": "The address was successfully added",
         "data": address.json
     }
 def setup_dummy_services_including_unpublished(self, n):
     self.setup_dummy_suppliers(TEST_SUPPLIERS_COUNT)
     self.setup_dummy_services(n)
     with self.app.app_context():
         # Add extra 'enabled' and 'disabled' services
         self.setup_dummy_service(service_id=str(n + 2000000001),
                                  supplier_code=n % TEST_SUPPLIERS_COUNT,
                                  status='disabled')
         self.setup_dummy_service(service_id=str(n + 2000000002),
                                  supplier_code=n % TEST_SUPPLIERS_COUNT,
                                  status='enabled')
         # Add an extra supplier that will have no services
         db.session.add(
             Supplier(
                 code=TEST_SUPPLIERS_COUNT,
                 name=u"Supplier {}".format(TEST_SUPPLIERS_COUNT),
                 addresses=[
                     Address(address_line="{} Empty Street".format(
                         TEST_SUPPLIERS_COUNT),
                             suburb="Empty",
                             state="ZZZ",
                             postal_code="0000",
                             country='Australia')
                 ],
             ))
         db.session.commit()
Exemple #11
0
 def post(self):
     if request.is_json:
         customer_name = request.json['customer_name']
         addressLine1 = request.json['jobaddressLine1']
         addressLine2 = request.json['jobaddressLine2']
         landmark = request.json['landmark']
         zipcode = request.json['zipcode']
         city = request.json['city']
         state = request.json['state']
         email = request.json['email']
         customer_phone = request.json['customer_phone']
         description = request.json['description']
         size = request.json['size']
         expectedStartDate = request.json['expectedStartDate']
         expectedEndDate = request.json['expectedEndDate']
         address = Address(addressLine1=addressLine1,
                           addressLine2=addressLine2,
                           landmark=landmark,
                           zipcode=zipcode,
                           city=city,
                           state=state)
         job = Jobs(customer_name=customer_name,
                    job_address=address,
                    billing_address=address,
                    email=email,
                    customer_phone=customer_phone,
                    description=description,
                    size=size,
                    expectedStartDate=expectedStartDate,
                    expectedEndDate=expectedEndDate)
         job.save()
         return jsonify(job)
     return {'status': 'invalid request'}
Exemple #12
0
def edit_address():
    form = AddressForm(current_user.username)
    if form.validate_on_submit():
        language = guess_language(form.address.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        address = Address(body=form.address.data, author=current_user)
        db.session.add(address)
        db.session.commit()
        flash(_('Your changes have been saved.'))
        return redirect(url_for('edit_address'))
    page = request.args.get('page', 1, type=int)
    addresses = current_user.addresses.order_by(
        Address.timestamp.desc()).paginate(page, 25, False)
    next_url = url_for('index', page=addresses.next_num) \
        if addresses.has_next else None
    prev_url = url_for('index', page=addresses.prev_num) \
        if addresses.has_prev else None

    return render_template('edit_address.html',
                           title=_('Edit Address'),
                           form=form,
                           addresses=addresses.items,
                           next_url=next_url,
                           prev_url=prev_url)
Exemple #13
0
def new_address():
    form = AddressForm()
    form.address_type.choices = [(address_type.id, address_type.name)
                                 for address_type in AddressTypeLu.query.order_by('name').all()]
    form.contact.choices = [(contact.id, ''.join([contact.first_name, ', ', contact.middle_name,  ' ',  contact.last_name]))
                            for contact in Contact.query.filter_by(created_by=current_user).all()]
    if form.validate_on_submit():
        address = Address(address_type_id=form.address_type.data,
                          contact_id=form.contact.data,
                          created_by=current_user,
                          address_line1=form.address_line1.data,
                          address_line2=form.address_line2.data,
                          address_line3=form.address_line3.data,
                          city=form.city.data,
                          state=form.state.data,
                          country=form.country.data,
                          comments=form.comments.data,
                          latitude=form.latitude.data,
                          longitude=form.longitude.data,
                          is_private=form.is_private.data
                          )
        db.session.add(address)
        db.session.commit()
        flash('New Address has been added', 'Success')
        return redirect(url_for('contacts.all_address'))
    return render_template('/contacts/_contacts.addAddress.html', form=form, legend='Add new Address')
Exemple #14
0
def signup():
    data = request.get_json()
    # for key, value in data.items():
    #     if not value:
    #         data[key] = None
    email = data["email"]
    username = request.json.get("username", None)
    image_url = current_app.config['PROFILE_IMAGE']
    image_back_url = current_app.config['PROFILE_BACK_IMAGE']
    if User.query.filter_by(email=email).first():
        return {"error": f"The user with email {email} already exists"}, 409
    if username and User.query.filter_by(username=username).first():
        return {"error": f"The user with username {username} already exists"}, 409
    email_verified = False
    uuid = str(uuid4())
    profile_addr = uuid[:13]
    now = datetime.utcnow()
    # create user's folder
    user_folder = os.path.join(current_app.config['USERS_FOLDER'], uuid)
    try:
        os.mkdir(user_folder)
    except OSError:
        print(f"Creation of the directory for user {uuid} failed")

    user = User(username=username,
                uuid=uuid,
                first_name=data["first_name"],
                password=data["password"],
                email=email,
                email_verified=email_verified,
                image_url=image_url,
                image_back_url=image_back_url,
                profile_addr=profile_addr,
                confirm_email_sent=now)
    db.session.add(user)
    db.session.commit()

    address = Address(user_id=user.id,
                      primary_address=True,
                      state=data["state"],
                      city=data["city"],
                      country=data["country"],
                      lat=data["lat"],
                      lon=data["lon"],
                      address=data["address"],
                      zip_code=data["zip_code"] if data["zip_code"] else None)
    db.session.add(address)
    db.session.commit()

    session["id"] = user.id
    session["date"] = now
    # Send confirmation email

    email_token = ts.dumps(email, salt="email-confirm")
    confirm_url = url_for(".confirm_email", token=email_token, _external=True)
    subject = "InstaHarvest - Confirm your account"
    send_email(email, subject, "confirmation_email",
               user=user, confirm_url=confirm_url)
    return user.to_dict_auth(), 201
Exemple #15
0
def create_product():
    data = request.get_json()
    user_id = session["id"]
    address_id = None
    if type(data["location"]).__name__ == "str":
        address_id = int(data["location"])
    if address_id is None:
        loc = data["location"]
        user = User.query.filter_by(id=user_id).first()
        address = user.addresses.filter_by(
            lon=loc["lon"], lat=loc["lat"]).first()
        if address:
            return {"error": "Address already exists"}, 409

        address = Address(user_id=user_id,
                          primary_address=False,
                          state=loc["state"],
                          city=loc["city"],
                          country=loc["country"],
                          lat=loc["lat"],
                          lon=loc["lon"],
                          address=loc["address"],
                          zip_code=loc["zip_code"] if loc["zip_code"] else None)
        db.session.add(address)
        db.session.commit()
        address_id = address.id

    if request.method == "POST":
        product = Product(user_id=user_id,
                          name=data["name"],
                          product_type=data["product_type"],
                          product_icon=data["product_icon"],
                          price=data["price"],
                          status="available",
                          description=data["description"],
                          address_id=address_id)

    elif request.method == "PATCH":
        product = Product.query.filter_by(id=data["product_id"]).first()
        if product is None or product.user_id != user_id:
            return {}, 403
        product.name = data["name"]
        product.product_type = data["product_type"]
        product.product_icon = data["product_icon"]
        product.price = data["price"]
        product.description = data["description"]
        product.address_id = address_id

    db.session.add(product)
    db.session.commit()

    ret = {"msg": "Product created",
           "product_id": product.id}

    if request.method == "PATCH":
        ret["msg"] = "Product has been updated"
        return ret, 200

    return ret, 201
 def addresses(self):
     return Address(
         address1=fake.street_address(),
         city=fake.city(),
         state=choice(constants.STATE_CHOICES),
         zip_code=fake.postcode(),
         address_description=fake.random_element(ADDRESS_TYPES)
     )
Exemple #17
0
def seed_addresses():
    demo_address = Address(userId=1,
                           street_address="1111 One Drive",
                           city="Onevile",
                           state="Georgia",
                           zip_code=11111)
    db.session.add(demo_address)
    db.session.commit()
    def setup_services(self):
        with self.app.app_context():
            self.app.config['DM_API_SERVICES_PAGE_SIZE'] = 10
            now = pendulum.now('UTC')

            g5_saas = self.load_example_listing("G5")
            g5_paas = self.load_example_listing("G5")
            g6_paas_2 = self.load_example_listing("G6-PaaS")
            g6_iaas_1 = self.load_example_listing("G6-IaaS")
            g6_paas_1 = self.load_example_listing("G6-PaaS")
            g6_saas = self.load_example_listing("G6-SaaS")
            g6_iaas_2 = self.load_example_listing("G6-IaaS")

            db.session.add(
                Supplier(
                    code=1,
                    name=u"Supplier 1",
                    description="",
                    summary="",
                    addresses=[
                        Address(address_line="{} Dummy Street 1",
                                suburb="Dummy",
                                state="ZZZ",
                                postal_code="0000",
                                country='Australia')
                    ],
                    contacts=[],
                    references=[],
                    prices=[],
                ))

            def insert_service(listing, service_id, lot_id, framework_id):
                db.session.add(
                    Service(service_id=service_id,
                            supplier_code=1,
                            updated_at=now,
                            status='published',
                            created_at=now,
                            lot_id=lot_id,
                            framework_id=framework_id,
                            data=listing))

            # override certain fields to create ordering difference
            g6_iaas_1['serviceName'] = "b service name"
            g6_iaas_2['serviceName'] = "a service name"
            g6_paas_1['serviceName'] = "b service name"
            g6_paas_2['serviceName'] = "a service name"
            g5_paas['lot'] = "PaaS"

            insert_service(g5_paas, "123-g5-paas", 2, 3)
            insert_service(g5_saas, "123-g5-saas", 1, 3)
            insert_service(g6_iaas_1, "123-g6-iaas-1", 3, 1)
            insert_service(g6_iaas_2, "123-g6-iaas-2", 3, 1)
            insert_service(g6_paas_1, "123-g6-paas-1", 2, 1)
            insert_service(g6_paas_2, "123-g6-paas-2", 2, 1)
            insert_service(g6_saas, "123-g6-saas", 1, 1)

            db.session.commit()
Exemple #19
0
def edit_user_address():
    user_id = session["id"]
    data = request.get_json()

    if request.method == "POST":
        lon = data["lon"]
        lat = data["lat"]
        user = User.query.filter_by(id=user_id).first()
        if user is None:
            return {}, 404
        address = user.addresses.filter_by(
            lon=lon, lat=lat).first()
        if address:
            return {"error": "Address already exists"}, 409
        address = Address(user_id=user_id,
                          primary_address=False,
                          state=data["state"],
                          city=data["city"],
                          country=data["country"],
                          lat=lat,
                          lon=lon,
                          address=data["address"],
                          zip_code=data["zip_code"] if data["zip_code"] else None)
        db.session.add(address)
        db.session.commit()
        address_id = address.id
        return {
            "msg": "Address has been added",
            "address_id": address_id
        }, 201

    if request.method == "DELETE":
        address_id = data["address_id"]
        address = Address.query.filter_by(id=address_id).first()
        if user_id != address.user_id:
            return {}, 403
        n_products = address.products.count()
        if n_products > 0:
            return {"error": f"You can not delete this address. You have {n_products} product{'s' if n_products > 1 else ''} connected to it."}, 404
        db.session.delete(address)
        db.session.commit()
        return {"msg": "Address has been deleted"}, 200

    if request.method == "PATCH":
        address_id = data["address_id"]
        address = Address.query.filter_by(id=address_id).first()
        if user_id != address.user_id:
            return {}, 403
        prev_prim_address = address.user.addresses.filter_by(
            primary_address=True).first()
        if prev_prim_address is None:
            return {}, 404
        prev_prim_address.primary_address = False
        address.primary_address = True
        db.session.add(prev_prim_address)
        db.session.add(address)
        db.session.commit()
        return {"msg": "Primary address has been changed"}, 200
Exemple #20
0
def createdonor():
    """
    @api {post} /donor Add a new donor
    @apiVersion 1.0.0
    @apiName createdonor
    @apiGroup Donor

    @apiParam {String}      first_name      The first name of the Donor.
    @apiParam {String}      last_name       the last name of the Donor.
    @apiParam {String}      email           email of Donor.
    @apiParam {String}      phone_no        phone number of Donor.
    @apiParam {String}      password        password of Donor.
    @apiParam {String}      organisation    organisation of Donor.
    @apiParam {String}      city            city name(part of address)
    @apiParam {String}      street          street number(part of address)
    @apiParam {String}      landmark        landmark description(part of address)
    @apiParam {String}      country         country name(part of address)

    @apiSuccess {String}    message         donor added to database

    @apiError               message         Donor with that email already exists!
    @apiError               message[2]         address street not provided
    @apiError               message[3]         not json
    """
    donor = request.json
    if not donor:
        return jsonify({"message": "not json"}), 400
    if not donor.get("street"):
        return jsonify({"message": "address street not provided"}), 400
    print(donor)
    check_donor = Donor.query.filter_by(email=donor.get('email')).first()
    if check_donor:
        return jsonify({'message': 'Donor with that email already exists!'})
    password_hash = bcrypt.generate_password_hash(
        donor.get('password')).decode('utf-8')
    username = donor.get('email').split('@')[0]
    check_username = username_in_database_donor(username)
    if check_username:
        while check_username:
            username = username + '1'
            check_username = username_in_database_donor(username)
    u = Donor(first_name=donor.get('first_name'),
              last_name=donor.get('last_name'),
              email=donor.get('email'),
              phone_no=donor.get('phone_no'),
              username=username,
              password_hash=password_hash,
              organisation=donor.get('organisation'))
    address = Address(donor=u,
                      city=donor.get('city'),
                      street=donor.get('street'),
                      country=donor.get('country'),
                      landmark=donor.get('landmark'))
    db.session.add(address)
    db.session.add(u)
    db.session.commit()
    return jsonify({'message': 'Donor added to database'}), 200
 def setup(self):
     super(TestGetService, self).setup()
     now = pendulum.now('UTC')
     with self.app.app_context():
         db.session.add(Framework(
             id=123,
             name="expired",
             slug="expired",
             framework="g-cloud",
             status="expired",
         ))
         db.session.commit()
         db.session.add(FrameworkLot(
             framework_id=123,
             lot_id=1
         ))
         db.session.add(
             Supplier(code=1, name=u"Supplier 1",
                      addresses=[Address(address_line="{} Dummy Street 1",
                                         suburb="Dummy",
                                         state="ZZZ",
                                         postal_code="0000",
                                         country='Australia')])
         )
         db.session.add(Service(service_id="123-published-456",
                                supplier_code=1,
                                updated_at=now,
                                created_at=now,
                                status='published',
                                data={'foo': 'bar'},
                                lot_id=1,
                                framework_id=1))
         db.session.add(Service(service_id="123-disabled-456",
                                supplier_code=1,
                                updated_at=now,
                                created_at=now,
                                status='disabled',
                                data={'foo': 'bar'},
                                lot_id=1,
                                framework_id=1))
         db.session.add(Service(service_id="123-enabled-456",
                                supplier_code=1,
                                updated_at=now,
                                created_at=now,
                                status='enabled',
                                data={'foo': 'bar'},
                                lot_id=1,
                                framework_id=1))
         db.session.add(Service(service_id="123-expired-456",
                                supplier_code=1,
                                updated_at=now,
                                created_at=now,
                                status='enabled',
                                data={'foo': 'bar'},
                                lot_id=1,
                                framework_id=123))
         db.session.commit()
Exemple #22
0
def createbeneficiary():
    """
    @api {post} /beneficiary Add a new beneficiary
    @apiVersion 1.0.0
    @apiName createbeneficiary
    @apiGroup Beneficiary

    @apiParam {String}      first_name      The first name of the Beneficiary.
    @apiParam {String}      last_name       the last name of the Beneficiary.
    @apiParam {String}      email           email of Beneficiary.
    @apiParam {String}      phone_no        phone number of Beneficiary
    @apiParam {String}      password        password of Beneficiary
    @apiParam {String}      city            city name(part of address)
    @apiParam {String}      street          street number(part of address)
    @apiParam {String}      landmark        landmark description(part of address)
    @apiParam {String}      country         country name(part of address)

    @apiSuccess {String}    message         beneficiary added to database

    @apiError               message         beneficiary with that email already exists
    @apiError               message[2]         address street not provided
    @apiError               message[3]         not json
    """
    beneficiary = request.json
    if not beneficiary:
        return jsonify({"message": "not json"}), 400
    check_beneficiary = Beneficiary.query.filter_by(
        email=beneficiary.get('email')).first()
    if check_beneficiary:
        return jsonify(
            {'message': 'beneficiary with that email already exists'})
    password_hash = bcrypt.generate_password_hash(
        beneficiary.get('password')).decode('utf-8')
    username = beneficiary.get('email').split('@')[0]
    check_username = username_in_database_beneficiary(username)
    if check_username:
        while check_username:
            username = username + '1'
            check_username = username_in_database_beneficiary(username)
    u = Beneficiary(first_name=beneficiary.get('first_name'),
                    last_name=beneficiary.get('last_name'),
                    email=beneficiary.get('email'),
                    phone_no=beneficiary.get('phone_no'),
                    username=username,
                    password_hash=password_hash,
                    type=1,
                    status=0)
    address = Address(beneficiary=u,
                      city=beneficiary.get('city'),
                      street=beneficiary.get('street'),
                      country=beneficiary.get('country'),
                      landmark=beneficiary.get('landmark'))
    db.session.add(address)
    db.session.add(u)
    db.session.commit()
    return jsonify({'message': 'beneficiary added to database'}), 200
Exemple #23
0
def add_properties():
    # TODO fix not property found error
    ## get address
    address = request.form.get('address')
    address = ' '.join(address.replace(',', '').split()[:-1])

    ## get property info from Cl
    cl_sugg = suggest.Suggest()
    dets = cl_sugg.suggest_properties(address, parcel=False)
    pid = dets['suggestions'][0]['propertyId']

    ## get property details
    cl_details = details.Details()
    prop_detail = cl_details.property_attributes(pid)

    ## store property and address
    try:
        new_property = Properties(propertyId=pid,
                                  userId=current_user.id,
                                  bedrooms=prop_detail.get('beds', 0),
                                  bathrooms=prop_detail.get('baths', 0),
                                  carSpaces=prop_detail.get('carSpaces', 0),
                                  floorAreaM2=prop_detail.get('floorArea', 0),
                                  landAreaM2=prop_detail.get('landArea', 0),
                                  propertyType=prop_detail.get(
                                      'propertyType', 0),
                                  saleDate="",
                                  salePrice=0,
                                  valuation=0,
                                  valuationDate="",
                                  yearBuilt=prop_detail.get('yearBuilt', 0))

        full_add = dets['suggestions'][0]['suggestion']
        components = full_add.split()
        pc = components.pop(-1)
        sta = components.pop(-1)
        sub = components.pop(-1)
        st = " ".join(components)

        new_address = Address(property_id=pid,
                              description=full_add,
                              street=st,
                              suburb=sub,
                              state=sta,
                              postcode=pc)

        db.session.add(new_property)
        db.session.add(new_address)
        db.session.commit()

    except Exception as e:
        db.session.rollback()
    finally:
        db.session.close()

    return redirect(url_for('home_blueprint.index'))
Exemple #24
0
 def test_unknownTrue(self, newAddressDict, mockGeoResponse):
     newAddressDict.update({
         'unknown': True,
         'line1': None,
         'zip': None,
         'user_id': None
     })
     address = Address(**newAddressDict)
     assert address is not None
     assert address.city == newAddressDict['city']
Exemple #25
0
def index(request):
    address = ''
    try:
        address = request.GET['address']

        add = Address(address=address)
        add.save()
    except MultiValueDicKeyError:
        pass
    return HttpResponse('{"Hello":"' + address + '"}')
Exemple #26
0
 def save_address(self, result):
     """ Saves the address to the DB """
     address = Address(name=self.address['name'],
                       address=self.address['address'],
                       city=self.address['city'],
                       state=self.address['state'],
                       zip=self.address['zip'],
                       error=self.determine_error(result))
     db.session.add(address)
     db.session.commit()
Exemple #27
0
def checkout(request):
    addresses = Address.objects.filter(user_id=request.user.id)
    if addresses.exists():
        address = addresses[0]
    else:
        address = Address()
    return render(request, 'app/checkout.html', {
        'a': address,
        'title': 'Checkout',
        'year': datetime.now().year
    })
Exemple #28
0
 def setUp(self):
     self.app = create_app("testing")
     self.gloria = User("gloria", "*****@*****.**", "gloria")
     self.silas = User("silas", "*****@*****.**", "Nyamwaro2012")
     self.daniel = User("danielotieno", "*****@*****.**", "dan")
     self.product1 = Product("Wet Fry", "Some yummy food", 120)
     self.product2 = Product("Boiled fish", "Some yummy Fish", 200)
     self.product3 = Product("Sushi", "Hot sushi from Japan", 300)
     self.product4 = Product("Sushi", "Hot Dog stuff cooked", 400)
     self.silas_address = Address("Kisumu", "Kibuye", "0792333333")
     self.daniel_address = Address("Kisumu", "Kondele", "0700000000")
     self.gloria_address = Address("Kericho", "Kiserian", "0728828288")
     self.silas.add_address(self.silas_address)
     self.daniel.add_address(self.daniel_address)
     self.database = db
     self.database.add_user(self.gloria)
     self.database.add_user(self.silas)
     self.database.add_user(self.daniel)
     self.test_admin = User("admin", "*****@*****.**", "admin")
     self.test_admin.is_admin = True
Exemple #29
0
def newProviderDict():
    addressDict = {
        "line1": "7708 Covey Chase Dr", 'line2': '', "city": "Charlotte",
        "state": State.query.get(1), "zip": "28210", "unknown": False
    }
    testCase = {
        "name": "Smith Electric", "telephone": "704-410-3873",
        "email": "*****@*****.**", "address": Address(**addressDict),
        "categories": [Category.query.get(1), Category.query.get(2)]
    }
    return testCase
Exemple #30
0
def index():
    form = AddressForm()

    if form.validate_on_submit():
        address = Address(active=form.active.data, street_address=form.street_address.data, city=form.city.data, state=form.state.data, zip_code=form.zip_code.data, latitude=0,longitude=0, user=current_user)
        db.session.add(address)
        address.get_coordinates()
        db.session.commit()
        flash('Your address has been added!')
        return redirect(url_for('addresses.index'))
    return render_template('addresses/index.html', title='Addresses', form=form)