Skip to content

Country prediction during series creation #547

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

Merged
merged 1 commit into from
Apr 15, 2017

Conversation

Shkarin
Copy link
Contributor

@Shkarin Shkarin commented Mar 14, 2017

Addressed to #517

@mystamps-bot
Copy link

mystamps-bot commented Mar 14, 2017

16 Errors
🚫 robotframework-maven-plugin error in src/test/robotframework/category/creation/logic.robot:
Test case Create category with name in English fails with message:
Element locator ‘id=category’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/country/creation/logic.robot:
Test case Create country with name in English fails with message:
Element locator ‘id=country-selectized’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/logic.robot:
Test case Create series by filling only required fields fails with message:
Element locator ‘id=category’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/logic.robot:
Test case Create series by filling all fields fails with message:
Element locator ‘id=category’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/misc.robot:
Test case Catalog numbers should accept valid values fails with message:
Several failures occurred:

1) Element locator ‘id=add-catalog-numbers-link’ did not match any elements

2) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

3) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

4) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/misc.robot:
Test case Issue year should have options for range from 1840 to the current year fails with message:
Element locator ‘id=specify-issue-date-link’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Create series with non-numeric quantity fails with message:
Element locator ‘id=quantity’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Create series with quantity that is less than 1 fails with message:
Element locator ‘id=quantity’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Create series with quantity that is greater than 50 fails with message:
Element locator ‘id=quantity’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Create series with empty image fails with message:
Element locator ‘id=image’ did not match any elements
🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Catalog numbers should reject invalid values fails with message:
Several failures occurred:

1) Element locator ‘id=add-catalog-numbers-link’ did not match any elements

2) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

3) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

4) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

5) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

6) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

7) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

8) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

9) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Catalog price should reject invalid values fails with message:
Several failures occurred:

1) Element locator ‘id=add-catalog-numbers-link’ did not match any elements

2) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

3) Element locator ‘id=add-catalog-numbers-link’ did not match any elements.

🚫 robotframework-maven-plugin error in src/test/robotframework/series/creation/validation.robot:
Test case Create series with too long comment fails with message:
Element locator ‘id=add-comment-link’ did not match any elements
🚫 maven-failsafe-plugin error in src/test/java/ru/mystamps/web/tests/cases/WhenAdminAddSeries.java:
Test case WhenAdminAddSeries.shouldHaveStandardStructure fails with error:
submit button with value ‘Add’ should exists
🚫 maven-failsafe-plugin error in src/test/java/ru/mystamps/web/tests/cases/WhenUserAddSeries.java:
Test case WhenUserAddSeries.shouldHaveStandardStructure fails with error:
submit button with value ‘Add’ should exists
🚫 danger check: pull request contains merge commits! Please, rebase your branch to get rid of them: git rebase master gh571_prediction_country
2 Messages
📖 robotframework-maven-plugin reported about 13 errors. Please, fix them.
📖 maven-failsafe-plugin reported about 2 errors. Please, fix them. See also: https://github.com/php-coder/mystamps/wiki/integration-tests

Generated by 🚫 Danger

@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 14, 2017 via email

@php-coder
Copy link
Owner

Не очень понятно, что это такое так как под Linux/MacOS этих ошибок нет. Либо это баг в самом checkstyle, либо его надо как-то специальным образом конфигурировать под Windows. Поэтому можешь игнорировать. Как вариант -- заведи задачу, чтобы при возможности я посмотрел или завел баг в апстриме.

Copy link
Owner

@php-coder php-coder left a comment

Choose a reason for hiding this comment

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

Посмотрел более-менее внимательно и оставил комментарии. Кажется, не смог удержаться и все-таки обратил твое внимание на мелкие детали, но они должны быть очень легко устраняемы.

Кстати, у тебя почему-то везде фигурирует задача 571, но такой еще нет, есть 517 :) Если вдруг соберешься ветку переименовывать (не советую, но вдруг ты захочешь), то не пересоздавай запрос, а просто измени в нем ветку.

@@ -11,5 +11,6 @@
<include file="initial-state.xml" relativeToChangelogFile="true" />
<include file="version/0.3.xml" relativeToChangelogFile="true" />
<include file="version/0.4.xml" relativeToChangelogFile="true" />
<include file="initial-test.xml" relativeToChangelogFile="true" />
Copy link
Owner

Choose a reason for hiding this comment

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

Давай уберем миграцию и тестовые данные для начала, чтобы сфокусироваться на коде. А тесты добавим чуть позже, отдельно.

@@ -121,6 +121,7 @@ t_add_more_images_hint = Later you will be able to add additional images
t_not_chosen = Not chosen
t_create_category_hint = You can also <a tabindex="-1" href="{0}">add a new category</a>
t_create_country_hint = You can also <a tabindex="-1" href="{0}">add a new country</a>
t_guess_country = Guess the country
Copy link
Owner

Choose a reason for hiding this comment

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

Замени "the" на "a"

@@ -202,6 +202,10 @@ <h3 th:text="${#strings.capitalize(add_series)}">
<span id="country.errors" class="help-block" th:if="${#fields.hasErrors('country')}" th:each="error : ${#fields.errors('country')}" th:text="${error}"></span>
/*/-->
</div>

<span id="guess_country">
<a tabindex="-1" th:text="#{t_guess_country}" href="javascript:void(0)">Guess the country</a>
Copy link
Owner

Choose a reason for hiding this comment

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

Замени "the" на "a"

@Override
public String guessCountryBy(Integer createdBy) {
Map<String, Object> params = new HashMap<>();
params.put("created_by", createdBy);
Copy link
Owner

Choose a reason for hiding this comment

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

Используй Collections.singletonMap() раз у тебя всего одно значение.

@@ -421,6 +422,13 @@ public String searchSeriesByCatalog(
return "series/search_result";
}

@ResponseBody
Copy link
Owner

Choose a reason for hiding this comment

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

Добавь комментарий со своим авторством.

@@ -202,6 +202,10 @@ <h3 th:text="${#strings.capitalize(add_series)}">
<span id="country.errors" class="help-block" th:if="${#fields.hasErrors('country')}" th:each="error : ${#fields.errors('country')}" th:text="${error}"></span>
/*/-->
</div>

<span id="guess_country">
Copy link
Owner

Choose a reason for hiding this comment

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

Нужно добавить новый переключатель в togglz и скрывать и этот тег и JS-код для него, в случае, если фича выключена.

@@ -421,6 +422,13 @@ public String searchSeriesByCatalog(
return "series/search_result";
}

@ResponseBody
@GetMapping(Url.INFO_COUNTRY_SERIES_PAGE)
Copy link
Owner

Choose a reason for hiding this comment

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

Вынеси метод в отдельный контроллер (SuggestionController).

