Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Personal deadlines #300

Merged
merged 34 commits into from
Jun 4, 2018
Merged

Personal deadlines #300

merged 34 commits into from
Jun 4, 2018

Conversation

Ostrenkiy
Copy link
Contributor

@Ostrenkiy Ostrenkiy commented May 31, 2018

Задача: #APPS-1880

Коротко для Release Notes, в формате «Сделали/Добавили/Исправили N»:
Добавили пользовательские дедлайны

Описание:
Основные классы:

  • PersonalDeadlineCounter - класс, ответственный за рассчет времени
  • PersonalDeadlineLocalStorageManager - класс, ответственный за хранение StorageRecord объектов
  • PersonalDeadlineNotificationsManager - класс, ответственный за установку нотификаций по дедлайнам
  • StorageRecordsAPI - АПИ класс работы со эндпоинтом api/storage-records
  • PersonalDeadlineManager - класс, ответственный за реализацию всех кейсов использования персональных дедлайнов
  • PersonalDeadlineEditScheduleViewController - контроллер изменения расписания
  • PersonalDeadlineModesSelectionViewController - контроллер выбора режимов изучения

Существует несколько кейсов для использования пользовательских дедлайнов, каждый из которых разрешается методом в PersonalDeadlineManager :

  • Создание дедлайна func countDeadlines(for course: Course, mode: DeadlineMode)
    • Подсчет дедлайна с помощью PersonalDeadlineCounter
    • POST запрос с помощью StorageRecordsAPI
    • Сохранение полученного в ответе дедлайна с помощью PersonalDeadlineLocalStorageManager
    • Установка уведомлений с помощью PersonalDeadlineNotificationsManager
  • Синхронизация дедлайна для курса syncDeadline(for course: Course, userID: Int)
    • GET запрос на StorageRecordsAPI по kind с ID нужного нам курса
    • Обновляем с помощью PersonalDeadlineLocalStorageManager локальную запись для курса
    • Обновляем уведомления с помощью PersonalDeadlineNotificationsManager
  • Удаление дедлайна для курса с помощью func deleteDeadline(for course: Course)
    • Получаем ID объекта StorageRecord для курса с помощью PersonalDeadlineLocalStorageManager
    • DELETE запрос на StorageRecordsAPI с полученным ID записи
    • Удаляем с помощью PersonalDeadlineLocalStorageManager локальную запись для курса
    • Удаляем уведомления с помощью PersonalDeadlineNotificationsManager
  • Изменение дедлайна changeDeadline(for course: Course, newDeadlines: [SectionDeadline])
    • Получаем объект StorageRecord для курса с помощью PersonalDeadlineLocalStorageManager
    • PUT запрос на StorageRecordsAPI с подмененными дедлайнами в полученном объекте
    • Обновляем с помощью PersonalDeadlineLocalStorageManager локальную запись для курса
    • Обновляем уведомления с помощью PersonalDeadlineNotificationsManager

Для установки дедлайнов в PersonalDeadlineNotificationsManager используется фреймворк UserNotifications. Подсчет времени в PersonalDeadlineCounter происходит по полю time_to_complete для каждого урока. Core Data была смигрирована на новую версию для хранения time_to_complete. StorageRecord объекты хранятся в UserDefaults.

@Ostrenkiy Ostrenkiy added the main label May 31, 2018
@Ostrenkiy Ostrenkiy self-assigned this May 31, 2018
@Ostrenkiy Ostrenkiy requested a review from kvld May 31, 2018 07:57
@Ostrenkiy Ostrenkiy changed the title Feature/user deadlines Personal Deadlines May 31, 2018
@Ostrenkiy Ostrenkiy added this to the 1.60 milestone May 31, 2018
@kvld kvld changed the title Personal Deadlines Personal deadlines May 31, 2018
@@ -41,6 +41,13 @@ class Parser: NSObject {
}
}

func timedateStringFromDate(date: Date) -> String {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Где-то я это уже видел 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Где? Оо

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну, у нас есть ещё несколько мест, где мы Date форматируем как-то.

}
fulfill((section.id, sectionTimeToComplete))
}, error: {
//TODO: Add error handling here
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно добавить хотя бы логирование, я считаю.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, упустил эту тудушку вообще

private func countTimeToComplete(section: Section) -> Promise<(Int, TimeInterval)> {
return Promise {
fulfill, _ in
section.loadUnits(success: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если это возможно, стоит избавляться от коллбеков сразу.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Там легаси, которое надо рефакторить, когда будет переделывать старые классы модели типа Course, Section, Lesson

import UIKit
import ActionSheetPicker_3_0

class PersonalDeadlineEditScheduleViewController: UIViewController {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не MVP модуль? Кажется, что здесь совсем легко можно разделить логику.

extension PersonalDeadlineEditScheduleViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
AnalyticsReporter.reportEvent(AnalyticsEvents.PersonalDeadlines.EditSchedule.Time.opened)
ActionSheetDatePicker.show(withTitle: NSLocalizedString("SelectTimeTitle", comment: ""), datePickerMode: UIDatePickerMode.dateAndTime, selectedDate: sectionDeadlinesData[indexPath.row].deadline, minimumDate: Date(), maximumDate: Date().addingTimeInterval(60 * 60 * 24 * 30 * 365), doneBlock: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Возможно, произведения единиц времени стоит выносить в константы, чтобы было понятно, что это за интервал.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок

collectionView.constrainHeight("\(modeButtonSize.height)")
collectionView.invalidateIntrinsicContentSize()
collectionView.layoutIfNeeded()
(collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = modeButtonSize
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ниже дублирование кода. Возможно стоит сделать свой лэйаут или хотя бы в отдельный метод.

import FLKAutoLayout
import SVProgressHUD

class PersonalDeadlinesModeSelectionViewController: UIViewController {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже про MVP вопрос. Правда, здесь ещё меньше логики, которую можно извлечь.

override func setupSubviews() {
self.view.setRoundedCorners(cornerRadius: 8)
yesButton.setRoundedCorners(cornerRadius: 8, borderWidth: 1, borderColor: UIColor(hex: 0x45B0FF))
//TODO: Do not forget to localize text and buttons here
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Уже локализовали.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Потру

@@ -34,6 +34,8 @@ enum StepikLabelColorMode {
return UIColor.white
case .gray:
return UIColor.lightGray
case .blue:
return UIColor(hex: 0x45B0FF)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В трёх местах уже используется. Вынесем?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что вынесем? Цвет? Давай.


protocol StorageData {
init(json: JSON)
var dictValue: [String : Any] {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всегда ж было { get set } в одну строку :)

@Ostrenkiy Ostrenkiy merged commit a858911 into dev Jun 4, 2018
@Ostrenkiy Ostrenkiy mentioned this pull request Jun 4, 2018
@kvld kvld deleted the feature/user-deadlines branch January 29, 2019 11:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants