Example #1
0
        /// <summary>
        /// Updates borrow record
        /// </summary>
        /// <param name="url">url to borrow record</param>
        /// <param name="input">input model for borrow record</param>
        /// <returns>the API HTTP response to request</returns>
        private async Task <HttpResponseMessage> UpdateBorrowRecord(string url, BorrowRecordInputModel input)
        {
            var         recordInputJson = JsonConvert.SerializeObject(input);
            HttpContent content         = new StringContent(recordInputJson, Encoding.UTF8, "application/json");

            return(await client.PutAsync(url, content));
        }
Example #2
0
        public async Task SimulateBorrowRecordActions()
        {
            // Use seeded content to aid tests, a single tape and single user from initialized content
            // Seeded user no 2 has no borrow records and seeded tape no 1 is available (e.g. not on loan) so use that content
            // Construct base URL to request borrow relation for selected seeded content
            int tapeNo = 1, userNo = 2;
            var tapeId          = _fixture.tapeIds[tapeNo];
            var userId          = _fixture.userIds[userNo];
            var userLocation    = _fixture.userUrls[userNo];
            var borrowRecordUrl = userLocation + "/tapes/" + tapeId;

            // Create borrow record for user x for tape y (some user and some tape from seeded content intialized)
            // Expect operation to be successful and return status code of 200 (OK)
            // Then get the new record as it should be and ensure that an entry exists for user for tape with no return date
            var createRecordResponse = await client.PostAsync(borrowRecordUrl, null);

            Assert.Equal("", await createRecordResponse.Content.ReadAsStringAsync());
            Assert.Equal(HttpStatusCode.Created, createRecordResponse.StatusCode);
            var newRecord = (await GetUserBorrowRecords(userLocation)).History
                            .ToList()
                            .FirstOrDefault(r => r.TapeId == tapeId && r.UserId == userId && r.ReturnDate == null);

            Assert.NotNull(newRecord);

            // Return the tape we just registered on loan (done with DELETE method)
            // Verify that operation works (e.g. we recieve status code of 204 (No Content)
            // Then get all borrow records again and verify that the return date has been set (e.g. is not null anymore)
            // Then try to return tape again and expect an error (as tape is not on loan for user anymore)
            var returnTapeResponse = await client.DeleteAsync(borrowRecordUrl);

            Assert.Equal(HttpStatusCode.NoContent, returnTapeResponse.StatusCode);
            var review = (await GetUserBorrowRecords(userLocation)).History
                         .ToList()
                         .FirstOrDefault(r => r.TapeId == tapeId && r.UserId == userId);

            Assert.NotNull(review.ReturnDate);
            returnTapeResponse = await client.DeleteAsync(borrowRecordUrl);

            Assert.Equal(HttpStatusCode.NotFound, returnTapeResponse.StatusCode);

            // Update the borrow record (admin functionality only, so full flexibility for input model)
            // Expect operation to work and get a response of 204 (No Content)
            // Re-fetch borrow record and expect returned date to be changed
            var updateModel = new BorrowRecordInputModel()
            {
                BorrowDate = new DateTime(0), ReturnDate = DateTime.Now
            };
            var updateReviewResponse = await UpdateBorrowRecord(borrowRecordUrl, updateModel);

            Assert.Equal(HttpStatusCode.NoContent, updateReviewResponse.StatusCode);
            var updatedReview = (await GetUserBorrowRecords(userLocation)).History
                                .ToList()
                                .FirstOrDefault(r => r.TapeId == tapeId && r.UserId == userId);

            Assert.NotEqual(review.ReturnDate, updatedReview.ReturnDate);
        }
Example #3
0
 public IActionResult UpdateBorrowRecord(int userId, int tapeId, [FromBody] BorrowRecordInputModel BorrowRecord)
 {
     // Check if input model is valid, output all errors if not
     if (!ModelState.IsValid)
     {
         IEnumerable <string> errorList = ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage);
         throw new InputFormatException("User input model improperly formatted.", errorList);
     }
     _tapeService.UpdateBorrowRecord(tapeId, userId, BorrowRecord);
     return(NoContent());
 }