@@ -223,6 +223,14 @@ public long countUpdatedSince(Date date) {

@Override
@Transactional(readOnly = true)
public String guessCountryBy(Integer createdBy) {
Copy link
Owner

Choose a reason for hiding this comment

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

Нужно добавить защиту на метод. Он должен быть доступен только пользователям с авторити CREATE_SERIES.

SELECT slug \
FROM series LEFT JOIN countries ON countries.id = series.country_id \
GROUP BY country_id \
ORDER BY COUNT(*) DESC LIMIT 1
Copy link
Owner

Choose a reason for hiding this comment

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

Кажется, что этот запрос выбирает что-то отличное от того, чтобы было в ТЗ. Наша задача найти самую популярную страну в коллекции пользователя.

FROM series LEFT JOIN countries ON countries.id = series.country_id \
WHERE series.created_at IN (SELECT MAX(series.created_at) \
FROM series \
WHERE series.created_by = :created_by)
Copy link
Owner

Choose a reason for hiding this comment

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

Надо будет еще раз потом (не в два ночи) посмотреть на этот запрос. Какой-то он чересчур сложный, как мне кажется.

@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 15, 2017 via email

@php-coder php-coder changed the title Gh571 prediction country Try to predict country during series creation Mar 16, 2017
@php-coder php-coder changed the title Try to predict country during series creation Country prediction during series creation Mar 16, 2017
@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 18, 2017 via email

@Shkarin Shkarin force-pushed the gh571_prediction_country branch from 9785734 to 5350d35 Compare March 18, 2017 12:46
@@ -15,7 +15,7 @@
<link rel="stylesheet" href="../../static/styles/main.css" th:href="${MAIN_CSS}" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.3/css/selectize.bootstrap3.min.css" th:href="${SELECTIZE_CSS}" />
</head>
<body onload="initPage()">
<body>
Copy link
Owner

Choose a reason for hiding this comment

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

Hm... did you try <body th:onload="initPage(${urlSuggest})"> ?

Shkarin referenced this pull request Mar 18, 2017
@php-coder
Copy link
Owner

Забыл добавить, что нужно добавить фичу в togglz, чтобы эту ссылку и js-код можно было отключать динамически.

@php-coder
Copy link
Owner

maven-pmd-plugin error in src/main/java/ru/mystamps/web/service/CountryService.java#L26-L39:
This class has too many methods, consider refactoring it

Чтобы подавить подобные предупреждения добавь @SuppressWarnings("PMD.TooManyMethods")

@Shkarin Shkarin force-pushed the gh571_prediction_country branch 3 times, most recently from f1b685a to 5254bb1 Compare March 26, 2017 20:26
*/
@ResponseBody
@GetMapping(Url.INFO_COUNTRY_SERIES_PAGE)
@PreAuthorize(HasAuthority.CREATE_SERIES)
Copy link
Owner

Choose a reason for hiding this comment

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

Эту аннотацию нужно вешать на сервис (на случай, если в другой раз мы вызовим его из другого контроллера). А контроллер нужно защищать немного иначе -- см. src/main/java/ru/mystamps/web/support/spring/security/SecurityConfig.java

@Override
@Transactional(readOnly = true)
public String suggestCountryForUser(Integer userId) {
Validate.isTrue(userId != null, "UserId must be non null");
Copy link
Owner

Choose a reason for hiding this comment

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

Поправь чуток описание: "User id must be non null"

@@ -0,0 +1,12 @@
--
Copy link
Owner

Choose a reason for hiding this comment

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

Почему этот файл еще тут?

@@ -0,0 +1,18 @@
--
Copy link
Owner

Choose a reason for hiding this comment

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

Почему этот файл еще тут?

Copy link
Owner

Choose a reason for hiding this comment

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

Все еще актуально.

@@ -15,7 +15,7 @@
<link rel="stylesheet" href="../../static/styles/main.css" th:href="${MAIN_CSS}" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.3/css/selectize.bootstrap3.min.css" th:href="${SELECTIZE_CSS}" />
</head>
<body onload="initPage()">
<body onload="initPage(${suggestCountryUrl})">
Copy link
Owner

Choose a reason for hiding this comment

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

Думаю, что вот эта строчка -- причина падения тестов. После отрисовки на сервере, на клиент придет код типа такого: <body onload="initPage(/suggestion/country)"> Этот код, разумеется, невалидный, так как строки должны быть в кавычках.

Copy link
Owner

Choose a reason for hiding this comment

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

P.S. В одинарных кавычках.

@@ -81,3 +81,17 @@ country.find_country_link_info_by_slug = \
FROM countries c \
WHERE c.slug = :slug \
ORDER BY CASE WHEN 'ru' = :lang THEN COALESCE(c.name_ru, c.name) ELSE c.name END

country.find_last_country_by_id = \
SELECT slug \
Copy link
Owner

Choose a reason for hiding this comment

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

При использовании алиасов лучше везде потом явно указывать из какой таблицы поля, чтобы а) было сразу понятно при чтении запроса б) этот SQL не стал невалидным, если во второй таблице появится такое же поле.

@@ -31,6 +31,7 @@
@SuppressWarnings("PMD.TooManyMethods")
public interface SeriesService {
Integer add(AddSeriesDto dto, Integer userId, boolean userCanAddComments);

Copy link
Owner

Choose a reason for hiding this comment

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

Не забудь убрать эту пустую строку.

@@ -30,6 +30,7 @@
@SuppressWarnings("PMD.TooManyMethods")
public interface SeriesDao {
Integer add(AddSeriesDbDto series);

Copy link
Owner

Choose a reason for hiding this comment

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

Не забудь убрать пустую строку тут.

@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 27, 2017 via email

@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 27, 2017 via email

@php-coder
Copy link
Owner

и вот еще <body onload="initPage("${suggestCountryUrl})"> как правильно
кавычки поставить чтоб заработало?

Попробуй так: <body onload="initPage('${suggestCountryUrl}')">

@php-coder
Copy link
Owner

Вот с этим не сообразил почему нужно брать из SecurityConfig? я делаю как в
CountryController

Все правильно сделал.

Просто есть две проверки -- 1) по URL-у, которая выполняется в самом начале и тогда выполнение не дойдет даже до контроллера 2) перед вызовом сервисного метода

Нам нужны обе, ты пока реализовал вторую и я предлагаю добавить еще первую (в SecurityConfig).

@Shkarin
Copy link
Contributor Author

Shkarin commented Mar 28, 2017 via email

@php-coder
Copy link
Owner

Потому что нет тестовых данных, запросы возвращают нул и ссылка просто пропадает.

But then why I can see this link at all? It shouldn't be visible in this case. I bet that it doesn't work and request doesn't return null as you said. Try to inspect request in the browser inspector, for example. I know why it doesn't work but I'll let you debug it first :)

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 17, 2017 via email

@php-coder
Copy link
Owner

Да есть, ошибка, $.get возвращает пустую строку, исправлю и добавлю скрытие
ссылки.

Будет любопытно взглянуть.

