public async Task AddBookstoreHistory([FromBody] LogParameters parameters) { var history = new BookHistory { UserLogin = User.Identity.Name, Action = parameters.UserAction, BookId = parameters.BookId }; await _service.AddBookstoreHistoryAsync(history); }
/// <summary> /// When the user edits the pending checkin message, save it away in the book history database. /// </summary> /// <param name="request"></param> private void HandleCheckinMessage(ApiRequest request) { var message = request.GetPostStringOrNull() ?? ""; BookHistory.SetPendingCheckinMessage(request.CurrentBook, message); request.PostSucceeded(); }
public void Delete(BookHistory bookHistoryRecord) { var existed = _context.BookHistoryRecords.Find(bookHistoryRecord.Id); _context.BookHistoryRecords.Remove(existed); _context.SaveChanges(); }
public void UploadBook() { _progressBox.WriteMessage("Starting..."); _uploadWorker = new BackgroundWorker(); _uploadWorker.DoWork += BackgroundUpload; _uploadWorker.WorkerReportsProgress = true; _uploadWorker.RunWorkerCompleted += (theWorker, completedEvent) => { // Return all controls to normal state. (Do this first, just in case we get some further exception somehow.) // I believe the event is guaranteed to be raised, even if something in the worker thread throws, // so there should be no way to get stuck in the state where the tabs etc. are disabled. SetStateOfNonUploadControls(true); // Don't call UpdateDisplay, it will wipe out the progress messages. if (_progressBox.CancelRequested) { _progressBox.WriteMessageWithColor(Color.Red, LocalizationManager.GetString("PublishTab.Upload.Cancelled", "Upload was cancelled")); } else { if (completedEvent.Error != null) { string errorMessage = GetBasicErrorUploadingMessage(); _progressBox.WriteError(errorMessage, _model.Title); _progressBox.WriteException(completedEvent.Error); } else if ((string)completedEvent.Result == "quiet") { // no more reporting, sufficient message already given. } else if (string.IsNullOrEmpty((string)completedEvent.Result)) { // Something went wrong, possibly already reported. if (!_model.PdfGenerationSucceeded) { ReportPdfGenerationFailed(); } else { ReportTryAgainDuringUpload(); } } else { var url = BloomLibraryUrlPrefix + "/my-books/book/" + _parseId; string congratsMessage = LocalizationManager.GetString("PublishTab.Upload.UploadCompleteNotice", "Congratulations, \"{0}\" is now available on BloomLibrary.org ({1})", "{0} is the book title; {1} is a clickable url which will display the book on the website"); _progressBox.WriteMessageWithColor(Color.Blue, congratsMessage, _model.Title, url); BookHistory.AddEvent(_model.Book, BookHistoryEventType.Uploaded, "Book uploaded to Bloom Library"); } } _uploadWorker = null; }; SetStateOfNonUploadControls(false); // Last thing we do before launching the worker, so we can't get stuck in this state. _uploadWorker.RunWorkerAsync(_model); }
public void ReturnABook(BookHistory borrowedbook) { var bookHistory = _context.BookHistory.FirstOrDefault(x => x.BookHistoryId == borrowedbook.BookHistoryId); bookHistory.DateIn = DateTime.Now; _context.Update(bookHistory); _context.SaveChanges(); }
public async void GetBookHistory() { BookHistory.Clear(); var result = await bookManager.GetBookTransactionHistory(SelectedBook.BookId).ConfigureAwait(false); foreach (var record in result) { BookHistory.Add(record); } }
public static void Borrow(Book book, Reader reader) { BookHistory history = new BookHistory(); history.BorrowedDate = DateTime.Today; history.Book = book; history.Reader = reader; DiContainer.Container.Resolve <BookHistoryRepository>().Save(history); }
public void CreateLend(Book book, User borrower) { BookHistory bookHistory = new BookHistory(); bookHistory.BookId = book.BookId; bookHistory.UserId = borrower.UserId; bookHistory.DateOut = DateTime.Now; _context.Add(bookHistory); _context.SaveChanges(); }
public async Task AddReviewAsync(string bookId) { var history = new BookHistory { BookId = bookId, ReadyBy = _tenantContext.User, ReadDate = DateTime.UtcNow }; await _dbRepo.AddAsync(history); }
public static List <BookHistoryEvent> GetBookEvents(BookInfo bookInfo) { var events = BookHistory.GetHistory(bookInfo); // add in the title, which isn't in the database (this could done in a way that involves less duplication) events.ForEach(e => { e.Title = bookInfo.Title; e.ThumbnailPath = Path.Combine(bookInfo.FolderPath, "thumbnail.png").ToLocalhost(); }); return(events); }
public void Save(BookHistory item) { if (item.Id == 0) { _connectDb.BookHistory.Add(item); } else { _connectDb.Entry(item).State = EntityState.Modified; } _connectDb.SaveChanges(); }
public static bool ReaderReturnBook(int bookId) { BookHistory history = DiContainer.Container.Resolve <BookHistoryRepository>().GetLastRecord(bookId); if (history == null) { return(false); } history.ReturnDate = DateTime.Today; DiContainer.Container.Resolve <BookHistoryRepository>().Save(history); return(true); }
public void Update(BookHistory bookHistoryRecord) { var existed = _context .BookHistoryRecords.Find(bookHistoryRecord.Id); existed.BookId = bookHistoryRecord.BookId; existed.AltitudeCoordinate = bookHistoryRecord.AltitudeCoordinate; existed.LongtiudeCoordinate = bookHistoryRecord.LongtiudeCoordinate; existed.UserId = bookHistoryRecord.UserId; existed.GetBookOn = bookHistoryRecord.GetBookOn; existed.GiveBookOn = bookHistoryRecord.GiveBookOn; _context.SaveChanges(); }
public IActionResult BooksHistory(Guid Id) { var book = _context.Books.First(x => x.Id == Id); var history = _context.Histories.Where(x => x.BookId == Id); var readers = _context.Readers.Where(x => history.Any(y => y.ReaderId == x.Id)); BookHistory bookHistory = new BookHistory() { Book = book, Histories = history.ToList(), Readers = readers.ToList() }; return(View(bookHistory)); }
public IHttpActionResult bookinghistory(string mail) { try { var user = db.User_Master.Where(x => x.email_id == mail).FirstOrDefault(); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (user == null) { return(BadRequest("User Not Found")); } var bh = db.sp_booked_history(user.userid).ToArray(); BookHistory [] histarray = new BookHistory[bh.Length]; for (int i = 0; i < bh.Length; i++) { var seatn = db.sp_seatsbooked(bh[i].transaction_id); var seats = seatn.ToArray(); BookHistory b = new BookHistory(); b.flight_number = bh[i].flight_number; b.transaction_id = bh[i].transaction_id; b.number_of_seats = bh[i].number_of_seats; b.travel_date = bh[i].travel_date; b.arrival_location = bh[i].arrival_location; b.departure_location = bh[i].departure_location; b.departure_time = bh[i].departure_time; b.arrival_time = bh[i].arrival_time; b.booking_date = bh[i].booking_date; b.cancellation_status = bh[i].cancellation_status; b.duration = bh[i].duration; b.amount = bh[i].amount; b.seat_type = bh[i].seat_type; b.seats = seats; histarray[i] = b; } return(Ok(histarray)); } catch (Exception ex) { return(BadRequest(ex.ToString())); } }
/// <summary> /// This is our primary entry point for importing from a spreadsheet. There is also a CLI command, /// but we shouldn't need that one much, now that we have this on our book thumb context menus. /// </summary> public void HandleImportContentFromSpreadsheet(Book.Book book) { if (!_collectionModel.CollectionSettings.HaveEnterpriseFeatures) { Enterprise.ShowRequiresEnterpriseNotice(Form.ActiveForm, "Import to Spreadsheet"); return; } var bookPath = book.GetPathHtmlFile(); try { string inputFilepath; using (var dlg = new DialogAdapters.OpenFileDialogAdapter()) { dlg.Filter = "xlsx|*.xlsx"; dlg.RestoreDirectory = true; dlg.InitialDirectory = GetSpreadsheetFolderFor(book, false); if (DialogResult.Cancel == dlg.ShowDialog()) { return; } inputFilepath = dlg.FileName; var spreadsheetFolder = Path.GetDirectoryName(inputFilepath); SetSpreadsheetFolder(book, spreadsheetFolder); } var importer = new SpreadsheetImporter(_webSocketServer, book, Path.GetDirectoryName(inputFilepath)); importer.ImportWithProgress(inputFilepath); // The importer now does BringBookUpToDate() which accomplishes everything this did, // plus it may have actually changed the folder (and subsequent 'bookPath') // due to a newly imported title. That would cause this call to fail. //XmlHtmlConverter.SaveDOMAsHtml5(book.OurHtmlDom.RawDom, bookPath); book.ReloadFromDisk(null); BookHistory.AddEvent(book, TeamCollection.BookHistoryEventType.ImportSpreadsheet); _bookSelection.InvokeSelectionChanged(false); } catch (Exception ex) { var msg = LocalizationManager.GetString("Spreadsheet:ImportFailed", "Import failed: "); NonFatalProblem.Report(ModalIf.All, PassiveIf.None, msg + ex.Message, exception: ex, showSendReport: false); } }
private void HandleForceUnlock(ApiRequest request) { if (!_tcManager.CheckConnection()) { request.Failed(); return; } try { var bookStatus = _tcManager.CurrentCollection.GetStatus(BookFolderName); var lockedBy = bookStatus.lockedByFirstName; if (string.IsNullOrEmpty(lockedBy)) { lockedBy = bookStatus.lockedBy; } // Could be a problem if there's no current book or it's not in the collection folder. // But in that case, we don't show the UI that leads to this being called. _tcManager.CurrentCollection.ForceUnlock(BookFolderName); BookHistory.AddEvent(_bookSelection.CurrentSelection, BookHistoryEventType.ForcedUnlock, $"Admin force-unlocked while checked out to {lockedBy}."); UpdateUiForBook(); Analytics.Track("TeamCollectionRevertOtherCheckout", new Dictionary <string, string>() { { "CollectionId", _settings?.CollectionId }, { "CollectionName", _settings?.CollectionName }, { "Backend", _tcManager?.CurrentCollection?.GetBackendType() }, { "User", CurrentUser }, { "BookId", _bookSelection?.CurrentSelection?.ID }, { "BookName", _bookSelection?.CurrentSelection?.Title } }); request.PostSucceeded(); } catch (Exception e) { NonFatalProblem.Report(ModalIf.All, PassiveIf.All, "Could not force unlock", null, e, true); request.Failed("could not unlock"); } }
public static IEnumerable <BookHistoryEvent> GetAllEvents(BookCollection collection) { var all = collection.GetBookInfos().Select(bookInfo => { var events = BookHistory.GetHistory(bookInfo); // add in the title, which isn't in the database (this could done in a way that involves less duplication) events.ForEach(e => { e.Title = bookInfo.Title; e.ThumbnailPath = Path.Combine(bookInfo.FolderPath, "thumbnail.png").ToLocalhost(); }); return(events); }); // strip out, if there are no events var booksWithHistory = from b in all where b.Any() select b; return(booksWithHistory.SelectMany(e => e)); }
public void DuplicateBook(Book.Book book) { var newBookDir = book.Storage.Duplicate(); // Get rid of any TC status we copied from the original, so Bloom treats it correctly as a new book. BookStorage.RemoveLocalOnlyFiles(newBookDir); ReloadEditableCollection(); var dupInfo = TheOneEditableCollection.GetBookInfos() .FirstOrDefault(info => info.FolderPath == newBookDir); if (dupInfo != null) { var newBook = GetBookFromBookInfo(dupInfo); SelectBook(newBook); BookHistory.AddEvent(newBook, BookHistoryEventType.Created, $"Duplicated from existing book \"{book.Title}\""); } }
public void HandleForgetChangesInSelectedBook(ApiRequest request) { try { if (!_tcManager.CheckConnection()) { request.Failed(); return; } // Enhance: do we need progress here? var bookName = Path.GetFileName(_bookSelection.CurrentSelection.FolderPath); // Todo before 5.1: forgetting changes might involve undoing a rename. // If so, ForgetChanges will return a list of folders affected (up to 3). // We need to notify the new collection tab to update its book list // and also possibly update the current selection, and in case we undid // things in the book, we should update the preview. var modifiedBookFolders = _tcManager.CurrentCollection.ForgetChangesCheckin(bookName); string updatedBookFolder = null; var finalBookName = bookName; if (modifiedBookFolders.Count > 0) { updatedBookFolder = modifiedBookFolders[0]; finalBookName = Path.GetFileName(updatedBookFolder); } if (finalBookName != bookName) { _bookSelection.CurrentSelection.Storage.RestoreBookName(finalBookName); } // We've restored an old meta.json, things might be different...book titles for one. // This needs to come AFTER RestoreBookName, which fixes the book's FolderPath // so it knows where to load the restored meta.json from. But BEFORE // UpdateLabelOfBookInEditableCollection, which wants to use the restored BookInfo // to get a name (and fix the one in the Model). _bookSelection.CurrentSelection.UpdateBookInfoFromDisk(); // We need to do this as early as possible so that as notifications start to // go to the UI and it starts to request things from our server the answers are // up to date. _bookSelection.CurrentSelection.ReloadFromDisk(updatedBookFolder); if (finalBookName != bookName) { _collectionModel.UpdateLabelOfBookInEditableCollection(_bookSelection.CurrentSelection); } BookHistory.SetPendingCheckinMessage(_bookSelection.CurrentSelection, ""); UpdateUiForBook(reloadFromDisk: false, renamedTo: updatedBookFolder); // We need to do this after updating the rest of the UI, so the button we're // looking for has been adjusted. _tcManager.CurrentCollection.UpdateBookStatus(finalBookName, true); request.PostSucceeded(); } catch (Exception ex) { var msgId = "TeamCollection.ErrorForgettingChanges"; var msgEnglish = "Error forgetting changes for {0}: {1}"; var log = _tcManager?.CurrentCollection?.MessageLog; // Pushing an error into the log will show the Reload Collection button. It's not obvious this // is useful here, since we don't know exactly what went wrong. However, it at least gives the user // the option to try it. if (log != null) { log.WriteMessage(MessageAndMilestoneType.Error, msgId, msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, ex.Message); } Logger.WriteError(String.Format(msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, ex.Message), ex); request.Failed("forget changes failed"); } }
public void Delete(BookHistory item) { _connectDb.BookHistory.Remove(item); _connectDb.SaveChanges(); }
public HttpResponseMessage AddBook([FromBody] BookModel incomingBook) { try { var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value; var user = _context.Users.FirstOrDefault(u => u.Id == int.Parse(userId)); if (user != null) { byte[] ImageData = null; if (incomingBook.photoInBinary != null) { ImageData = PictureHelper.ConvertToImage(incomingBook.photoInBinary); } Book book = new Book { CurrentUserId = user.Id, ContributorId = user.Id, Title = incomingBook.name, Author = incomingBook.author, Price = Convert.ToDecimal(incomingBook.price), Picture = ImageData != null ? new Data.Models.Picture() { ImageData = ImageData, Name = incomingBook.photo } : null, BookTypeId = 1, //incomingBook.type, GenreId = 1, //incomingBook.genre IsUsable = true, CreatedOn = DateTime.UtcNow }; _context.Books.Add(book); _context.SaveChanges(); BookHistory bookHistory = new BookHistory { BookId = book.Id, GetBookOn = DateTime.UtcNow, UserId = user.Id, AltitudeCoordinate = incomingBook.AltitudeCoordinate, LongtiudeCoordinate = incomingBook.LongitudeCoordinate }; _context.BookHistoryRecords.Add(bookHistory); _context.SaveChanges(); return(new HttpResponseMessage(HttpStatusCode.Created)); } else { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } } catch (Exception e) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } }
public async Task AddBookstoreHistoryAsync(BookHistory history) { _context.BookstoreHistory.Add(history); await _context.SaveChangesAsync(); }
public ReaderHistoryDto(BookHistory book) { BorrowedDate = book.BorrowedDate; ReturnDate = book.ReturnDate; BookTitle = book.Book.Title; }
public async Task AddBookstoreHistoryAsync(BookHistory history) { await _repository.AddBookstoreHistoryAsync(history); }
public BookHistoryDto(BookHistory book) { BorrowedDate = book.BorrowedDate; ReturnDate = book.ReturnDate; ReaderName = $"{book.Reader.Name} {book.Reader.Surname}"; }
public void Insert(BookHistory bookHistoryRecord) { _context.BookHistoryRecords.Add(bookHistoryRecord); _context.SaveChanges(); }
public void HandleCheckInCurrentBook(ApiRequest request) { Action <float> reportCheckinProgress = (fraction) => { dynamic messageBundle = new DynamicJson(); messageBundle.fraction = fraction; _socketServer.SendBundle("checkinProgress", "progress", messageBundle); // The status panel is supposed to be showing a progress bar in response to getting the bundle, // but since we're doing the checkin on the UI thread, it doesn't get painted without this. Application.DoEvents(); }; try { // Right before calling this API, the status panel makes a change that // should make the progress bar visible. But this method is running on // the UI thread so without this call it won't appear until later, when // we have Application.DoEvents() as part of reporting progress. We do // quite a bit on large books before the first file is written to the // zip, so one more DoEvents() here lets the bar appear at once. Application.DoEvents(); _bookSelection.CurrentSelection.Save(); if (!_tcManager.CheckConnection()) { request.Failed(); return; } var bookName = Path.GetFileName(_bookSelection.CurrentSelection.FolderPath); if (_tcManager.CurrentCollection.OkToCheckIn(bookName)) { _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, true, false, reportCheckinProgress); reportCheckinProgress(0); // cleans up panel for next time // review: not super happy about this being here in the api. Was stymied by // PutBook not knowing about the actual book object, but maybe that could be passed in. BookHistory.AddEvent(_bookSelection.CurrentSelection, BookHistoryEventType.CheckIn); _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, checkin: true); Analytics.Track("TeamCollectionCheckinBook", new Dictionary <string, string>() { { "CollectionId", _settings?.CollectionId }, { "CollectionName", _settings?.CollectionName }, { "Backend", _tcManager?.CurrentCollection?.GetBackendType() }, { "User", CurrentUser }, { "BookId", _bookSelection?.CurrentSelection.ID }, { "BookName", _bookSelection?.CurrentSelection.Title } }); } else { // We can't check in! The system has broken down...perhaps conflicting checkouts while offline. // Save our version in Lost-and-Found _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, false, true, reportCheckinProgress); reportCheckinProgress(0); // cleans up panel for next time // overwrite it with the current repo version. _tcManager.CurrentCollection.CopyBookFromRepoToLocal(bookName, dialogOnError: true); // Force a full reload of the book from disk and update the UI to match. _bookSelection.SelectBook(_bookServer.GetBookFromBookInfo(_bookSelection.CurrentSelection.BookInfo, true)); var msg = LocalizationManager.GetString("TeamCollection.ConflictingEditOrCheckout", "Someone else has edited this book or checked it out even though you were editing it! Your changes have been saved to Lost and Found"); ErrorReport.NotifyUserOfProblem(msg); Analytics.Track("TeamCollectionConflictingEditOrCheckout", new Dictionary <string, string>() { { "CollectionId", _settings?.CollectionId }, { "CollectionName", _settings?.CollectionName }, { "Backend", _tcManager?.CurrentCollection?.GetBackendType() }, { "User", CurrentUser }, { "BookId", _bookSelection?.CurrentSelection?.ID }, { "BookName", _bookSelection?.CurrentSelection?.Title } }); } UpdateUiForBook(); request.PostSucceeded(); } catch (Exception e) { reportCheckinProgress(0); // cleans up panel progress indicator var msgId = "TeamCollection.ErrorCheckingBookIn"; var msgEnglish = "Error checking in {0}: {1}"; var log = _tcManager?.CurrentCollection?.MessageLog; // Pushing an error into the log will show the Reload Collection button. It's not obvious this // is useful here, since we don't know exactly what went wrong. However, it at least gives the user // the option to try it. if (log != null) { log.WriteMessage(MessageAndMilestoneType.Error, msgId, msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message); } Logger.WriteError(String.Format(msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message), e); NonFatalProblem.ReportSentryOnly(e, $"Something went wrong for {request.LocalPath()} ({_bookSelection?.CurrentSelection?.FolderPath})"); request.Failed("checkin failed"); } }
// Needs to be thread-safe private string GetBookStatusJson(string bookFolderName, Book.Book book) { string whoHasBookLocked = null; DateTime whenLocked = DateTime.MaxValue; bool problem = false; // bookFolderName may be null when no book is selected, e.g., after deleting one. var status = bookFolderName == null ? null :_tcManager.CurrentCollection?.GetStatus(bookFolderName); // At this level, we know this is the path to the .bloom file in the repo // (though if we implement another backend, we'll have to generalize the notion somehow). // For the Javascript, it's just an argument to pass to // CommonMessages.GetPleaseClickHereForHelpMessage(). It's only used if hasInvalidRepoData is non-empty. string clickHereArg = ""; var folderTC = _tcManager.CurrentCollection as FolderTeamCollection; if (folderTC != null && bookFolderName != null) { clickHereArg = UrlPathString.CreateFromUnencodedString(folderTC.GetPathToBookFileInRepo(bookFolderName)) .UrlEncoded; } string hasInvalidRepoData = (status?.hasInvalidRepoData ?? false) ? (folderTC)?.GetCouldNotOpenCorruptZipMessage() : ""; if (bookFolderName == null) { return(JsonConvert.SerializeObject( new { // Keep this in sync with IBookTeamCollectionStatus defined in TeamCollectionApi.tsx who = "", whoFirstName = "", whoSurname = "", when = DateTime.Now.ToShortDateString(), where = "", currentUser = CurrentUser, currentUserName = TeamCollectionManager.CurrentUserFirstName, currentMachine = TeamCollectionManager.CurrentMachine, problem = "", hasInvalidRepoData = false, clickHereArg = "", changedRemotely = false, disconnected = false, newLocalBook = true, checkinMessage = "", isUserAdmin = _tcManager.OkToEditCollectionSettings })); } bool newLocalBook = false; try { whoHasBookLocked = _tcManager.CurrentCollectionEvenIfDisconnected?.WhoHasBookLocked(bookFolderName); // It's debatable whether to use CurrentCollectionEvenIfDisconnected everywhere. For now, I've only changed // it for the two bits of information actually needed by the status panel when disconnected. whenLocked = _tcManager.CurrentCollection?.WhenWasBookLocked(bookFolderName) ?? DateTime.MaxValue; if (whoHasBookLocked == TeamCollection.FakeUserIndicatingNewBook) { // This situation comes about from two different scenarios: // 1) The user is creating a new book and TeamCollection status doesn't matter // 2) The user is trying to check out an existing book and TeamCollectionManager // discovers [through CheckConnection()] that it is suddenly in a disconnected // state. // In both cases, the current selected book is in view. The only way to tell // these two situations apart is that in (1) book.IsSaveable is true // and in (2) it is not. // Or, book may be null because we're just getting a status to show in the list // of all books. In that case, book is null, but it's fairly safe to assume it's a new local book. if (book?.IsSaveable ?? true) { whoHasBookLocked = CurrentUser; newLocalBook = true; } else { whoHasBookLocked = null; } } problem = _tcManager.CurrentCollection?.HasLocalChangesThatMustBeClobbered(bookFolderName) ?? false; } catch (Exception e) when(e is ICSharpCode.SharpZipLib.Zip.ZipException || e is IOException) { hasInvalidRepoData = (_tcManager.CurrentCollection as FolderTeamCollection)?.GetCouldNotOpenCorruptZipMessage(); } // If the request asked for the book by name, we don't have an actual Book object. // However, it happens that those requests don't need the checkinMessage. var checkinMessage = book == null ? "" : BookHistory.GetPendingCheckinMessage(book); return(JsonConvert.SerializeObject( new { // Keep this in sync with IBookTeamCollectionStatus defined in TeamCollectionApi.tsx who = whoHasBookLocked, whoFirstName = _tcManager.CurrentCollection?.WhoHasBookLockedFirstName(bookFolderName), whoSurname = _tcManager.CurrentCollection?.WhoHasBookLockedSurname(bookFolderName), when = whenLocked.ToLocalTime().ToShortDateString(), where = _tcManager.CurrentCollectionEvenIfDisconnected?.WhatComputerHasBookLocked(bookFolderName), currentUser = CurrentUser, currentUserName = TeamCollectionManager.CurrentUserFirstName, currentMachine = TeamCollectionManager.CurrentMachine, problem, hasInvalidRepoData, clickHereArg, changedRemotely = _tcManager.CurrentCollection?.HasBeenChangedRemotely(bookFolderName), disconnected = _tcManager.CurrentCollectionEvenIfDisconnected?.IsDisconnected, newLocalBook, checkinMessage, isUserAdmin = _tcManager.OkToEditCollectionSettings })); }
/// <summary> /// Aproves Book recieved by requester who received the book from previous owner.Could be called by requster /// </summary> /// <param name="bookRecieved"></param> /// <returns>HttpResponseMessage OK/BadRequest</returns> public async Task <HttpResponseMessage> BookRecieved([FromBody] BookReceivedModel bookRecieved) { if (bookRecieved == null) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } try { var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value; var user = _context.Users.FirstOrDefault(u => u.Id == int.Parse(userId)); if (user == null) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } Deal deal = await _context.Deals.Where(d => d.Id == bookRecieved.DealId).Include(d => d.Book).FirstOrDefaultAsync(); deal.DealStatusId = (int?)DealHelper.Status.RECIEVED; deal.ModifiedOn = DateTime.UtcNow; deal.ExpiredOn = DateTime.UtcNow.AddDays(_context.DealStatuses.FirstOrDefault(s => s.Id == (int?)DealHelper.Status.RECIEVED).ExpirationTime); if (deal.Book == null) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } deal.Book.CurrentUserId = user.Id; var bookHistoryPrevous = await _context.BookHistoryRecords .Where(bh => bh.BookId == deal.BookId) .OrderByDescending(bh => bh.GetBookOn) .FirstOrDefaultAsync(); if (bookHistoryPrevous == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } bookHistoryPrevous.GiveBookOn = DateTime.UtcNow; BookHistory bookHistoryNew = new BookHistory { BookId = deal.BookId, UserId = deal.AcceptorId, GetBookOn = DateTime.UtcNow, LongtiudeCoordinate = bookRecieved.LongtiudeCoordinate, AltitudeCoordinate = bookRecieved.AltitudeCoordinate }; _context.BookHistoryRecords.Add(bookHistoryNew); _context.SaveChanges(); return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } }