def setUp(self):
        self.repo = Repository()
        self.brepo = Repository()
        self.crepo = Repository()
        self.Ucontroller = UndoController()
        self.book = Book(21, 'titlu', 'descriere', 'author')
        self.book2 = Book(22, 'titlu2', 'descriere2', 'author')
        self.brepo.add(self.book)
        self.brepo.add(self.book2)
        self.client = Client(23, 'alex')
        self.client2 = Client(24, 'ana')
        self.client3 = Client(29, 'ana')

        self.crepo.add(self.client)
        self.crepo.add(self.client2)
        self.rental = Rental(21236, 21, 24, date(2017, 11, 5),
                             date(2017, 12, 6), date(2017, 12, 5))
        self.rental2 = Rental(21238, 22, 24, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental3 = Rental(21238, 23, 24, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental4 = Rental(21238, 21, 29, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental5 = Rental(21231, 21, 23, date(2017, 11, 5),
                              date(2017, 10, 6), None)

        self.controller = RentalController(self.repo, self.brepo, self.crepo,
                                           self.Ucontroller)
        self.ceva = LateRentalCount(12, 32)
        self.altceva = BookRentalCount(12, 23)
        self.nu = AuthorRentalCount('da', 23)
        self.da = ClientRentalCount(32, 12)
Beispiel #2
0
 def setUp(self):
     self.client = Client(23, 'alex')
     self.client2 = Client(12, 'diana')
     self.book = Book(21, 'titlu', 'descriere', 'author')
     self.book2 = Book(22, 'titlu2', 'descriere2', 'author2')
     self.rental = Rental(21236, 21, 23, date(2017, 11, 5), date(2017, 12, 6), date(2017, 12, 5))
     self.rental2 = Rental(21236, 21, 23, date(2017, 11, 5), date(2017, 12, 6), date(2017, 12, 5))
Beispiel #3
0
    def testRentalRepository(self):
        rentalRepo = Repository()
        book1 = Book(0, "The Q", "Albert", "Heinrich")
        book2 = Book(1, "The D", "Elbert", "Reinsich")
        client1 = Client(0, "Mihai", 1854987548795)
        client2 = Client(1, "Alex", 1987548759658)

        rentalRepo.addElement(Rental(1, book1, 0))
        rentalRepo.addElement(Rental(0, book2, 1))

        # _find(_id) returns the Rental from the repository
        # that has the client Id equal to _id

        self.assertEqual(rentalRepo._find(0).getRentedBook(), book1)
        self.assertEqual(rentalRepo._find(1).getId(), 1)

        self.assertEqual(rentalRepo._find(1).getRentedBook(), book2)
        self.assertEqual(rentalRepo._find(0).getId(), 0)

        # findId() function for Repository class
        self.assertEqual(rentalRepo.findId(12), False)
        self.assertEqual(rentalRepo.findId(0), True)

        # elementFromId()
        self.assertEqual(rentalRepo.elementFromId(0).getRentedBook(), book1)

        rentalRepo.addElement(Rental(1, book2, 2))
Beispiel #4
0
def testRentalRepository():
    rentalRepo = Repository()
    book1 = Book(0, "The Q", "Albert", "Heinrich")
    book2 = Book(1, "The D", "Elbert", "Reinsich")
    client1 = Client(0, "Mihai", 1854987548795)
    client2 = Client(1, "Alex", 1987548759658)

    rentalRepo.addElement(Rental(1, book1, 0))
    rentalRepo.addElement(Rental(0, book2, 1))

    # _find(_id) returns the Rental from the repository
    # that has the client Id equal to _id

    assert rentalRepo._find(0).getRentedBook() == book1 
    assert rentalRepo._find(1).getId() == 1

    assert rentalRepo._find(1).getRentedBook() == book2
    assert rentalRepo._find(0).getId() == 0

    # findId() function for Repository class
    assert rentalRepo.findId(12) == False
    assert rentalRepo.findId(0) == True

    # elementFromId()
    assert rentalRepo.elementFromId(0).getRentedBook() == book1

    rentalRepo.addElement(Rental(1, book2, 2)) 

    print ("Rental repository tests ran successfully!")
    def __loadFromFile(self, type):
        """
        :param sample: Element
        :return: None
        :raises RepositoryException when the file cannot be read for some reason
        """
        try:
            f = open(self.__fileName, "r")
            line = f.readline().strip()
            while line != "":
                attrs = line.split(",")

                if type == Book:
                    book = Book(int(attrs[0]), attrs[1], attrs[2], attrs[3])
                    self.__repo.add(book)
                    line = f.readline().strip()

                if type == Client:
                    client = Client(int(attrs[0]), attrs[1])
                    self.__repo.add(client)
                    line = f.readline().strip()

                if type == Rental:
                    rental = Rental(
                        int(attrs[0]), int(attrs[1]), int(attrs[2]),
                        createDateFromString(self.__reverseDate(attrs[3])),
                        createDateFromString(self.__reverseDate(attrs[4])),
                        createDateFromString(self.__reverseDate(attrs[5])))
                    self.__repo.add(rental)
                    line = f.readline().strip()
        except IOError:
            raise RepositoryException()
        finally:
            f.close()
Beispiel #6
0
    def testRental(self):
        repo = Repository()
        book1 = Book(1, "ala", "mala", "dala")

        rentList = Repository()
        rentList.addElement(Rental(2, book1, 0))

        lis1 = rentList.getElementList()
        self.assertEqual(len(lis1), 1)

        rentList.addElement(Rental(2, book1, 1))
        lis1 = rentList.getElementList()
        self.assertEqual(len(lis1), 2)
        self.assertEqual(lis1[0].getRenterId(), 2)
        self.assertEqual(lis1[0].getRentedBook(), book1)
        self.assertEqual(lis1[0].getId(), 0)
Beispiel #7
0
def testRental():
    repo = Repository()
    book1 = Book(1, "ala", "mala", "dala")
    
    rentList = Repository()
    rentList.addElement(Rental(2, book1, 0))

    lis1 = rentList.getElementList()
    assert len(lis1) == 1

    rentList.addElement(Rental(2, book1, 1))
    lis1 = rentList.getElementList()
    assert len(lis1) == 2
    assert lis1[0].getRenterId() == 2
    assert lis1[0].getRentedBook() == book1
    assert lis1[0].getId() == 0

    print ("Rental tests ran successfully!")
Beispiel #8
0
 def read_rental():
     bookID = UI.readInt("enter book ID: ")
     clientID = UI.readInt("enter client ID: ")
     rentalID = int(str(bookID) + str(clientID) + str(randint(0, 9)))
     rentedDate = UI.readDate()
     dueDate = date(2017, rentedDate.month % 12 + 1, randint(1, 31))
     returnedDate = None
     return Rental(rentalID, bookID, clientID, rentedDate, dueDate,
                   returnedDate)
Beispiel #9
0
 def addRentalUI(self):
     rentalID = int(input("RentalID: "))
     bookID = int(input("BookID: "))
     clientID = int(input("ClientID: "))
     rd = input("Rented date: ")
     rd = datetime.strptime(rd, '%Y-%m-%d')
     dd = input("Due date: ")
     dd = datetime.strptime(dd, '%Y-%m-%d')
     retd = None
     r = Rental(rentalID, bookID, clientID, rd, dd, retd)
     self._controller.createRental(rentalID,bookID,clientID,rd,dd,retd)
Beispiel #10
0
 def validateUpdate(rental):
     errors = []
     if PersistenceValidator.checkExists(Rental, rental.id):
         original = ReadOnlyAccess.getEntityCopy(Rental, rental.id)
     else:
         original = Rental()
         errors.append(
             PersistenceValidator.entityDoesNotExist(
                 "Rental", "id", rental.id))
     return BaseValidator.getValidationMessage(
         RentalValidator.checkUniqueness(errors, rental, original))
Beispiel #11
0
    def createRental(self, rentalId, client, car, start, end, recordUndo=True):
        rental = Rental(rentalId, start, end, client, car)
        self.__validator.validate(rental)
        '''
        Check the car's availability for the given period 
        '''
        if self.isCarAvailable(rental.car, rental.start, rental.end) == False:
            raise CarRentalException("Car is not available during that time!")
        self.__repository.store(rental)

        return rental
 def _loadFile(self):
     f = open(self._fileName, "r")
     line = f.readline().strip()
     while len(line) > 2:
         tok = line.split(";")
         d1 = tok[3].split("-")
         d2 = tok[4].split("-")
         d3 = tok[5].split("-")
         rental = Rental(int(tok[0]), int(tok[1]), int(tok[2]), date(int(d1[0]), int(d1[1]), int(d1[2])),
                         date(int(d2[0]), int(d2[1]), int(d2[2])), date(int(d3[0]), int(d3[1]), int(d3[2])))
         Repository.store(self, rental)
         line = f.readline().strip()
Beispiel #13
0
    def list_rentals(self):
        rentals = []

        for i in self.__borepo.get_all():
            r = Rental(
                i.get_id(),
                self.__dvdrepo.get_all()[self.__dvdrepo.find(
                    i.get_id_dvd())].get_name(), i.get_name_client())
            rentals.append(r)

        rentals = sorted(rentals, key=lambda x: x.dvd_name)
        return rentals
    def testDomainRental(self):
        rental = Rental(Rental.getNextId(), 2, 3, createDateFromString("11.12.2017"),
                        createDateFromString("20.12.2017"), None)
        self.assertTrue(rental.getBookId() == 2)
        self.assertTrue(rental.getClientId() == 3)
        self.assertTrue(rental.getRentedDate() == date(2017, 12, 11))
        self.assertTrue(rental.getDueDate() == date(2017, 12, 20))
        self.assertTrue(rental.getReturnDate() is None)

        rental.setReturnDate(date(2017, 12, 15))
        x = str(rental)
        self.assertTrue(rental.getReturnDate() == date(2017, 12, 15))
Beispiel #15
0
def init_rental():
    startDay = 1
    returnDay = 2
    indexRent = 1
    for index, car in enumerate(carRepo.getAll()):
        rentalRepo.store(
            Rental(indexRent, date(2016, 11, startDay),
                   date(2016, 11, returnDay),
                   clientRepo.getAll()[index], car))
        indexRent += 1
        startDay += 1
        returnDay += 2
Beispiel #16
0
 def _loadFile(self):
     try:
         f = open(self._fileName, "rb")
         res = pickle.load(f)
         while res != "":
             r = Rental(int(res.id), int(res.movie), int(res.client), res.rentedDate, res.dueDate, res.returnedDate)
             Repository.store(self, r)
             res = pickle.load(f)
     except EOFError:
         return []
     except IOError as e:
         raise RepositoryError(str(e))
Beispiel #17
0
 def _addRental(self, userId, bookElement):
     '''
         Adds rental to _repo.
     '''
     if self._repo.findId(userId) == False:
         if self._bookController.getNumberOf(bookElement.getId()) > 0:
             newElement = Rental(userId, bookElement, self._lastId)
             self._repo.addElement(newElement)
             addOperation = AddOperation(self._repo, newElement)
             self._undoController._addOperation(addOperation)
             self._bookController.modifyNumberOf(
                 bookElement.getId(),
                 self._bookController.getNumberOf(bookElement.getId()) - 1)
             self._lastId += 1
             return True
         else:
             raise RentalException("No more books in repository!")
             return False
     elif self._repo.findId(userId) == True:
         element = self._repo.getElementList()
         for i in element:
             if i.getId() == userId and i.getRentedBook() == bookElement:
                 raise RentalException("That client already rented " +
                                       bookElement.getTitle())
                 return False
         if self._bookController.getNumberOf(bookElement.getId()) > 0:
             newElement = Rental(userId, bookElement, self._lastId)
             self._repo.addElement(newElement)
             addOperation = AddOperation(self._repo, addOperation)
             self._undoController._addOperation(addOperation)
             self._lastId += 1
             self._bookController.modifyNumberOf(
                 bookElement.getId(),
                 self._bookController.getNumberOf(bookElement.getId()) - 1)
             return True
     else:
         raise RentalException("Client already has that book!")
Beispiel #18
0
 def cancel(rentalId):
     # Authenticate
     authenticator = Authenticator(request.headers.get(
         HeaderKey.TOKEN)).allowAgent()
     authentification = authenticator.authenticate()
     if FieldKey.ERROR in authentification:
         return ResponseFormatter.getFormattedValidatorResponse(
             authentification)
     # Create Domain Instance
     rental = Rental()
     rental.id = rentalId
     rental.status = RentalStatus.CANCELLED
     # Call Service Layer
     response = RentalService.update(rental)
     return ResponseFormatter.getFormmattedServiceResponse(
         RentalConverter.toResource, response)
Beispiel #19
0
    def _loadFromFile(self):
        try:
            f = open(self._fName, "r")
        except IOError:
            return
        line = f.readline().strip()
        while line != "":
            t = line.split(";")

            car = self._carRepo.find(int(t[1]))
            client = self._clientRepo.find(int(t[2]))

            c = Rental(t[0], datetime.strptime(t[3], "%Y-%m-%d"),
                       datetime.strptime(t[4], "%Y-%m-%d"), client, car)
            Repository.store(self, c)
            line = f.readline().strip()
        f.close()
Beispiel #20
0
    def writeToBinaryFile(self):
        rentals = []
        rental = Rental(1414, 1035, 1078, datetime.date(2019, 10, 23),
                        datetime.date(2019, 10, 30),
                        datetime.date(2019, 10, 27))
        rentals.append(rental)

        clients = []
        names = ["Mike", "Jake", "Maria", "Andrei", "Dan", "Ana", "Diana"]
        for i in range(20):
            clients.append(Client(i * 134 + 51, random.choice(names)))

        movies = []
        titles0 = [
            "Avengers", "A Star Wars Story", "Jurassic World", "Incredibles",
            "Venom", "The Last Jedi", "Deadpool"
        ]
        descriptions = [
            "A man suffering from Alzheimer's embarks on a final road trip with his granddaughter.",
            "A couple find themselves in over their heads when they foster three children.",
            "A young couple's decision to get engaged threatens to break them apart."
        ]
        genres = ["drama", "comedy", "musical", "thriller", "action", "Sci-Fi"]

        for i in range(10):
            title = random.choice(titles0)
            desc = random.choice(descriptions)
            genre = random.choice(genres)
            movies.append(Movie(i * 156 + 46, title, desc, genre))

        f = open("movies.pickle", "wb")
        for m in movies:
            pickle.dump(m, f)
        f.close()

        f = open("clients.pickle", "wb")
        for c in clients:
            pickle.dump(c, f)
        f.close()

        f = open("rentals.pickle", "wb")
        for r in rentals:
            pickle.dump(r, f)
        f.close()
    def createRental(self, rentalId, client, car, start, end, recordUndo=True):
        rental = Rental(rentalId, start, end, client, car)
        '''
        Check the car's availability for the given period 
        '''
        if self.isCarAvailable(rental.car, rental.start, rental.end) == False:
            raise Exception("Car is not available during that time!")

        self.__repository.store(rental)
        '''
        If the operation did not raise an Exception, then we record it for Undo/Redo
        '''
        if recordUndo == True:
            redo = FunctionCall(self.createRental, rentalId, client, car,
                                start, end)
            undo = FunctionCall(self.deleteRental, rentalId)
            cascadeOp = CascadedOperation(Operation(redo, undo))
            self._undoController.recordOperation(cascadeOp)

        return rental
Beispiel #22
0
    def rentBook(self, bookId, clientId, currentDate, dueDate):
        """
        
        :param currentDate:
        :param bookId: int
        :param clientId: int
        :param dueDate: date
        :return: a list of errors if any
        """
        rentedDate = currentDate
        dueDate = createDateFromString(dueDate)
        # returnedDate = createDateFromString(returnedDate)

        if bookId == -1 or clientId == -1 or currentDate is None:
            return "Invalid input"

        if rentedDate is None or dueDate is None:
            return "Invalid date(s)"

        if rentedDate > dueDate:
            return "Inconsistent dates"

        if self.__isBookRented(bookId):
            return "Book already rented"

        try:
            book = self.__bookRepo.getById(bookId)
            client = self.__clientRepo.getById(clientId)
        except Exception as re:
            return str(re)

        rental = Rental(Rental.getNextId(), book.getId(), client.getId(), rentedDate, dueDate, None)
        self.__rentalRepo.add(rental)
        self.__bookRepo.getById(bookId).setRented(True)

        self.__stats.addBookToStats(self.__bookRepo.getById(bookId))

        return ""
Beispiel #23
0
 def toDomain(rentalResource):
     rental = Rental()
     rental.id = rentalResource[
         RentalField.ID] if RentalField.ID in rentalResource else None
     rental.customer = rentalResource[
         RentalField.
         CUSTOMER] if RentalField.CUSTOMER in rentalResource else None
     rental.property = rentalResource[
         RentalField.
         PROPERTY] if RentalField.PROPERTY in rentalResource else None
     rental.agent = rentalResource[
         RentalField.AGENT] if RentalField.AGENT in rentalResource else None
     rental.rent = rentalResource[
         RentalField.RENT] if RentalField.RENT in rentalResource else None
     rental.start = Date.formatDate(
         rentalResource[RentalField.START]
     ) if RentalField.START in rentalResource else None
     rental.end = Date.formatDate(rentalResource[
         RentalField.END]) if RentalField.END in rentalResource else None
     rental.status = rentalResource[
         RentalField.
         STATUS] if RentalField.STATUS in rentalResource else None
     return rental
Beispiel #24
0
from domain.Client import Client
from domain.Rental import Rental
from controller.BookController import BookController
from controller.ClientController import ClientController
from controller.RentalController import RentalController
from controller.UndoController import UndoController
from repository.repository import Repository, FileRepository
from datetime import date
from tkinter import *

Brepo = FileRepository('books.txt', Book.readBookFromLine, Book.writeBookToLine)

Crepo = FileRepository('clients.txt', Client.readClientFromLine, Client.writeClientToLine)

Rrepo = Repository()
Rrepo.add(Rental(16675, 16, 67, date(2017, 11, 10), date(2017, 12, 11)))
Rrepo.add(Rental(12675, 12, 67, date(2017, 11, 1), date(2017, 11, 11)))
Rrepo.add(Rental(13115, 13, 11, date(2017, 11, 21), date(2017, 11, 11)))
Rrepo.add(Rental(13678, 13, 67, date(2017, 11, 7), date(2017, 11, 20)))
Rrepo.add(Rental(12622, 12, 62, date(2017, 11, 18), date(2017, 1, 11)))
Rrepo.add(Rental(14675, 14, 67, date(2017, 11, 5), date(2017, 11, 24)))
Rrepo.add(Rental(14637, 14, 63, date(2017, 11, 10), date(2017, 10, 11)))
Rrepo.add(Rental(14671, 14, 67, date(2017, 11, 9), date(2017, 12, 11)))
Rrepo.add(Rental(16652, 16, 65, date(2017, 11, 4), date(2017, 11, 16)))
Rrepo.add(Rental(15661, 15, 66, date(2017, 11, 12), date(2017, 10, 30)))
Rrepo.add(Rental(12629, 12, 62, date(2017, 11, 13), date(2017, 11, 25)))
Rrepo.add(Rental(15695, 15, 69, date(2017, 11, 19), date(2017, 11, 24)))
Rrepo.add(Rental(16770, 16, 77, date(2017, 11, 2), date(2017, 11, 24)))

Ucontroller = UndoController()
Bcontroller = BookController(Brepo, Ucontroller, Rrepo)
 def setUp(self):
     self.v = RentalValidator()
     self.c = Rental("1", "2", "3", datetime.date(2019, 11, 20),
                     datetime.date(2019, 11, 27),
                     datetime.date(2019, 11, 23))
    def createRental(self, movie, client, rentedDate, dueDate, returnedDate):
        rental = Rental(len(self.getAll()) * 45 + 66 * 84, movie, client, rentedDate, dueDate, returnedDate)
        self.__validator.validate(rental)
        self.__repository.add(rental)

        return rental
 def removeRental(self, rentalID, movieId, clientId, rentalDate, dueDate, returnedDate):
     rental = Rental(rentalID, movieId, clientId, rentalDate, dueDate, returnedDate)
     self.__validator.validate(rental)
     self.__repository.remove(rental)
Beispiel #28
0
 def checkUniqueness(errors, rental, original=Rental()):
     return errors
Beispiel #29
0
    def ValidateFileInput(self, repoType, fileInput):
        if repoType == "Client":
            if len(fileInput) != 4:
                return None
            try:
                clientId = int(fileInput[1])
                clientName = fileInput[2]
                clientCnp = int(fileInput[3])

                while (clientName[0] == " "):
                    clientName = clientName[1:]

                validElement = Client(clientId, clientName, clientCnp)
                self._tempClientRepo.append(
                    validElement)  # necessary for complete validation
                return validElement
            except:
                return None

        if repoType == "Book":
            if len(fileInput) != 5:
                return None
            try:
                bookId = int(fileInput[1])
                bookTitle = fileInput[2]
                bookDescription = fileInput[3]
                bookAuthor = fileInput[4]

                while (bookTitle[0] == " "):
                    bookTitle = bookTitle[1:]

                while (bookDescription[0] == " "):
                    bookDescription = bookDescription[1:]

                while (bookAuthor[0] == " "):
                    bookAuthor = bookAuthor[1:]

                bookAuthor = bookAuthor.replace("\n", "")

                validElement = Book(bookId, bookTitle, bookDescription,
                                    bookAuthor)
                self._tempBookRepo.append(
                    validElement)  # necessary for complete validation

                return validElement
            except:
                return None

        if repoType == "Rental":
            if len(fileInput) != 4:
                return None
            try:
                rentalId = int(fileInput[3])
                rbookId = int(fileInput[2])
                rclientId = int(fileInput[1])
                rbook = None

                valid = False
                for i in self._tempClientRepo:
                    if i.getId() == rclientId:
                        valid = True
                        break

                if not valid:
                    return None

                for i in self._tempBookRepo:
                    if i.getId() == rbookId:
                        rbook = i
                        break

                if rbook == None:
                    return None

                for i in self._tempRentalRepo:
                    if i.getId() == rentalId:
                        return None

                validElement = Rental(rclientId, rbook, rentalId)
                self._tempRentalRepo.append(validElement)

                return validElement

            except:
                return None

        return None