Beispiel #1
0
 def test_get_address(self):
     self.try_add_entities([
        Address(id=123, name='Address_1', zip=11111, address_1='address01', address_2='address02')
     ])
     res = self.try_user_operation(
         lambda: self.client.get('/api/v1/admin/addresses'))
     self.assertEqual(len(res.json), 1)
Beispiel #2
0
def save_address(address_id):
    '''
    Creates or modifies existing address
    '''
    payload = request.get_json()
    if not payload:
        abort(Response('No data was provided', status=400))

    if payload.get('zip'):
        try:
            float(payload['zip'])
        except: 
            abort(Response('Not number', status=400))

    address = None
    if address_id is None:
        address = Address()
        address.when_created = datetime.now()
        db.session.add(address)
    else:
        address = Address.query.get(address_id)
        if not address:
            abort(Response(f'No address <{address_id}> was found', status=400))

    for key, value in payload.items():

        if getattr(address, key) != value:
            setattr(address, key, value)
            address.when_changed = datetime.now()

    db.session.commit()
    return jsonify(address.to_dict())
Beispiel #3
0
def buildLawn(lawn_dict):
    lawn_name = lawn_measure = address1 = address2 = city = state = zip = country = ''
    lawn_area = 0

    if 'name' in lawn_dict:
        lawn_name = lawn_dict['name']
    if 'total_area' in lawn_dict:
        lawn_area = lawn_dict['total_area']
    if 'unit_of_measure' in lawn_dict:
        lawn_measure = lawn_dict['unit_of_measure']
    if 'address1' in lawn_dict['address']:
        address1 = lawn_dict['address']['address1']
    if 'address2' in lawn_dict['address']:
        address2 = lawn_dict['address']['address2']
    if 'city' in lawn_dict['address']:
        city = lawn_dict['address']['city']
    if 'state' in lawn_dict['address']:
        state = lawn_dict['address']['state']
    if 'zip' in lawn_dict['address']:
        zip = lawn_dict['address']['zip']
    if 'country' in lawn_dict['address']:
        country = lawn_dict['address']['country']
    
    address = Address(address1, address2, city, state, zip, country)
    lawn = Lawn(lawn_name, address, lawn_area, lawn_measure)

    return lawn
Beispiel #4
0
 def test_get_address(self):
     self.try_add_entities([
         Address(id=2)
     ])
     self.try_admin_operation(
         lambda: self.client.get('/admin/addresses/')
         )
Beispiel #5
0
 def test_delete_address(self):
     gen_id = int(datetime.now().timestamp())
     self.try_add_entities([
         Address(id=gen_id, name='Address_1', zip='11111', address_1='address01', address_2='address02')
     ])
     res = self.try_admin_operation(
         lambda: self.client.delete(f'/api/v1/admin/addresses/{gen_id}')
     )
     self.assertEqual(res.status_code, 200)
     address = Address.query.get(gen_id)
     self.assertEqual(address, None)
Beispiel #6
0
 def test_create_purchase_order(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     gen_int_id = int(datetime.now().timestamp())
     self.try_add_entities([
         Order(id=gen_id, user=self.user, status=OrderStatus.can_be_paid),
         Subcustomer(id=gen_int_id),
         Subcustomer(id=gen_int_id + 1),
         Suborder(id=gen_id, order_id=gen_id, subcustomer_id=gen_int_id),
         Suborder(id=gen_id + '1',
                  order_id=gen_id,
                  subcustomer_id=gen_int_id + 1),
         OrderProduct(suborder_id=gen_id, product_id='0000'),
         OrderProduct(suborder_id=gen_id + '1', product_id='0000'),
         Address(id=gen_int_id, zip='00000'),
         Company(id=gen_int_id, address_id=gen_int_id)
     ])
Beispiel #7
0
    def test_save_address(self):
        gen_id = int(datetime.now().timestamp())
        self.try_add_entities([
            Address(id=gen_id, name='Address_1', zip='11111', address_1='address01', address_2='address02')
        ])
        res = self.try_admin_operation(
            lambda: self.client.post(f'/api/v1/admin/addresses/{gen_id}',
            json={'zip': '22222'})
        )
        self.assertEqual(res.status_code, 200)
        address = Address.query.get(gen_id)
        self.assertEqual(address.zip, '22222')

        res = self.client.post(f'/api/v1/admin/addresses/{gen_id}',
            json={'zip': '22222@'})
        self.assertEqual(res.status_code, 400)
Beispiel #8
0
 def build_from_db_record(record):
     new_user = User(record)
     new_user.credit_card = CreditCard({
         'expire_year':
         record['credit_card']['expire']['year'],
         'expire_month':
         record['credit_card']['expire']['month'],
         'number':
         record['credit_card']['number']
     })
     new_user.address = Address({
         'country': record['address']['country'],
         'zip': record['address']['zip'],
         'street': record['address']['street'],
         'num': record['address']['num'],
     })
     return new_user
Beispiel #9
0
 def setUp(self):
     super().setUp()
     db.create_all()
     
     admin_role = Role(id=10, name='admin')
     self.try_add_entities([
         User(id=0, username='******', email='*****@*****.**',
             password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', 
             enabled=True, roles=[admin_role]),
         User(id=10, username='******', email='*****@*****.**',
             password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', 
             enabled=True),
         User(id=20, username='******', email='*****@*****.**',
             password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', 
             enabled=True),
         admin_role,
         Address()
     ])
Beispiel #10
0
    def post(self, user_id):

        # Validate user
        if User.get_by_id(user_id) is None:
            abort(404, 'User not found')

        # Create new address
        args = self.parser.parse_args()
        address = Address(user_id=user_id,
                          street=args['street'],
                          house_number=args['house_number'],
                          city=args['city'],
                          post_code=args['post_code'],
                          flat_number=args['flat_number'],
                          country=args['country'],
                          neighbourhood=args['neighbourhood'])

        # Persist and return address
        address.persist()
        return address, 201
Beispiel #11
0
 def test_create_payment_transaction(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     gen_id_int = datetime.now().microsecond
     self.try_add_entities([
         Order(id=gen_id, user=self.user),
         Currency(code='USD', name='US Dollar', rate=1),
         Address(id=gen_id_int),
         Company(id=gen_id_int, address_id=gen_id_int),
         # PaymentMethod(id=gen_id_int, payee_id=gen_id_int),
         Payment(id=gen_id_int,
                 user=self.user,
                 currency_code='USD',
                 amount_sent_krw=2600,
                 amount_received_krw=2600)
     ])
     res = self.try_admin_operation(
         lambda: self.client.post(f'/api/v1/admin/payment/{gen_id_int}',
                                  json={'status': 'approved'}))
     self.assertEqual(res.status_code, 200)
     transaction = Transaction.query.first()
     self.assertEqual(transaction.amount, 2600)
     self.assertEqual(self.user.balance, 2600)
def createProvider():
    providerForm = ProviderForm()
    contactForm = ContactForm()
    addressForm = AddressForm()

    if providerForm.validate_on_submit():
        address = Address(addressForm.street.data, addressForm.number.data,
                          addressForm.complement.data,
                          addressForm.district.data, addressForm.city.data,
                          addressForm.state.data, addressForm.country.data,
                          addressForm.postal_code.data)

        db.session.add(address)
        db.session.commit()

        provider = Provider(providerForm.trading_name.data,
                            providerForm.company_name.data,
                            providerForm.document_number.data,
                            providerForm.cnae.data, providerForm.ie.data,
                            providerForm.im.data, address.id)

        db.session.add(provider)
        db.session.commit()

        contact = Contact(contactForm.phone.data, contactForm.email.data,
                          contactForm.employee_name.data,
                          contactForm.employee_department.data, provider.id)

        db.session.add(contact)
        db.session.commit()

        flash('Fornecedor cadastrado com sucesso!', 'success')
        return redirect(url_for('indexProvider'))

    return render_template('provider/form.html',
                           providerForm=providerForm,
                           contactForm=contactForm,
                           addressForm=addressForm)
Beispiel #13
0
 def test_create_payment(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     gen_id_int = datetime.now().microsecond
     self.try_add_entities([
         Order(id=gen_id, user=self.user),
         Currency(code='USD', name='US Dollar', rate=1),
         Address(id=gen_id_int),
         Company(id=gen_id_int, address_id=gen_id_int),
         PaymentMethod(id=gen_id_int, payee_id=gen_id_int)
     ])
     res = self.try_user_operation(
         lambda: self.client.post('/api/v1/payment',
                                  json={
                                      'orders': [gen_id],
                                      'amount_sent_original': 100,
                                      'currency_code': 'USD',
                                      'payment_method': {
                                          'id': gen_id_int
                                      }
                                  }))
     self.assertEqual(Payment.query.count(), 1)
     transaction = Payment.query.first()
     self.assertEqual(transaction.amount_sent_krw, 100)
Beispiel #14
0
    def post(self):
        ''' Create an address '''
        arguments = request.get_json(force=True)
        district = arguments.get('district').strip()
        postal = arguments.get('postal').strip() or None
        country = arguments.get('country').strip() or None
        address_line_1 = arguments.get('address1').strip() or None
        address_line_2 = arguments.get('address1').strip() or None

        if not address_line_1:
            return abort(400, 'Address cannot be empty!')
        try:
            address = Address(
                district=district,
                postal_code=postal,
                country=country,
                address_line_1=address_line_1,
                address_line_2=address_line_2
                )
            if address.save_address():
                return {'message': 'Address created successfully!'}, 201
            return abort(409, message='Address already exists!')
        except Exception as e:
            abort(400, message='Failed to create new address -> {}'.format(e))
Beispiel #15
0
def register_barber_shop():
    try:
        session = current_app.db.session

        request_data = request.get_json()

        error_list = []

        if request_data:
            if not Barber_shop.query.filter_by(
                    name=request_data["name"]).first():
                name = request_data["name"]
            else:
                error_list.append("name")

            if not Barber_shop.query.filter_by(
                    phone_number=request_data["phone_number"]).first():
                phone_number = request_data["phone_number"]
            else:
                error_list.append("phone_number")

            if not Barber_shop.query.filter_by(
                    cnpj=request_data["cnpj"]).first():
                cnpj = request_data["cnpj"]
            else:
                error_list.append("cnpj")

            if not Barber_shop.query.filter_by(
                    email=request_data["email"]).first():
                email = request_data["email"]
            else:
                error_list.append("email")

            if error_list:
                raise NameError(error_list)

            barber_shop = Barber_shop(
                name=name,
                phone_number=phone_number,
                cnpj=cnpj,
                email=email,
                user_type="barber_shop",
            )

            barber_shop.password = request_data["password"]

            address = Address(
                state=request_data["address"]["state"],
                city=request_data["address"]["city"],
                street_name=request_data["address"]["street_name"],
                building_number=request_data["address"]["building_number"],
                zip_code=request_data["address"]["zip_code"],
            )

            session.add(barber_shop)
            session.add(address)
            session.commit()

            address.barber_shop_id = barber_shop.id

            session.commit()

            barber_shop_serialized = BarberSchema().dump(barber_shop)

            address_serializer = AddressSchema().dump(address)

            barber_shop_serialized["address"] = address_serializer

            return {"data": barber_shop_serialized}, HTTPStatus.CREATED

        else:
            return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST

    except IntegrityError as e:
        error_origin = e.orig.diag.message_detail
        error = re.findall("\((.*?)\)", error_origin)

        return {"msg": f"{error[0].upper()} already registered"}, HTTPStatus.OK

    except KeyError:
        return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST

    except NameError as e:
        unique = e.args[0]
        errors = ""
        for error in unique:
            errors = errors + f"{error}, "

        return {"msg": f"{errors}already registered"}, HTTPStatus.BAD_REQUEST

    except DataError:
        return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST
Beispiel #16
0
 def __init__(self, name, address = Address(), total_area = 0, unit_of_measurement = ''):
     self.id = ''
     self.address = address
     self.name = name
     self.total_area = total_area
     self.unit_of_measurement = unit_of_measurement
from app.models.lawn import Lawn
from app.models.address import Address

ADDRESSES = [
    Address('123 Main St.', '', 'Chicago', 'IL', '12345', 'USA'),
    Address('555 Fifth St.', 'Apt 2', 'New York', 'NY', '12345', 'USA'),
    Address('20445 Royal Road', '', 'LONDON', 'WIP', '6HQ', 'ENGLAND'),
    Address('4545 Continental Cir', '', '', 'St Paul', '06570', 'France')
]

LAWNS = [
    Lawn('Home', ADDRESSES[0], 5000, 'sq. ft'),
    Lawn('Parents', ADDRESSES[1], 1200, 'sq. ft'),
    Lawn('Summer Home', ADDRESSES[2], 500, 'sq m'),
    Lawn('Somewhere else', ADDRESSES[3], 1000, 'sq m')
]
Beispiel #18
0
from run import app
from app.db import db
from app.models.address import Address
from app.models.person import Person

with app.app_context():
    email1 = 'teste3@teste'
    owner = Person.find_by_name('Paulo')
    address = Address(email=email1, owner=owner)
    db.session.add(address)
    db.session.commit()
Beispiel #19
0
class PropertyForm(FlaskForm):
    address = FormField(AddressForm, default=lambda: Address())
    sq_foot = IntegerField('What is the square footage of the home?',
                           description='Do not include basement, \
                                        non-permitted additions, or \
                                        non-heated square footage.',
                           validators=[Optional()])
    year_built = IntegerField('What year was the home built?',
                              description='(For example, 2001)',
                              validators=[Optional()])
    stories_count = RadioField('How many stories does the home have?',
                               description="Don't include a basement... \
                                            We will git to that later.",
                               choices=[
                                    ('1', 'One story'),
                                    ('2', 'Two story'),
                                    ('3', 'Three story')],
                               validators=[Optional()])
    basement_type = RadioField('Does the home have a basement?',
                               description='A basement is a level that is \
                                            either completely or partially \
                                            below the ground floor. Finished \
                                            means that the space is sutable \
                                            for living, with fully finished \
                                            walls, flooring, as well as air \
                                            conditioning and heating.',
                               choices=[
                                    ('none', 'No Basement'),
                                    ('unfinished', 'Unfinished Basement'),
                                    ('partial', 'Partially Finished Basement'),
                                    ('finished', 'Finished Basement')
                               ],
                               validators=[Optional()])
    addition_type = RadioField('Have you or the previous owners made \
                                additions to the structure of the home?',
                               description='Additions include garages that \
                                            may have been converted, \
                                            sunrooms, bonus rooms, or any \
                                            other living area extensions.',
                               choices=[
                                    ('none', 'No additions'),
                                    ('additions-no-permits',
                                        'Additions without permits'),
                                    ('garage-no-permit',
                                        'Garage conversion without permits'),
                                    ('porch-no-permit',
                                        'Porch conversion without permits'),
                                    ('additions-with-permits',
                                        'Additions with permits'),
                                    ('garage-with-pemrit',
                                        'Garage conversion with permits'),
                                    ('porch-with-permit',
                                        'Porch conversion with permits')
                               ],
                               validators=[Optional()])
    bedroom_count = RadioField('How many bedrooms does the home have?',
                               description='A room counts as a bedroom if \
                                            it has a closet, door, \
                                            and window.',
                               choices=[
                                    ('0', 'Studio'),
                                    ('1', '1 Bed'),
                                    ('2', '2 Beds'),
                                    ('3', '3 Beds'),
                                    ('4', '4 Beds'),
                                    ('5', '5+ Beds')
                               ],
                               validators=[Optional()])
    full_bath_count = RadioField('How many full bathrooms does the home have?',
                                 description='A room counts as a full \
                                              bathroom if it includes a \
                                              toilet, sink and \
                                              bathtub/shower.',
                                 choices=[
                                    ('1', '1'),
                                    ('2', '2'),
                                    ('3', '3'),
                                    ('4', '4'),
                                    ('5', '5+')
                                 ],
                                 validators=[Optional()])
    half_bath_count = RadioField('How many half bathrooms does the home have?',
                                 description='A room counts as a half \
                                              bathroom if it includes a \
                                              toilet and sink but no \
                                              bathtub/shower.',
                                 choices=[
                                    ('0', '0'),
                                    ('1', '1'),
                                    ('2', '2'),
                                    ('3', '3'),
                                    ('4', '4'),
                                    ('5', '5+')
                                 ],
                                 validators=[Optional()])
    parking_type = RadioField('What kind of parking or garage does the \
                               home have?',
                              choices=[
                                ('single', '1-Car Garage'),
                                ('double', '2-Car Garage'),
                                ('triple', '3-Car Garage'),
                                ('quad', '4-Car Garage'),
                                ('1carport', '1 Carport'),
                                ('2carport', '2 Carport'),
                                ('outside', 'Outside'),
                                ('street', 'Street'),
                                ('other', 'Other')
                              ],
                              validators=[Optional()])
    countertops = RadioField('What kind of countertops are in the kitchen?',
                             description='Select the option that most closely \
                                          describes your counter tops.',
                             choices=[
                                ('granite-slab', 'Granite Slab'),
                                ('granite-tile', 'Granite Tile'),
                                ('quartz', 'Quartz'),
                                ('corian', 'Corian'),
                                ('laminate', 'Laminate'),
                                ('tile', 'Tile')
                             ],
                             validators=[Optional()])
    appliances = RadioField('What kind of appliances does the kitchen have?',
                            choices=[
                                ('stainless', 'Stainless Steel'),
                                ('black', 'Black'),
                                ('white', 'White'),
                                ('mixed', 'Mixed')
                            ],
                            validators=[Optional()])
    double_oven_ind = BooleanField('Double oven')
    walk_in_pantry_ind = BooleanField('Walk-in pantry')
    separate_cooktop_ind = BooleanField('Separate cooktop')
    built_in_oven_ind = BooleanField('Built-in wall oven')
    built_in_microwave_ind = BooleanField('Built-in microwave')
    kitchen_flooring = RadioField('What type of flooring is used in \
                                   the kitchen?',
                                  description='Select the option that most \
                                               closely matches the flooring.',
                                  choices=[
                                    ('tile', 'Tile'),
                                    ('vinyl', 'Vinyl'),
                                    ('laminate', 'Laminate'),
                                    ('hardwood', 'Hardwood'),
                                    ('travertine', 'Travertine'),
                                    ('saltillo-tile', 'Saltillo Tile'),
                                    ('carpet', 'Carpet'),
                                    ('woodplank-tile', 'Woodplank Tile'),
                                    ('concrete', 'Concrete'),
                                    ('other', 'other')
                                  ],
                                  validators=[Optional()])
    main_flooring = RadioField('What type of flooring is used in the main \
                                living areas?',
                               description='Select the option that most \
                                            closely matches the flooring.',
                               choices=[
                                    ('tile', 'Tile'),
                                    ('vinyl', 'Vinyl'),
                                    ('laminate', 'Laminate'),
                                    ('hardwood', 'Hardwood'),
                                    ('travertine', 'Travertine'),
                                    ('saltillo-tile', 'Saltillo Tile'),
                                    ('carpet', 'Carpet'),
                                    ('woodplank-tile', 'Woodplank Tile'),
                                    ('concrete', 'Concrete'),
                                    ('other', 'other')
                               ],
                               validators=[Optional()])
    bathroom_flooring_tile_ind = BooleanField('Tile')
    bathroom_flooring_vinyl_ind = BooleanField('Vinyl')
    bathroom_flooring_laminate_ind = BooleanField('Laminate')
    bathroom_flooring_hardwood_ind = BooleanField('Hardwood')
    bathroom_flooring_travertine_ind = BooleanField('Travertine')
    bathroom_flooring_saltillo_tile_ind = BooleanField('Saltillo Tile')
    bathroom_flooring_carpet_ind = BooleanField('Carpet')
    bathroom_flooring_woodplank_tile_ind = BooleanField('Woodplank Tile')
    bathroom_flooring_concrete_ind = BooleanField('Concrete')
    bathroom_flooring_other_ind = BooleanField('Other')
    bedroom_flooring_tile_ind = BooleanField('Tile')
    bedroom_flooring_vinyl_ind = BooleanField('Vinyl')
    bedroom_flooring_laminate_ind = BooleanField('Laminate')
    bedroom_flooring_hardwood_ind = BooleanField('Hardwood')
    bedroom_flooring_travertine_ind = BooleanField('Travertine')
    bedroom_flooring_saltillo_tile_ind = BooleanField('Saltillo Tile')
    bedroom_flooring_carpet_ind = BooleanField('Carpet')
    bedroom_flooring_woodplank_tile_ind = BooleanField('Woodplank Tile')
    bedroom_flooring_concrete_ind = BooleanField('concrete')
    bedroom_flooring_other_ind = BooleanField('other')
    landscaping = RadioField('Does the home have landscaping?',
                             choices=[
                                ('none', 'None'),
                                ('both', 'Both front and back yard'),
                                ('front', 'Front yard only'),
                                ('back', 'Back yard only')
                             ],
                             validators=[Optional()])
    pool = RadioField('Does the home have an in-ground pool?',
                      choices=[
                         (True, 'Yes'),
                         (False, 'No')
                      ], coerce=lambda x: x == 'True',
                      validators=[Optional()])
    hottub = RadioField('Does the home have an in-ground spa / hot tub?',
                        choices=[
                           (True, 'Yes'),
                           (False, 'No')
                        ], coerce=lambda x: x == 'True',
                        validators=[Optional()])
    gated_community_ind = BooleanField('Gated Community')
    hoa_ind = BooleanField('Homeowners Association')
    age_restricted_ind = BooleanField('Age Restricted')
    solar_panels_ind = BooleanField('Solar Panels')
    septic_system_ind = BooleanField('Septic System')
    well_water_ind = BooleanField('Well Water')
    poor_location_ind = BooleanField('The property backs to a busy road, \
                                      commercial buildings, or power lines')
    sinkholes_ind = RadioField('Are you aware of sinkholes on the property?',
                               choices=[
                                  (True, 'Yes'),
                                  (False, 'No')
                               ], coerce=lambda x: x == 'True',
                               validators=[Optional()])
    foundation_issues = RadioField('Are there foundation issues?',
                                   choices=[
                                    (True, 'Yes'),
                                    (False, 'No')
                                   ], coerce=lambda x: x == 'True',
                                   validators=[Optional()])
    additional_info = TextAreaField('Is there anything else you would like to \
                                     tell us?',
                                    description='This field is optional but \
                                                it gives you teh opportunity \
                                                to tell us what is special \
                                                about the home. \
                                                (Max 1500 characters)')
    submitter_type = RadioField('What is your relationship to this home?',
                                choices=[
                                    ('owner', 'Owner'),
                                    ('agent', 'Real Estate Agent'),
                                    ('other', 'Other')
                                ],
                                validators=[Optional()])
    listed_ind = RadioField('Is this home listed on the MLS?',
                            choices=[
                               (True, 'Yes'),
                               (False, 'No')
                            ], coerce=lambda x: x == 'True',
                            validators=[Optional()])
    submitter_first_name = StringField('First Name',
                                       validators=[DataRequired()])
    submitter_last_name = StringField('Last Name',
                                      validators=[DataRequired()])
    submitter_phone = StringField('Phone',
                                  validators=[DataRequired()])
    submitter_email = StringField('Email',
                                  validators=[DataRequired()])
Beispiel #20
0
    def mutate(
        cls,
        _,
        info,
        mission_id,
        type,
        company_known_address_id=None,
        geo_api_data=None,
        manual_address=None,
        kilometer_reading=None,
    ):
        with atomic_transaction(commit_at_end=True):
            if (int(company_known_address_id is not None) +
                    int(geo_api_data is not None) +
                    int(manual_address is not None) != 1):
                raise InvalidParamsError(
                    "Exactly one of companyKnownAddressId or geoApiData or manualAddress should be set"
                )

            mission = Mission.query.get(mission_id)

            company_known_address = None
            if company_known_address_id:
                company_known_address = CompanyKnownAddress.query.get(
                    company_known_address_id)
                if (not company_known_address
                        or company_known_address.company_id !=
                        mission.company_id):
                    raise InvalidParamsError("Invalid companyKnownAddressId")
                address = company_known_address.address
            elif geo_api_data:
                address = Address.get_or_create(geo_api_data)
            else:
                address = Address(manual=True, name=manual_address)
                db.session.add(address)

            existing_location_entry = [
                l for l in mission.location_entries if l.type == type
            ]
            existing_location_entry = (existing_location_entry[0]
                                       if existing_location_entry else None)

            if existing_location_entry:
                are_addresses_equal = (
                    address.name == existing_location_entry.address.name if
                    address.manual and existing_location_entry.address.manual
                    else address == existing_location_entry.address)
                if are_addresses_equal:
                    if kilometer_reading:
                        existing_location_entry.register_kilometer_reading(
                            kilometer_reading)
                    return existing_location_entry
                raise MissionLocationAlreadySetError()

            now = datetime.now()

            location_entry = LocationEntry(
                _address=address,
                mission=mission,
                reception_time=now,
                submitter=current_user,
                _company_known_address=company_known_address,
                type=type,
            )
            location_entry.register_kilometer_reading(kilometer_reading, now)
            db.session.add(location_entry)

        return location_entry
Beispiel #21
0
    def post(self):
        ''' Create a company '''
        arguments = request.get_json(force=True)
        name = arguments.get('name').strip()
        district = arguments.get('district').strip() or None
        postal = arguments.get('postal').strip() or None
        country = arguments.get('country').strip() or None
        tech_person_name_string = arguments.get(
            'techPersonName').strip() or None
        tech_person_email = arguments.get('techPersonEmail').strip() or None
        address_line_1 = arguments.get('address1').strip() or None
        address_line_2 = arguments.get('address2').strip() or None
        legal_person_name_str = arguments.get(
            'legalPersonName').strip() or None
        legal_person_email = arguments.get('legalPersonEmail').strip() or None
        tech_person_name = tech_person_name_string.split()
        legal_person_name = legal_person_name_str.split()

        if not name:
            return abort(400, 'Name cannot be empty!')
        try:
            address = Address(
                district=district,
                postal_code=postal,
                country=country,
                address_line_1=address_line_1,
                address_line_2=address_line_2
                )
            tech_person = Person(tech_person_name[0], tech_person_name[-1])
            legal_person = Person(legal_person_name[0], legal_person_name[-1])
            tech_contact = Contact(email=tech_person_email)
            legal_contact = Contact(email=legal_person_email)

            if not address.save_address():
                address = Address.query.filter_by(
                    address_line_1=address.address_line_1,
                    active=True).first()
            if not tech_person.save_person():
                tech_person = Person.query.filter_by(
                    full_name=tech_person_name_string).first()
            if not legal_person.save_person():
                legal_person = Person.query.filter_by(
                    full_name=legal_person_name_str).first()
            if not tech_contact.save_contact():
                tech_contact = Contact.query.filter_by(
                    email=tech_person_email).first()
            if not legal_contact.save_contact():
                legal_contact = Contact.query.filter_by(
                    email=legal_person_email).first()
            tech_contact_person = ContactPerson(
                person=tech_person,
                contact=tech_contact)
            legal_contact_person = ContactPerson(
                person=legal_person,
                contact=legal_contact)
            if not tech_contact_person.save_contact_person():
                tech_contact_person = ContactPerson.query.filter_by(
                    person=tech_person,
                    contact=tech_contact).first()
            if not legal_contact_person.save_contact_person():
                legal_contact_person = ContactPerson.query.filter_by(
                    person=legal_person,
                    contact=legal_contact).first()

            company = Company(
                name=name,
                address=address,
                legal_person=legal_contact_person,
                tech_person=tech_contact_person
                )
            if company.save_company():
                return {'message': 'Company created successfully!'}, 201
            return abort(409, message='Company already exists!')
        except Exception as e:
            abort(400, message='Failed to create new company -> {}'.format(e))