Зачем добавлять скрытие, если она скрыта по-умолчанию? Насколько понимаю, нужно разобраться почему она раскрывается, когда с сервера не пришла нужная информация.

Только я что-то не так сделал и у меня появились в моей ветку кучу твоих
коммитов, это нормально или нужно октатить?

Я не знаю что ты делал и не знаю в каком состоянии сейчас ветка, так как ты это все не пушил на гитхаб, поэтому ничего не могу тебе подсказать. Скорее всего, да, ты сделал что-то странное.

@php-coder
Copy link
Owner

P.S. Ах, тот коммит преследует нас -- из-за того, что он все еще в твоем мастере, все работает так странно. Необходимо в ветке мастер сделать что-то типа git reset --hard f0db7 а затем git merge upstream/master. Если до этого ты обновлял твою ветку из мастера, то ее снова придется чистить..

@php-coder
Copy link
Owner

P.P.S. Это прекрасный урок для меня больше никогда не менять публичные коммиты. Приношу свои извинения еще раз.

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 17, 2017 via email

@php-coder
Copy link
Owner

Во-первых, зачем второй раз делал git reset? Это конечно ничего не изменило, но выглядит странно.

Во-вторых, похоже, что мой репо у тебя назван как-то иначе. Должен называться upstream, если ты следовал инструкции. Если ты назвал его как-то еще, то нужно подставить другое имя (см. git remote show).

@php-coder
Copy link
Owner

Please, create a new PR from that branch, so we'll be able to continue working on this feature.

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

А удалять коммит твой уже не стоит?

Стоит конечно.

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

Я пока не вижу результат полностью, но выглядит так, что ты делаешь все правильно. Но! Я сейчас понял, что у тебя, вероятно, этот коммит есть в php-coder/master и он снова прилетает к тебе после мерджа :(

Сделай тогда git fetch php-coder чтобы получить обновления. И только потом git reset и git merge, как было выше.

@php-coder
Copy link
Owner

Давай я попробую объяснить. Есть следующие ветки

  1. master в моем репозитории на гитхабе
  2. php-coder/master -- это отражение моего мастера из пункта 1 но находящееся у тебя локально
  3. master в твоем локальном репозитории -- это тоже самое что и мой мастер, но основан он на локальной ветке из пункта 2
  4. далее есть ветка gh571_prediction_country -- она основана на твоем мастере плюс там твои изменения

Теперь что получилось:

  • я добавил плохой коммит в 1)
  • ты его скачал себе в 2)
  • потом при мердже из 2) он также попал и в 3)
  • далее при ребейзе он также попал и в 4)

Для того, чтобы его удалить мы должны:

  • убрать его из 2) -- это должен сделать git fetch
  • убрать его из 3) -- это должны сделать git reset и git merge
  • убрать его из 4) -- это должен будет сделать git rebase

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

Очень странно. А что, например, выводит git log php-coder/master?

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

Попробуй сделать git fetch --force php-coder -- нужно чтобы твой php-coder/master бранч перезатерся изменениями из моего мастера.

Еще меня смущает это сообщение про ambiguous refname... впервые такое вижу.

@php-coder
Copy link
Owner

  1. Пока не забыл, когда отключаешь js в браузере то кнопки становятся не
    кликабельными http://prntscr.com/eygb5g

Это баг. Можешь создать его?

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

Окей, покажи, что выводят команды git tag и git branch -a

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

Теперь мы нашли причину ambiguous refname -- у тебя есть локальная ветка php-coder/master которая затеняет такую же но remote (вот он: http://stackoverflow.com/a/28100234/352708).

Сделай git branch -D php-coder/master и потом снова git fetch --force php-coder Надеюсь, что это оно.

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 19, 2017 via email

@php-coder
Copy link
Owner

  1. Вроде получилось: http://prntscr.com/eygwcj, теперь push делать?

Да: git push -f (это для мастера)

А потом нужно снова почистить gh571_prediction_country:

Выполни команду git rebase -i HEAD~2 (находясь в ветке gh571_prediction_country). Когда откроется редактор, то удали строчку с коммитом 7dca59c (должна остаться строчка только с твоим коммитом).

и сделать ребейз: git rebase master gh571_prediction_country и потом снова git push -f чтобы запушить эту ветку.

@php-coder
Copy link
Owner

  1. Вот еще ошибку обнаружил http://prntscr.com/eygwpc, перевода нет

Это не баг. <input type=file> целиком отрисовывается браузером и эти подписи тоже его. Локализовать его нет никакой возможности :(

@php-coder
Copy link
Owner

Спасибо за терпение! 🥇

(Я спать.)

@Shkarin
Copy link
Contributor Author

Shkarin commented Apr 20, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants