def add_fake_data(count):
    """
    Adds fake data to the database.
    """
    User.generate_fake(count=count)
    ZIPCode.generate_fake()
    Resource.generate_fake()
    ResourceReview.generate_fake(count=count)
    Address.generate_fake()
    AffiliationTag.generate_default()

    # Set a random zip for each user without one.
    User.set_random_zip_codes(User.query.filter_by(zip_code=None).all(),
                              ZIPCode.query.all())
    # Set a random affiliation tag for each user.
    User.set_random_affiliation_tags(User.query.all(),
                                     AffiliationTag.query.all())
Beispiel #2
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']
Beispiel #3
0
def address(request):
    if request.POST:
        street = request.POST.get('street')
        address2 = request.POST.get('address2')
        city = request.POST.get('city')
        zip = request.POST.get('zip')
        state = request.POST.get('state')
        country = request.POST.get('country')
        request.session['street'] = street
        request.session['address2'] = address2
        request.session['city'] = city
        request.session['zip'] = zip
        request.session['state'] = state
        request.session['country'] = country
        add_obj = Address(street=street, address2=address2, city=city, zip=zip, state=state, country=country)
        add_obj.save()
        return HttpResponseRedirect('/gopay/')
    else:
        return render(request, 'address.html')
Beispiel #4
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()
Beispiel #5
0
def process_checkout(request):
    addresses = Address.objects.filter(user_id=request.user.id)
    if addresses.exists():
        address = addresses[0]
        address.first_name = request.POST.get('first_name')
        address.last_name = request.POST.get('last_name')
        address.address_line_1 = request.POST.get('address_line_1')
        address.address_line_2 = request.POST.get('address_line_2')
        address.city = request.POST.get('city')
        address.province = request.POST.get('province')
        address.postal_code = request.POST.get('postal_code')
        address.phone_number = request.POST.get('phone_number')
    else:
        address = Address(first_name=request.POST.get('first_name'),
                          last_name=request.POST.get('last_name'),
                          address_line_1=request.POST.get('address_line_1'),
                          address_line_2=request.POST.get('address_line_2'),
                          city=request.POST.get('city'),
                          province=request.POST.get('province'),
                          postal_code=request.POST.get('postal_code'),
                          phone_number=request.POST.get('phone_number'),
                          user_id=request.user.id)
    address.save()

    carts = Cart.objects.filter(
        user_id=request.user.id).order_by('-created_on')
    if carts.exists():
        cart = carts[0]
        order = Order(user_id=cart.user_id)
        order.save()
        for cartItem in cart.cartitem_set.all():
            orderItem = OrderItem(product_id=cartItem.product.id,
                                  product_title=cartItem.product.title,
                                  product_image=cartItem.product.image.url,
                                  order=order,
                                  unit_price=cartItem.unit_price,
                                  quantity=cartItem.quantity,
                                  total=cartItem.total)
            orderItem.save()
        cart.delete()

    return redirect(checkout_success)
    def test_address(self):
        with self.app.app_context():
            u0 = User(username='******',
                      email='*****@*****.**',
                      first_name='zack',
                      last_name='zhu')
            addr0 = Address(primary_street='12345 ABC st',
                            city='XYZ',
                            state='FL',
                            zipcode='12345',
                            country='USA',
                            creator=u0)
            db.session.add(addr0)
            db.session.commit()

        rp = self.test_client.get('/api/v1/addresses/1')
        # print_json(rp.data)

        rp = self.test_client.post(
            '/api/v1/addresses',
            data=json.dumps(
                dict(creator_id=2,
                     primary_street='789 WWWW LN',
                     city='XYZ',
                     state='FL',
                     zipcode='12345',
                     country='USA')),
            content_type='application/json',
        )
        # print_json(rp.data)

        rp = self.test_client.post(
            '/api/v1/addresses',
            data=json.dumps(
                dict(creator_id=1,
                     primary_street='789 WWWW LN',
                     city='XYZ',
                     state='FL',
                     zipcode='12345',
                     country='USA')),
            content_type='application/json',
        )
        # print_json(rp.data)

        rp = self.test_client.patch(
            '/api/v1/addresses/2',
            data=json.dumps(
                dict(
                    creator_id=2,
                    primary_street='1234 WWWW LN',
                    secondary_street='APT 123',
                )),
            content_type='application/json',
        )
Beispiel #7
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
Beispiel #8
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
Beispiel #9
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
    })
Beispiel #10
0
    def post(self, request):
        """
        create a new user with addresses
        """
        form = UserAddress(request.POST)
        if form.is_valid():
            try:
                address = Address()
                fk_user = User.objects.get(user=form.cleaned_data['user'])
                address.user = fk_user
                address.address = form.cleaned_data['address']
                address.save()
            except User.DoesNotExist:
                User(user=form.cleaned_data['user']).save()
                address = Address()
                fk_user = User.objects.get(user=form.cleaned_data['user'])
                address.user = fk_user
                address.address = form.cleaned_data['address']
                address.save()

        return redirect('/')
Beispiel #11
0
def save():
    '''
    Save a new or an existing organisation
    :return: User's organisations home page
    '''
    form = OrganisationForm()
    if form.validate_on_submit():
        # check if user is trying to edit
        id = request.form['id']
        new = id == "-1"
        user_can_edit = not new and user_has_rights(id)

        if not new and not user_has_rights(id):
            error = "Not allowed to edit this organisation"
            return to_403(error)

        # Create/get organisation
        if new:
            organisation = Organisation(
                name=request.form['name'],
                manager_name=request.form['manager_name'])
            organisation.users.append(g.user)
            db.session.add(organisation)
            db.session.commit()
        else:
            organisation = Organisation.query.get_or_404(id)
            organisation.name = request.form['name']
            organisation.manager_name = request.form['manager_name']

        if new:
            address = Address(address=request.form['address'],
                              city=request.form['city'],
                              province=request.form['province'],
                              country=request.form['country'],
                              postal_code=request.form['postal_code'],
                              organisation_id=organisation.id)
            db.session.add(address)
        else:
            address = organisation.addresses.first()
            address.address = request.form['address']
            address.city = request.form['city']
            address.province = request.form['province']
            address.country = request.form['country']
            address.postal_code = request.form['postal_code']
            address.organisation_id = organisation.id

        db.session.commit()

        flash(organisation.name + " has been saved")
        return redirect(url_for('organisations.index'))
Beispiel #12
0
    def load(self, data, many=None, partial=None):

        de_data = super().load(data, many=many, partial=partial)
        de_data = [de_data] if not many else de_data

        for de_data_item in de_data:
            location_dicts = de_data_item.get('locations')
            if location_dicts is None:
                continue
            locations = []
            for loc_dict in location_dicts:
                id = loc_dict.get('id')
                print(id)
                loc = None
                if id:
                    loc = Address.get_with_id(id)
                else:
                    loc = Address.create(commit=False, **loc_dict)
                locations.append(loc)
            de_data_item['locations'] = locations

        return de_data if many else de_data[0]
Beispiel #13
0
def addresses():
    '''
    GET: Returns all addresses.
    POST: Creates an address.
    '''

    if request.method == 'POST':
        json = request.get_json()
        address = Address.create(json)
        return jsonify(address.json), status.HTTP_201_CREATED

    addresses = Address.query.all()
    return jsonify({'addresses': unpack_json(addresses)}), status.HTTP_200_OK
Beispiel #14
0
def siteAdd():
    form = AddressForm()
    if form.validate_on_submit():
        data = form.data
        address = Address(name=data["name"],
                          phone=data["phone"],
                          address=data["address"],
                          user_id=session["userid"])
        db.session.add(address)
        db.session.commit()
        flash("添加成功!")
        return redirect(url_for('home.siteList', page=1))
    return render_template("home/user_center_site.html", form=form)
Beispiel #15
0
def new_address():
    form = NewAddressForm()
    if form.validate_on_submit():
        address = Address(name=form.name.data,
                          address=form.address.data,
                          city=form.city.data,
                          state=form.state.data,
                          zip=form.zip.data)
        db.session.add(address)
        db.session.commit()
        flash('{} has been added to your addresses.'.format(form.address.data))
        return redirect(url_for('addresses_index'))
    return render_template('new_address.html', title="New Address", form=form)
Beispiel #16
0
def add_speaker():
    form = SpeakerForm()
    if form.validate_on_submit():
        address = Address(street=form.street.data, city=form.city.data, state=form.state.data,
                          zip=form.zip.data)
        speaker = Speaker(first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data,
                          phone=form.phone.data)
        db.session.add(speaker)
        db.session.commit()
        speaker.address = address
        db.session.commit()
        flash("Speaker Saved.")
        return redirect(url_for('index'))
    return render_template('add_speaker.html', title='Add Speaker', form=form)
Beispiel #17
0
 def post(self):
     """Create a new order"""
     args = self.parser.parse_args()
     address_id = args.get("address", "")
     items = args.get("items", "")
     customer_id = details(claims).get("id", "0")
     if empty(address_id) or empty(items):
         return {
             "message": "Please specify an address and a list of"
             " items"
         }, 400
     address = Address.find_by_id(address_id=address_id,
                                  user_id=customer_id)
     if not address or len(address) == 0:
         return {
             "message":
             "The address you provided is not valid"
             " please check your addresses and give a"
             " valid id"
         }, 400
     items = items.split(",")
     new_items = [int(item) for item in items if item.strip() != '']
     copy_items = set(new_items)
     new_items = list(new_items)
     ordered_items = []
     total = 0.00
     for item in copy_items:
         item_object = Menu.find_by_id(meal_id=item)
         if item_object is None:
             return {
                 "message":
                 "The item with id %s does not exist."
                 ". Try another" % item
             }, 404
         item_object.quantity = new_items.count(item)
         total += float(item_object.price * item_object.quantity)
         ordered_items.append(item_object)
     order = Order(customer_id, address_id, ordered_items)
     order.total = total
     saved = order.save()
     if not saved:
         return {
             "message":
             "There was a problem placing the order please try again"
         }, 400
     return {
         "message": "The order was successfully placed",
         "order": order.json1
     }, 200
Beispiel #18
0
def addAdd():
    if request.method == 'POST':
        data = request.get_json()['data']
        cur_order = Order.query.filter_by(cart_id=data['cart_id']).first()
        data = data['form']
        new_add = Address(order_id=cur_order.id,
                          firstname=data['fname'],
                          lastname=data['lname'],
                          add1=data['add1'],
                          add2=data['add2'],
                          city=data['city'],
                          zipcode=data['zip'])
        db.session.add(new_add)
        db.session.commit()
    return jsonify({"success": True})
Beispiel #19
0
def track_address(addresse):
    if Address.query.filter_by(address=addresse).scalar() is None:
        address1 = build(addresse)
        address2 = Address(address=address1.address, comment=address1.comment, n_tx=address1.n_tx,
        total_received=address1.total_received, last_tx=datetime.utcfromtimestamp(address1.last_tx_date), author=current_user, total_sent=address1.total_sent, balance=address1.balance)
        db.session.add(address2)
        db.session.commit()
    addressquery = Address.query.filter_by(address=addresse).first()
    if addressquery is None:
        flash('Address not found')
    current_user.track_address(addressquery)
    db.session.commit()
    flash('You are now tracking {}!'.format(addresse))
    
    return redirect(url_for('show_address_details', address=addresse, addressobj = addressquery))
Beispiel #20
0
def confirm_address():
    data = (cg.address(request.form.get('address'), city=request.form.get('city'), state=request.form.get('state'),
                       zipcode=request.form.get('zipcode')))
    id = []
    context = {
        'data': data,
    }
    if request.method == "POST":
        address = Address(address=data[0]['matchedAddress'], census_tract=data[0]['geographies']['Census Tracts'][0]['BASENAME'], latitude=data[0]['geographies']['Census Tracts'][0]['CENTLAT'], longitude=data[0]['geographies']['Census Tracts'][0]['CENTLON'], zip=data[0]['addressComponents']['zip'])
        db.session.add(address)
        db.session.commit()
        id = address.id
        session['confirm_address_id']=id
        print(session['confirm_address_id'])
    return render_template('confirm_address.html', **context)
Beispiel #21
0
def add_event():
    form = EventForm()
    form.speakers.query_factory = speaker_query
    if form.validate_on_submit():
        address = Address(street=form.street.data, city=form.city.data, state=form.state.data, zip=form.zip.data)
        event = Event(topic=form.topic.data, date=form.date.data)
        db.session.add(event)
        db.session.commit()
        event.address = address
        for speaker in form.speakers.data:
            event.speakers.append(speaker)
        db.session.commit()
        flash("Event Saved.")
        return redirect(url_for('index'))
    return render_template('add_event.html', title='Add Event', form=form)
Beispiel #22
0
    def post(self):
        json_data = request.get_json()
        if not json_data:
            raise RequestException("No input data", 400)
        try:
            data = address_schema.load(json_data)
        except ValidationError as err:
            raise RequestException("Invalid input data", 400, err.messages)
        address = Address.create(**data)
        result = address_schema.dump(address)
        response = jsonify({
            APIConst.MESSAGE: 'created new address',
            APIConst.DATA: result
        })

        return response
    def setup(self):
        super(TestShouldCallSearchApiOnPutToCreateService, self).setup()

        with self.app.app_context():
            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.commit()
def add_address():
    form = EditAddressForm()
    if form.validate_on_submit():
        address = Address(name=form.name.data,
                          address_one=form.address_one.data,
                          address_two=form.address_two.data,
                          postal_code=form.postal_code.data,
                          city=form.city.data,
                          author=current_user)
        db.session.add(address)
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('add_address'))
    return render_template('edit_address.html',
                           title='Add an Address',
                           form=form)
Beispiel #25
0
def get_create_address_for_user(public_id, request):

    # check input is valid json
    try:
        data = request.get_json()
    except:
        return jsonify(
            {'message': 'Check ya inputs mate. Yer not valid, Jason'}), 400

    # validate input against json schemas
    try:
        country_data = {'iso_code': data.get('iso_code')}
        assert_valid_schema(country_data, 'country')
        assert_valid_schema(data, 'address')

    except JsonValidationError as err:
        return jsonify({
            'message': 'Check ya inputs mate.',
            'error': err.message
        }), 400

    country = Country.query.filter_by(
        iso_code=country_data.get('iso_code')).first()
    address = Address(public_id=public_id,
                      address_id=str(uuid.uuid4()),
                      house_name=data.get('house_name'),
                      house_number=data.get('house_number'),
                      address_line_1=data.get('address_line_1'),
                      address_line_2=data.get('address_line_2'),
                      address_line_3=data.get('address_line_3'),
                      state_region_county=data.get('state_region_county'),
                      post_zip_code=data.get('post_zip_code'),
                      country_id=country.id)

    try:
        db.session.add(address)
        db.session.flush()
        db.session.commit()
    except (SQLAlchemyError, DBAPIError) as e:
        db.session.rollback()
        return jsonify({'message':
                        'oopsy, something went wrong at our end'}), 422

    message = {}
    message['message'] = 'address created successfully'
    message['address_id'] = address.address_id
    return jsonify(message), 201
Beispiel #26
0
def listblocks() -> int:
    """Synch block data from node

    :return int: number of new blocks synched to database
    """

    # TODO: Handle blockchain forks gracefully

    client = get_active_rpc_client()

    height_node = client.getblockcount()['result']
    latest_block_obj = Block.select().order_by(Block.height.desc()).first()
    if latest_block_obj is None:
        height_db = 0
    else:
        height_db = latest_block_obj.height

    if height_db == height_node:
        return 0

    synced = 0

    for batch in batchwise(range(height_db, height_node), 100):

        new_blocks = client.listblocks(batch)

        with data_db.atomic():
            for block in new_blocks['result']:

                addr_obj, adr_created = Address.get_or_create(
                    address=block['miner'])
                block_obj, blk_created = Block.get_or_create(
                    hash=unhexlify(block['hash']),
                    defaults=dict(
                        time=datetime.fromtimestamp(block['time']),
                        miner=addr_obj,
                        txcount=block['txcount'],
                        height=block['height'],
                    ))
                if blk_created:
                    synced += 1

                log.debug('Synced block {}'.format(block_obj.height))
                signals.database_blocks_updated.emit(block_obj.height,
                                                     height_node)
    log.debug('Synced {} blocks total.'.format(synced))
    return synced
Beispiel #27
0
def add_address():
    form = AddressForm()
    if form.validate_on_submit():
        address = Address(first_name=form.first_name.data.title(),
                          last_name=form.last_name.data.title(),
                          address=form.address.data.title(),
                          city=form.city.data.title(),
                          state=form.state.data,
                          zip_code=form.zip_code.data,
                          user_id=current_user.id)
        db.session.add(address)
        db.session.commit()
        return redirect(url_for('address_book'))

    return render_template('address_form.html',
                           form=form,
                           form_title='Add A New Address')
Beispiel #28
0
    def setup(self):
        super(TestPutService, self).setup()

        payload = self.load_example_listing("G6-IaaS")
        del payload['id']
        with self.app.app_context():
            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.commit()
Beispiel #29
0
    def patch(self, id=None):
        address = self.get_resource_with_ids(Address, id)
        json_data = request.get_json()
        try:
            data = address_patch_schema.load(json_data, partial=True)
        except ValidationError as err:
            raise RequestException("Invalid input data", 400, err.messages)
        try:
            address.update(**data)
        except Exception as err:
            raise RequestException(
                payload={APIConst.INPUT: json_data}) from err
        result = address_schema.dump(Address.get_with_id(address.id))
        response = jsonify({
            APIConst.MESSAGE: 'updated address {}'.format(id),
            APIConst.DATA: result
        })

        return response
Beispiel #30
0
def get_or_create_address(country, region, city, street='', other=''):
    session = db_session()
    session.add(country)
    session.add(region)
    session.add(city)
    address = session.query(Address).filter_by(country_id=country.id, region_id=region.id, city_id=city.id, street=street, other=other).first()
    if not address:
        new_address = Address(country=country, country_id=country.id,
                              region=region, region_id=region.id,
                              city=city, city_id=city.id,
                              street=street, other=other)
        session.add(new_address)
        session.commit()
        session.expunge_all()
        session.close()
        return new_address
    session.expunge_all()
    session.close()
    return address
Beispiel #31
0
    def __init__(self, parent):
        super().__init__(parent)
        self.setupUi(self)

        self.edit_amount.textChanged.connect(self.on_amount_edit)

        self.edit_address.setValidator(AddressValidator())
        self.edit_address.textChanged.connect(self.on_address_edit)
        self.edit_address.textChanged.connect(self.check_state)

        self.edit_description.setStyleSheet('QLineEdit:focus {background-color: #fff79a}')

        self.btn_send_cancel.clicked.connect(self.on_cancel_clicked)
        self.btn_send_send.setDisabled(True)
        self.amount_valid = False
        self.address_valid = False
        self.btn_send_send.clicked.connect(self.on_send_clicked)

        address_list =[]
        for address in Address.select().order_by(Address.address.desc()):
            if address.alias is not None:
                address_list.append("{} ({})".format(address.alias, address.address))
            address_list.append(address.address)
        completer = QCompleter(address_list, self.edit_address)
        completer_delegate = QStyledItemDelegate(completer)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.popup().setItemDelegate(completer_delegate)
        completer.popup().setStyleSheet(
            """
            QAbstractItemView {
                font: 10pt "Roboto Light";
                border: 1px solid #41ADFF;
                border-top: 0px;
                background-color: #FFF79A;
                border-radius: 2px;
            }
            QAbstractItemView::item  {
                margin-top: 3px;
            }           
            """
        )
        self.edit_address.setCompleter(completer)