Example #4
0
        /// <summary>
        /// Updates borrow record
        /// </summary>
        /// <param name="TapeId">Id of tape to update record for</param>
        /// <param name="UserId">Id of user to update record for</param>
        /// <param name="BorrowRecord">The input model for borrow record to update to</param>
        public void UpdateBorrowRecord(int TapeId, int UserId, BorrowRecordInputModel BorrowRecord)
        {
            ValidateBorrowRecord(TapeId, UserId);
            var records    = _borrowRecordRepository.GetAllBorrowRecords().Where(record => record.UserId == UserId && record.TapeId == TapeId).ToList();
            var prevRecord = GetCurrentBorrowRecord(records);

            if (prevRecord == null)
            {
                prevRecord = records.OrderByDescending(r => r.ReturnDate).FirstOrDefault();
                if (prevRecord == null)
                {
                    throw new ResourceNotFoundException($"User does not have the specified tape on loan");
                }
            }
            ;
            _borrowRecordRepository.EditBorrowRecord(prevRecord.Id, BorrowRecord);
        }
Example #5
0
 /// <summary>
 /// Creates borrow record from tapes for user
 /// </summary>
 /// <param name="userJSON">json object for user</param>
 /// <param name="tapeService">tape service with tape functionalities</param>
 public static void CreateTapesForUser(dynamic userJSON, ITapeService tapeService)
 {
     // Create all borrows associated with user after user was added
     if (userJSON.tapes != null)
     {
         foreach (var borrowRecord in userJSON.tapes)
         {
             // Generate input model from json for borrow record
             BorrowRecordInputModel record = ConvertJSONToBorrowRecordInputModel(borrowRecord);
             // Check if borrow record input model is valid
             var results = new List <ValidationResult>();
             var context = new ValidationContext(record, null, null);
             if (!Validator.TryValidateObject(record, context, results))
             {
                 IEnumerable <string> errorList = results.Select(x => x.ErrorMessage);
                 throw new InputFormatException("Tapes borrow for user in initialization file improperly formatted.", errorList);
             }
             // Otherwise add to database
             tapeService.CreateBorrowRecord((int)borrowRecord.id, (int)userJSON.id, record);
         }
     }
 }
Example #6
0
        /// <summary>
        /// Creates a new borrow record into database for today
        /// </summary>
        /// <param name="TapeId">Id of tape to loan</param>
        /// <param name="UserId">Id of user borrowing tape</param>
        /// <param name="BorrowRecord">Borrow record input model with dates</param>
        public void CreateBorrowRecord(int TapeId, int UserId, BorrowRecordInputModel BorrowRecord)
        {
            ValidateBorrowRecord(TapeId, UserId);
            var records       = _borrowRecordRepository.GetAllBorrowRecords().Where(record => record.TapeId == TapeId).ToList();
            var currentRecord = GetCurrentBorrowRecord(records);

            if (currentRecord != null)
            {
                throw new InputFormatException("Tape is already on loan");
            }
            if (BorrowRecord == null)
            {
                BorrowRecord = new BorrowRecordInputModel {
                    BorrowDate = DateTime.Now
                };
            }
            var Record = Mapper.Map <BorrowRecordDTO>(BorrowRecord);

            Record.TapeId = TapeId;
            Record.UserId = UserId;
            _borrowRecordRepository.CreateBorrowRecord(Record);
        }
Example #7
0
 /// <summary>
 /// Converts a borrow record to a HttpContent variable to update a borrow record
 /// </summary>
 /// <param name="input">the input to convert</param>
 private HttpContent GetBorrowRecordAsContent(BorrowRecordInputModel input)
 {
     return(new StringContent(JsonConvert.SerializeObject(input), Encoding.UTF8, "application/json"));
 }
Example #8
0
        /// <summary>
        /// Creates a single borrow record in the database
        /// </summary>
        /// <param name="url">url to post the data to</param>
        /// <param name="input">The input model to initialize the borrow record with</param>
        private async Task SeedSingleBorrowRecord(string url, BorrowRecordInputModel input)
        {
            var createResponse = await client.PostAsync(url, null);

            await client.PutAsync(url, GetBorrowRecordAsContent(input));
        }