Esempio n. 1
0
    def delete_vehicle(self, vehicle):
        self.logger.debug("delete_vehicle")

        self.logger.info("deleting vehicle from database")
        Vehicle.delete().where(Vehicle.number == vehicle.number).execute()

        self.logger.info("removing vehicle from model")
        tree_iter = self.get_iter_from_selected_row(vehicle.number)
        self.vehicles_model.remove(tree_iter)
Esempio n. 2
0
def save_a_basic_vehicle():
    vehicle = Vehicle(make='Kia',
                      model='Sorento',
                      body='SUV',
                      flag=0,
                      year=2014,
                      MSRP=24950.0,
                      details='http://www.truecar.com/prices-new/kia/sorento-pricing/2014/58BAB7AA',
                      image='http://img.truecar.com/colorid_images/v1/959520/175x90/f3q')
    vehicle.save()
Esempio n. 3
0
    def on_save_button_clicked(self, button):
        self.logger.debug("on_save_button_clicked")

        vehicle = self.validate_vehicle()

        if vehicle is None:
            dialog = Gtk.MessageDialog(
                    self.window, 0, Gtk.MessageType.ERROR,
                    Gtk.ButtonsType.CANCEL, "Invalid values")

            dialog.run()
            dialog.destroy()
        else:
            self.logger.debug("Trying to find vehicle: %s", vehicle.number)

            query = Vehicle.select().where(Vehicle.number == vehicle.number)
            if query.exists():
                dialog = Gtk.MessageDialog(
                        self.window, 0, Gtk.MessageType.QUESTION,
                        Gtk.ButtonsType.YES_NO,
                        "The vehicle already exists, do you want to update it?"
                        )

                if dialog.run() == Gtk.ResponseType.YES:
                    self.update_vehicle(vehicle)

                dialog.destroy()
            else:
                self.create_vehicle(vehicle)

            self.clean_form()
Esempio n. 4
0
def create_entry():
    try:
        validate(bottle.request.forms)
        item = Vehicle.create(**bottle.request.forms)
        return { "success": True, "data": parse(item) }
    except IntegrityError as error:
        return { "success": False, "error": "Creation rejected." }
Esempio n. 5
0
    def update_vehicle(self, vehicle):
        self.logger.debug("update_vehicle")

        self.logger.info("saving vehicle to database")
        self.logger.debug("vehicle: %s", vehicle)
        Vehicle.update(plate=vehicle.plate, brand=vehicle.brand,
                       model=vehicle.model, hour_price=vehicle.hour_price,
                       km_price=vehicle.km_price
                       ).where(Vehicle.number == vehicle.number).execute()

        self.logger.info("updating vehicle to model")
        tree_iter = self.get_iter_from_selected_row(vehicle.number)
        self.vehicles_model.set(
                tree_iter,
                [self.PLATE_COLUMN, self.BRAND_COLUMN, self.MODEL_COLUMN],
                [vehicle.plate, vehicle.brand, vehicle.model]
                )
def deleteVehicleById(id):
    res = {}
    res["result"] = 1
    res["message"] = ""

    if Vehicle.delete_one({"id": id}).deleted_count == 1:
        res["message"] = "success"
    else:
        res["result"] = 0
        res["message"] = "Fail to delete user!"

    return res
def editVehicle(vehicle):
    res = {}
    res["result"] = 1
    res["message"] = ""

    if Vehicle.update({"id": vehicle["id"]}, {"$set": vehicle}):
        res["message"] = "success"
    else:
        res["result"] = 0
        res["message"] = "Fail to modify user!"

    return res
def addVehicle(vehicle):
    res = {}
    res["result"] = 1
    res["message"] = ""

    if Vehicle.insert_one(vehicle).inserted_id != "":
        res["message"] = "success"
    else:
        res["result"] = 0
        res["message"] = "Fail to add user!"

    return res
def getAllVehicle():
    vehicleList = []
    for item in Vehicle.find():
        vehicle = {
            "id": item["id"],
            "number": item["number"],
            "user_id": item["user_id"],
            "project_id": item["project_id"],
            "data": item["data"],
            "task": item["task"],
            "status": item["status"],
            "accept": item["accept"],
        }
        vehicleList.append(vehicle)
    return vehicleList
def getVehicleById(id):
    item = Vehicle.find_one({"id": id})
    if item:
        vehicle = {
            "id": item["id"],
            "number": item["number"],
            "user_id": item["user_id"],
            "project_id": item["project_id"],
            "data": item["data"],
            "task": item["task"],
            "status": item["status"],
            "accept": item["accept"],
        }
        return vehicle
    else:
        return None
Esempio n. 11
0
def update_entry(auto_id):
    try:
        validate(bottle.request.forms)
    except IntegrityError:
        return { "success": False, "error": "Update rejected." }

    try:
        item = Vehicle.get(Vehicle.id == auto_id)
    except DoesNotExist:
        return { "success": False, "error": "Item not found." }

    for key, value in bottle.request.forms.items():
        setattr(item, key, value)
    photo = bottle.request.files.get('photo')
    if photo:
        item.photo = photo.file.read()
    item.save()
    return { "success": True, "data": parse(item) }
Esempio n. 12
0
    def on_row_activated(self, treeview, path, column):
        self.logger.debug("on_row_activated")

        tree_iter = self.vehicles_model.get_iter(path)
        number = self.vehicles_model.get_value(tree_iter, self.NUMBER_COLUMN)
        vehicle = Vehicle.select().where(Vehicle.number == number).get()

        if column.get_sort_column_id() == self.REMOVE_COLUMN:
            dialog = Gtk.MessageDialog(
                    self.window, 0, Gtk.MessageType.QUESTION,
                    Gtk.ButtonsType.YES_NO,
                    "Are you sure to remove the vehicle?")

            if dialog.run() == Gtk.ResponseType.YES:
                self.delete_vehicle(vehicle)

            dialog.destroy()
        else:
            self.populate_form(vehicle)
Esempio n. 13
0
    def validate_delivery_note(self):
        self.logger.debug("validate_delivery_note")

        delivery_note = None
        try:
            code = self.code_entry.get_text()
            date = self.date_entry.get_text()
            vehicle_number = self.vehicle_number_combo.get_active_text()

            vehicle = Vehicle.select().where(
                    Vehicle.number == vehicle_number
                    ).get()

            delivery_note = DeliveryNote(
                code=code, date=date, company=self.company, vehicle=vehicle,
                invoiced=False
                )

        except Exception as ex:
            self.logger.error("Exception: %: %", ex.errno, ex.strerror)
            self.logger.error("Invalid data")

        return delivery_note
Esempio n. 14
0
 def get(self):
     maintvehicle = self.request.get("vehicle")
     t = jinja_env.get_template("maintneeded.html")
     response = t.render(vehicle=Vehicle.get_by_id(int(maintvehicle)))
     self.write(response)
Esempio n. 15
0
def populate_db():
    v12 = Vehicle(
            number=12, plate="1234ABC", brand="My brand",
            model="My model", hour_price=27.32, km_price=8.99
            )
    v15 = Vehicle(
            number=15, plate="9876ZYX", brand="My brand",
            model="My model", hour_price=34.02, km_price=4.00
            )
    v12.save()
    v15.save()

    c1 = Company(
            code="0001", name="Company name", nif="B12345678",
            address="Rue st.", city="Zaragoza", state="Zaragoza",
            zip_code="50000", phone="123456789", contact_person="Foolano",
            alternative_phone="987654321", fax="246813579",
            email="*****@*****.**", iban="ES12345678901234567890123456789012",
            bank_name="THE Bank", payment_type="CASH", expiration_days=30,
            first_payment_day=5, second_payment_day=15, third_payment_day=25
            )

    c2 = Company(
            code="0002", name="Foo Inc.", nif="B45678123",
            address="Major st", city="Zaragoza", state="Zaragoza",
            zip_code="50002", email="*****@*****.**",
            iban="ES12345678901234567890123456789012", bank_name="Minor Bank",
            payment_type="BANK_TRANSFER", expiration_days=45,
            first_payment_day=8
            )

    c1.save()
    c2.save()

    dn1 = DeliveryNote(
            code="11111111", date=date(2016, 1, 3), company=c1, vehicle=v12,
            invoiced=False
            )
    dn2 = DeliveryNote(
            code="22222222", date=date(2016, 1, 5), company=c1, vehicle=v15,
            invoiced=False
            )
    dn1.save()
    dn2.save()

    dni1 = DeliveryNoteItem(
            delivery_note=dn1, item_type="HOURS", units=12,
            price=v12.hour_price, description="Working hard"
            )
    dni2 = DeliveryNoteItem(
            delivery_note=dn2, item_type="HOURS", units=7,
            price=21.00, description="We are working hard here"
            )
    dni3 = DeliveryNoteItem(
            delivery_note=dn2, item_type="OTHERS", units=1,
            price=327.86, description="Are you working hard?"
            )
    dni1.save()
    dni2.save()
    dni3.save()

    Settings(vat=21.00, invoice_number="0000000001").save()
Esempio n. 16
0
 def get_vehicles(self):
     query = Vehicle.all()
     vehicles = query.run()
     return vehicles
Esempio n. 17
0
 def load_data_from_database(self):
     self.logger.debug("Loading data from db...")
     self.vehicles = Vehicle.select()
     self.logger.debug("%s vehicles loaded", len(self.vehicles))
Esempio n. 18
0
def vehicles(id=None):
    if request.method == 'GET':
        if id is not None:
            vehicle = Vehicle.query.get(id)    
            if not vehicle:
                return jsonify({"fail": "Vehicle not found"}), 404
            return jsonify({
                "success": "Vehicle found",
                "vehicle": vehicle.serialize()
            }), 200
        else:
            vehicles = Vehicle.query.all()
            vehicles = list(map(lambda vehicle: vehicle.serialize(), vehicles))
            return jsonify({
                "total": len(vehicles),
                "results": vehicles
            }), 200

    if request.method == 'POST':
        name = request.json.get('name')
        model = request.json.get('model')
        vehicle_class = request.json.get('vehicle_class')
        crew = request.json.get('crew')
        manufacturer = request.json.get('manufacturer')
        cargo_capacity = request.json.get('cargo_capacity')
        cost_in_credits = request.json.get('cost_in_credits')
        consumables = request.json.get('consumables')
       
        

        vehicle = Vehicle()
        vehicle.name = name
        vehicle.model = model
        vehicle.vehicle_class = vehicle_class
        vehicle.crew = crew
        vehicle.manufacturer = manufacturer
        vehicle.cargo_capacity = cargo_capacity
        vehicle.cost_in_credits = cost_in_credits
        vehicle.consumables = consumables
        
        vehicle.save()
        return jsonify({
            "success": "vehicle created!",
            "vehicle": vehicle.serialize()
        }), 201

    if request.method == 'PUT':
        pass
    if request.method == 'DELETE':
        vehicle = Vehicle.query.get(id)
        if not vehicle: 
            return jsonify({"fail": "vehicle not found"}), 404
        vehicle.delete()
        return jsonify({"success": "vehicle deleted"}), 200
Esempio n. 19
0
def delete_vehicle(vehicleId):
    db.session.query(Vehicle.filter_by(id=vehicleId).delete())
Esempio n. 20
0
 def vehicle(self, agency_tag, route_tag):
     return formatter.JSON(Vehicle.get_or_fetch(agency_tag, route_tag))
Esempio n. 21
0
 def populate_vehicle_names_combo(self):
     for vehicle in Vehicle.select():
         self.vehicle_number_combo.append(
                 str(vehicle.number), str(vehicle.number)
                 )
Esempio n. 22
0
    def get_vehicle_by_unit(self, unit):
        q = Vehicle.all()

        return q.filter('unit =', unit)
Esempio n. 23
0
def retrieve_entry(auto_id):
    data = parse(Vehicle.get(Vehicle.id == auto_id))
    return { "success": True, "data": data }
Esempio n. 24
0
 def get(id):
     return Vehicle.get(id)
Esempio n. 25
0
def create_vehicle(registration, colour):
    vehicle = Vehicle(registration=registration, colour=colour)
    vehicle.save()
    return vehicle
 def process(self, command):
     input_arr = command.split()
     operationCommand = self._read_input(input_arr, 0)
     operation = commands_to_operation_map.get(operationCommand)
     if operation is None:
         raise MalformedCommandError(command + " missing valid operation.")
     if operation == "INIT":
         try:
             size = int(self._read_input(input_arr, 1))
         except ValueError:
             raise MalformedCommandError(
                 "{} is not int. Slot size should be int.".format(
                     input_arr[1]))
         try:
             num_slots = self.parking_lot_service.create_parking_lot_of_size(
                 size)
         except ValueError as e:
             raise MalformedCommandError(
                 "Lot size should be positive integer")
         return "Created parking of {} slots".format(num_slots)
     elif operation == "PARK":
         if self._read_input(input_arr, 2) != "driver_age":
             raise MalformedCommandError("Missing command arguments.")
         number_plate = self._read_input(input_arr, 1)
         try:
             driver_age = int(self._read_input(input_arr, 3))
             if driver_age <= 0:
                 raise MalformedCommandError(
                     "{} is negative. Age should be positive.".format(
                         input_arr[3]))
         except ValueError:
             raise MalformedCommandError(
                 "{} is not int. Drive age should be int.".format(
                     input_arr[3]))
         driver = Driver(driver_age)
         vehicle_to_park = Vehicle(number_plate, driver)
         try:
             parked_slot = self.parking_lot_service.park_vehicle(
                 vehicle_to_park)
             return 'Car with vehicle registration number "{}" has been parked at slot number {}'.format(
                 parked_slot.parked_vehicle.number, parked_slot.number)
         except DuplicateVehicleError as e:
             return "Vehicle with this registration number is already parked."
         except ParkingFullError as e:
             return "Cannot park more vehicles because parking is full."
     elif operation == "VEHICLE_NUM_TO_SLOT_NUM":
         vehicle_number = self._read_input(input_arr, 1)
         slot_num = self.parking_lot_service.get_slot_number_for_vehicle_number(
             vehicle_number)
         if slot_num is None:
             return ""
         return str(slot_num)
     elif operation == "AGE_TO_SLOT_NUMS":
         try:
             age = int(self._read_input(input_arr, 1))
             if age <= 0:
                 raise MalformedCommandError(
                     "{} is negative. Age should be positive.".format(
                         input_arr[1]))
         except ValueError:
             raise MalformedCommandError(
                 "{} is not int. Age should be int.".format(input_arr[1]))
         slot_nums = self.parking_lot_service.get_slot_numbers_for_driver_age(
             age)
         return ",".join([str(item) for item in slot_nums])
     elif operation == "AGE_TO_VEHICLE_NUMS":
         try:
             age = int(self._read_input(input_arr, 1))
             if age <= 0:
                 raise MalformedCommandError(
                     "{} is negative. Age should be positive.".format(
                         input_arr[1]))
         except ValueError:
             raise MalformedCommandError(
                 "{} is not int. Age should be int.".format(input_arr[1]))
         nums = self.parking_lot_service.get_parked_vehicle_numbers_of_driver_age(
             age)
         return ",".join([str(item) for item in nums])
     elif operation == "UNPARK":
         try:
             slot_num = int(self._read_input(input_arr, 1))
             if slot_num <= 0:
                 raise MalformedCommandError(
                     "{} is negative. Slot Number should be positive.".
                     format(input_arr[1]))
             vehicle = self.parking_lot_service.empty_slot(slot_num)
         except ValueError:
             raise MalformedCommandError(
                 "{} is not int. Slot Number should be int.".format(
                     input_arr[1]))
         except SlotNotPresentError:
             return 'Slot number not present.'
         if vehicle is None:
             return "Slot already vacant"
         return 'Slot number {} vacated, the car with vehicle registration number "{}" left the space, the driver of the car was of age {}'.format(
             slot_num, vehicle.number, vehicle.driver.age)
Esempio n. 27
0
def register_customer():
    if request.method == 'POST':
        token = request.headers.get('token')
        if not token:
            return Response(json.dumps(
                {"Message": "Please supply proper credentials"}),
                            status=400,
                            content_type="application/json")
        if not check_auth(token):
            return Response(json.dumps({"Message": "Unauthorized access"}),
                            status=401,
                            content_type="application/json")
        json_request = json.loads(request.data)
        c = Customer()
        try:
            c.first_name = json_request['first_name']
            c.last_name = json_request['last_name']
            c.address = json_request['address']
            c.contact_no = json_request['contact_no']
            c.driving_licence_link = json_request['driving_licence_link']
            c.email = json_request['email']
            c.password = json_request['password']
            vehicles = json_request['vehicles']
        except:
            return Response(json.dumps({"Message": "In-Complete form data"}),
                            status=400,
                            content_type="application/json")
        try:
            if not (int(c.contact_no) > 1000000000
                    and int(c.contact_no) <= 9999999999):
                return Response(json.dumps(
                    {"Message": "Contact no. not valid"}),
                                status=400,
                                content_type="application/json")
        except:
            return Response(json.dumps({"Message": "Contact no. not valid"}),
                            status=400,
                            content_type="application/json")
        for vehicle in vehicles:
            v = Vehicle()
            try:
                v.vehicle_type = vehicle['vehicle_type']
                v.vehicle_number = vehicle['vehicle_number']
                v.vehicle_rc_link = vehicle['vehicle_rc_link']
            except:
                return Response(json.dumps(
                    {"Message": "In-Complete form data"}),
                                status=400,
                                content_type="application/json")
            v.save()
            c.vehicles.append(v)
        try:
            c.save()
        except NotUniqueError:
            for vehicle in c.vehicles:
                v = Vehicle.objects.get(vid=vehicle.vid)
                v.delete()
            return Response(json.dumps(
                {"Message": "Customer with same e-mail already exists"}),
                            status=400,
                            content_type="application/json")
        ewallet_reg_url = "http://0.0.0.0:8000/login?x=1&name=" + str(
            c.cid) + "&password="******"QR_CODE_DATA": c.QR_CODE_DATA}),
                        status=200,
                        content_type="application/json")
Esempio n. 28
0
    def post(self):
        new_vehicle_make = self.request.get("new-vehicle-make")
        new_vehicle_model = self.request.get("new-vehicle-model")
        new_vehicle_odometer = self.request.get("new-vehicle-odometer")
        new_vehicle_vin = self.request.get("new-vehicle-vin")
        new_vehicle_year = self.request.get("new-vehicle-year")
        new_vehicle_service = self.request.get("new-vehicle-service")
        new_vehicle_unit = self.request.get("new-vehicle-unit")

        #new_vehicle_escaped = cgi.escape(new_vehicle, quote=True)
        errors = {}
        existing_unit_num = self.get_vehicle_by_unit(new_vehicle_unit)
        has_error = False

        if not new_vehicle_unit:
            errors['unit_error'] = "Please choose a unit number"
            has_error = True

        elif not existing_unit_num:
            errors['unit_error'] = "A vehicle already has that unit number"
            has_error = True

        elif (new_vehicle_vin and new_vehicle_make and new_vehicle_unit
              and new_vehicle_year and new_vehicle_model):

            vehicle = Vehicle(year=int(new_vehicle_year),
                              make=new_vehicle_make,
                              model=new_vehicle_model,
                              odometer=int(new_vehicle_odometer),
                              vin=new_vehicle_vin,
                              service=new_vehicle_service,
                              unit=int(new_vehicle_unit),
                              maintreq=False)
            vehicle.put()

            self.redirect('/fleet')
        else:
            has_error = True

            if not new_vehicle_vin:
                errors['vin_error'] = "Please enter VIN"

            if not new_vehicle_make:
                errors['make_error'] = "Please enter a vehicle make"

            if not new_vehicle_year:
                errors['year_error'] = "Please enter a year"

            if not new_vehicle_model:
                errors['model_error'] = "Please enter a model"

        if has_error:
            t = jinja_env.get_template("fleet.html")
            response = t.render(vin=new_vehicle_vin,
                                model=new_vehicle_model,
                                make=new_vehicle_make,
                                unit=new_vehicle_unit,
                                year=new_vehicle_year,
                                service=new_vehicle_service,
                                odometer=new_vehicle_odometer,
                                errors=errors)
            self.response.out.write(response)
        else:
            t = jinja_env.get_template("fleet.html")
            content = t.render(vehicles=self.get_vehicles())
            self.redirect('/fleet')
Esempio n. 29
0
def delete_entry(auto_id):
    Vehicle.get(Vehicle.id == auto_id).delete_instance()
    return { "success": True }
Esempio n. 30
0
def query_all():
    data = [parse(v) for v in Vehicle.select()]
    return { "success": True, "data": data }
Esempio n. 31
0
 def get_all(page, page_size, filters):
     return Vehicle.get_all(page, page_size, filters)