def add_properties():
  ## 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'))  
def process_order(request):
    print "placing order"

    try:
        phone_number = request.POST.get("phone_number")
        user_name = request.POST.get("userName")
        email = request.POST.get("email")
        app_version = request.POST.get("app_version")
        device_id = request.POST.get("device_id")
        app_id = request.POST.get("app_id")
        bring_change_of = int(request.POST.get("bring_change_of", "0"))
        address_str = request.POST.get("address")
        landmark = request.POST.get("landmark")
        location_show = request.POST.get("location_show")
        location_id = request.POST.get("location_id")
        api_key = request.POST.get("api_key")
        products = request.POST.get("products")
        tomorrow = request.POST.get("tomorrow")
        delivery_time = request.POST.get("delivery_time")
        # print request
        coupon_id = int(request.POST.get("coupon_id", "0"))

        coupon = None

        print "coupon"
        print phone_number
        user = User.objects.get(username=phone_number)
        if user:
            user.email = email
            user.first_name = user_name.title()
            user.save()
            user_profile = user.userprofile
            user_profile.app_version = app_version
            user_profile.app_id = app_id
            user_profile.device_id = device_id
            user_profile.save()
            if user.api_key.key != api_key:
                print "api key is not valid"
                data = simplejson.dumps({"status": "Not Valid Request"})
                return HttpResponse(data, content_type="application/json", status=403)
        else:
            print "User not found"
            data = simplejson.dumps({"status": "Not Valid Request"})
            return HttpResponse(data, content_type="application/json", status=403)

        print "user obj created"
        print coupon_id

        if coupon_id > 0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count += 1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon, user=user)
            print user
            if prev_order:
                if prev_order[0].status != 1:
                    print "coupon invalidation1"
                    coupon = None
            print coupon
        print "check for coupon"
        location = Location.objects.get(pk=location_id)
        address = Address.objects.filter(user=user, address=address_str, landmark=landmark)
        if address:
            address = address[0]
            address.location = location
            address.save()
        else:
            address = Address(
                user=user, address=address_str, landmark=landmark, location_show=location_show, location=location
            )
            address.save()
        print "address done"

        # print products
        products = products.split(",")
        product_ids = map(lambda x: x.split("::")[0], products)
        product_qns = map(lambda x: x.split("::")[1], products)
        print product_ids
        print product_qns
        order = Order(user=user, total_amount=0, address=address, status=3)
        if tomorrow == "1":
            print delivery_time
            if dt.datetime.now().hour > 20:
                order.delivery_time = dt.datetime.strptime(
                    str((dt.datetime.now() + dt.timedelta(days=1)).date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
            else:
                order.delivery_time = dt.datetime.strptime(
                    str(dt.datetime.now().date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
        else:
            order.delivery_time = dt.datetime.now() + dt.timedelta(hours=1)
        if bring_change_of:
            order.change_requested = bring_change_of
        order.save()
        invoice = Invoice(order=order, product_json="")
        invoice.save()
        print "order obj saved"
        total_amount = 0
        index = 0

        ordered_services = {}
        products_json = []
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append(
                {
                    "spid": prd.id,
                    "pid": prd.product.product.id,
                    "name": prd.product.product.name,
                    "price": prd.price,
                    "discount": prd.discount,
                    "qn": product_qns[index],
                    "size_id": prd.product.size.id,
                }
            )
            service = prd.product.product.category.service
            if "offer" in service.name.lower():
                OfferDeviceId(device_id=device_id).save()
                OfferProductOrderMapping(
                    device_id=device_id, order=order, offer_product=prd.offerproductmapping_set.all()[0]
                ).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)] = 0
            total_amount += int(product_qns[index]) * (prd.price - prd.discount)
            ordered_services[str(service.id)] += int(product_qns[index]) * (prd.price - prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order, store=store)
            if cart:
                cart = cart[0]
            else:
                cart = Cart(order=order, store=store)
                cart.save()

            OrderedProduct(product=prd, cart=cart, quantity=product_qns[index]).save()
            index += 1
        products_json = simplejson.dumps(products_json)
        invoice.product_json = products_json
        invoice.save()

        service_amount_ordered = []
        for key in ordered_services:
            service_amount_ordered.append(str(key) + ":" + str(ordered_services[key]))
        service_amount_ordered = ";;".join(service_amount_ordered)
        print total_amount

        final_amount = total_amount

        if coupon:
            if total_amount >= coupon.min_total:
                order.coupon_applied = coupon
                print "found coupon"
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(
                    coupon, user, location_id, int(app_version), final_amount, service_amount_ordered
                )["discount"]
                print "discount" + str(discount)
                final_amount -= discount

        print "passed coupon part"

        delivery_charges = {}
        for key in ordered_services:
            service = Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service, location=location)
            if lsm:
                lsm = lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True, is_active=True, lsm=lsm)
                print "done"
                if stl:
                    stl = stl[0]
                    if key not in delivery_charges:
                        delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": stl.delivery_min_amount}
                    if ordered_services[key] < stl.delivery_min_amount:
                        final_amount += -stl.delivery_charges
                        total_amount += stl.delivery_charges
                        delivery_charges[key]["delivery_charges"] = stl.delivery_charges
                else:
                    delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}
            else:
                delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}

        print "passed delivery part"

        order.total_amount = total_amount
        order.final_amount = final_amount
        order.delivery_charges = simplejson.dumps(delivery_charges)
        order.save()
        OrderActivity(order=order, user=order.user, actions=0, comment=" ").save()

        data = simplejson.dumps({"status": "done"})
        return HttpResponse(data, content_type="application/json", status=201)
    except Exception as process_order_function_error:
        print "process_order: " + str(process_order_function_error)
        data = simplejson.dumps({"status": "Server Error"})
        send_mail(
            "Order placing Error " + str(process_order_function_error),
            str(request) + "\n\n\n" + str(simplejson.dumps(request.POST)),
            "*****@*****.**",
            ["*****@*****.**"],
            fail_silently=False,
        )
        return HttpResponse(data, content_type="application/json", status=500)
    def obj_create(self, bundle, request=None, **kwargs):
        # data={'status':'cant place order'}
        # return HttpResponse(data, content_type='application/json')
        print bundle.data
        phone_number =  bundle.data['phone_number']
        userName =  bundle.data['userName']
        email =  bundle.data['email']
        app_version =  bundle.data['app_version']
        device_id =  bundle.data['device_id']
        app_id =  bundle.data['app_id']
        bring_change_of =  int(bundle.data['bring_change_of'])

        address_str = bundle.data['address']
        landmark = bundle.data['landmark']
        location_show = bundle.data['location_show']
        location_id = bundle.data['location_id']
        coupon_id =""
        try:
            coupon_id = int(bundle.data['coupon_id'])
        except:
            pass

        coupon=None

        print 'coupon'
        print phone_number
        user = User.objects.filter(username=phone_number)
        print user
        print '----'
        if user:
            user=user[0]
            user.email = email
            user.first_name=userName.title()
            user.save()
            print 'user saved'
            userProfile =UserProfile.objects.filter(user=user)
            print 'userprofile'
            print userProfile
            print '----'
            if userProfile:
                userProfile = userProfile[0]
                userProfile.app_version=app_version
                userProfile.app_id=app_id
                userProfile.device_id=device_id
                userProfile.save()
            else:
                UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        else:
            user=User.objects.create_user(phone_number,email,phone_number)
            user.first_name=userName.title()
            user.save()
            UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        print 'user obj created'
        print coupon_id
        if coupon_id>0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count+=1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon,user=user)
            print user
            if prev_order:
                if prev_order[0].status!=1:
                    print 'coupon invalidation1'
                    coupon=None
            print coupon
        print 'check for coupon'
        location = Location.objects.get(pk=location_id)
        address  = Address.objects.filter(user =user ,address=address_str,landmark=landmark)
        if address:
            address=address[0]
        else:
            address  = Address(user =user ,address=address_str,landmark=landmark,location_show=location_show,location=location )
            address.save()
        print 'address done'
        products = bundle.data['products']
        # print products
        products = products.split(',')
        product_ids = map(lambda x:x.split('::')[0],products)
        product_qns = map(lambda x:x.split('::')[1],products)
        print product_ids
        print product_qns
        order = Order(user = user,total_amount=0,address=address,status=3)
        order.delivery_time=dt.datetime.now()+dt.timedelta(hours=1)
        order.save()
        print 'order obj saved'
        total_amount = 0
        index=0

        ordered_services={}
        products_json=[]
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append({'spid':prd.id,'pid':prd.product.product.id,'name':prd.product.product.name,'price':prd.price,'discount':prd.discount,'qn':product_qns[index],'size_id':prd.product.size.id})
            service = prd.product.product.category.service
            if 'offer' in service.name.lower():
                OfferProductOrderMapping(device_id=device_id,order=order,offer_product=prd.offerproductmapping_set.all()[0]).save()
                OfferDeviceId(device_id=device_id).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)]= 0
            total_amount+= int(product_qns[index])*(prd.price- prd.discount)
            ordered_services[str(service.id)]+= int(product_qns[index])*(prd.price- prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order,store=store)
            if cart:
                cart=cart[0]
            else:
                cart = Cart(order=order,store=store)
                cart.save()

            OrderedProduct(product=prd,cart=cart,quantity=product_qns[index]).save()
            index+=1
        service_amount_ordered=[]
        for key in ordered_services:
            service_amount_ordered.append(str(key)+":"+str(ordered_services[key]))
        service_amount_ordered=';;'.join(service_amount_ordered)
        print total_amount

        final_amount=total_amount
        if coupon:
            if total_amount>=coupon.min_total:
                order.coupon_applied=coupon
                print 'found coupon'
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(coupon,user,location_id,int(app_version),final_amount,service_amount_ordered)['discount']
                print "discount" + str(discount)
                final_amount-=discount
        print "passed coupon part"
        delivery_charges = 0
        delivery_charges_to_save_in_order={}
        for key in ordered_services:
            service=Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service,location=location)
            if lsm:
                lsm=lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True,is_active=True,lsm=lsm)
                print 'done'
                if stl:
                    stl=stl[0]
                    # print 'done1'
                    if key not in delivery_charges_to_save_in_order:
                        # print 'done10'
                        delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':stl.delivery_min_amount}
                        # print 'done11'
                    if ordered_services[key]<stl.delivery_min_amount:
                        # print 'done20'
                        final_amount+=-stl.delivery_charges
                        total_amount+=stl.delivery_charges
                        # print 'done21'
                        delivery_charges_to_save_in_order[key]['delivery_charges']=stl.delivery_charges
                        # print 'done22'
                else:
                    delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
            else:
                delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
        print "passed delivery part"
        order.total_amount=total_amount
        order.final_amount=final_amount
        if bring_change_of:
            order.change_requested=bring_change_of
        order.delivery_charges = simplejson.dumps(delivery_charges_to_save_in_order)
        order.save()
        products_json=simplejson.dumps(products_json)
        Invoice(order=order,product_json=products_json).save()
        bundle.obj=order
        OrderActivity(order=order,user=order.user,actions=0,comment=" ").save()
        print bundle
        return bundle