Skip to content

Conversation

@johnnyshut
Copy link
Contributor

@johnnyshut johnnyshut commented Nov 25, 2025

Описание

Реализовано добавление свойств CheckUnique и CodeSeries в класс Catalog

Внесенные изменения:

  1. Добавлено свойство checkUnique в класс Catalog:

    • Тип: boolean
    • Значение по умолчанию: true
    • Определяет, нужно ли проверять уникальность кода справочника
  2. Создан enum CodeSeries для типизированного представления серии кодов справочника:

    • WHOLE_CATALOG ("WholeCatalog") - весь справочник
    • WITHIN_SUBORDINATION ("WithinSubordination") - в пределах подчинения
    • WITHIN_OWNER_SUBORDINATION ("WithinOwnerSubordination") - в пределах подчинения владельцу
    • Метод valueByName() возвращает WHOLE_CATALOG по умолчанию, если значение не найдено
  3. Добавлено свойство codeSeries в класс Catalog:

    • Тип: CodeSeries
    • Значение по умолчанию: CodeSeries.WHOLE_CATALOG
    • Для формата EDT: если поле отсутствует, автоматически устанавливается значение WHOLE_CATALOG
  4. Зарегистрирован конвертер для CodeSeries в ExtendXStream:

    • Конвертер автоматически преобразует строковые значения из XML/MDO в enum
  5. Обновлены тестовые JSON-файлы:

    • Добавлены поля checkUnique и codeSeries во все тестовые JSON-файлы с корректными значениями
    • Обновлены файлы для отдельных справочников и конфигураций

Особенности реализации:

  • Для формата Designer (XML): поля CheckUnique и CodeSeries обязательны и корректно парсятся из XML
  • Для формата EDT (MDO): поле CheckUnique обязательно, поле CodeSeries опционально — если отсутствует, используется значение по умолчанию WHOLE_CATALOG
  • Использована существующая инфраструктура рефлексии (TransformationUtils, ExtendXStream) для автоматического маппинга полей без явных изменений в конвертерах

Связанные задачи

Closes #546

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Дополнительно

Все тесты проходят успешно. Реализация соответствует требованиям issue #546 и обеспечивает корректную работу с обоими форматами (Designer и EDT).

Summary by CodeRabbit

  • New Features

    • Configurable catalog uniqueness checking with three scope options for code validation.
    • Import/conversion updated to recognize the new scope option.
  • Tests

    • Added parameterized tests validating the uniqueness-flag behavior.
  • Chores

    • Updated ignore list to exclude bin/ and .vscode/.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 25, 2025

Walkthrough

Adds parsing and model support for Catalog's checkUnique and codeSeries: new fields on Catalog, a new CodeSeries enum, XStream converter registration for CodeSeries, two identical new tests, and .gitignore entries for bin/ and .vscode/.

Changes

Cohort / File(s) Summary
Repository ignores
\.gitignore
Added bin/ and .vscode/ ignore entries.
Catalog model
src/main/java/com/github/_1c_syntax/bsl/mdo/Catalog.java
Added public fields boolean checkUnique (default false) and CodeSeries codeSeries (default WHOLE_CATALOG); added import for CodeSeries.
New enum type
src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java
New public enum CodeSeries implementing EnumWithName with constants WHOLE_CATALOG, WITHIN_SUBORDINATION, WITHIN_OWNER_SUBORDINATION; stores MultiName fullName, static valueByName(String) (case-insensitive, defaults to WHOLE_CATALOG), and KEYS lookup map.
XStream converters
src/main/java/com/github/_1c_syntax/bsl/reader/common/xstream/ExtendXStream.java
Registered enum converter for CodeSeries in setupConverters; added import.
Tests (duplicated)
src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java
Added parameterized test method testCheckUniqueFalse(ArgumentsAccessor) asserting isCheckUnique() is false; the same method appears twice in the diff.

Sequence Diagram(s)

sequenceDiagram
    participant File as XML/EDT File
    participant XStream as XStream Deserializer
    participant Conv as CodeSeries Converter
    participant Catalog as Catalog Model

    File->>XStream: supply <CheckUnique>/<checkUnique> and codeSeries string
    XStream->>Conv: convert codeSeries string to enum
    Conv->>Conv: CodeSeries.valueByName(string) (case-insensitive, default WHOLE_CATALOG)
    Conv-->>XStream: return CodeSeries enum
    XStream->>Catalog: set checkUnique (boolean)
    XStream->>Catalog: set codeSeries (CodeSeries)
    note right of Catalog: Catalog populated with new fields
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review focus:
    • Correct default for checkUnique (false) and its visibility/serialization implications.
    • CodeSeries.valueByName behavior and KEYS lookup correctness.
    • XStream converter registration and compatibility with other enum converters.
    • Duplicate test method in CatalogTest.java (remove one copy).

Poem

🐰 I nibble XML by moonlit light,

Found CheckUnique snug and tight.
CodeSeries sprung in three-shade hue,
Whole, Sub, Owner — hopped right through.
Catalogs hum — a tiny cheer from me! 🍃

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is in Russian and refers to CodeSeries and CheckUnique support in Catalog, which matches the actual changes made in the pull request.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #546: checkUnique field added to Catalog with proper parsing from both Designer (XML) and EDT (MDO) formats, CodeSeries enum created with correct values and valueByName() method, codeSeries field added to Catalog with proper defaults, and XStream converter registered for automatic serialization.
Out of Scope Changes check ✅ Passed Changes are focused on implementing CodeSeries and CheckUnique support in Catalog. The .gitignore modifications (bin/ and .vscode/) are minor housekeeping, and test file updates directly support the new functionality; no unrelated changes detected.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java (1)

53-81: Harden valueByName against null/whitespace input

valueByName will throw NullPointerException if string is null, and will not match values with leading/trailing spaces (e.g. " WholeCatalog "), silently defaulting to WHOLE_CATALOG. For robustness against parser quirks and defensive use, consider null/whitespace handling:

   public static CodeSeries valueByName(String string) {
-    return KEYS.getOrDefault(string.toLowerCase(Locale.ROOT), WHOLE_CATALOG);
+    if (string == null) {
+      return WHOLE_CATALOG;
+    }
+
+    var key = string.trim().toLowerCase(Locale.ROOT);
+    if (key.isEmpty()) {
+      return WHOLE_CATALOG;
+    }
+
+    return KEYS.getOrDefault(key, WHOLE_CATALOG);
   }

This keeps the existing defaulting behavior while avoiding NPEs and tolerating minor formatting issues in source data.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e25dab and 898986a.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/Catalog.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/Catalog.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
🔇 Additional comments (2)
src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java (2)

1-33: Header, package, and Lombok usage look consistent with project style

License header, package declaration, and Lombok annotations (@Getter, @ToString, @Accessors) are coherent and align with the existing patterns in the codebase. No issues here.


38-61: Enum design and naming are clear and match the domain

The enum constants, bilingual names via MultiName, and @ToString(of = "fullName") give a clear, localized representation of code series. This fits the described semantics (scope of code uniqueness) and should integrate cleanly with the existing EnumWithName infrastructure.

@johnnyshut
Copy link
Contributor Author

@coderabbitai generate docstrings

@coderabbitai
Copy link

coderabbitai bot commented Nov 25, 2025

✅ Actions performed

Initiated docstring generation; will generate only if new commits exist.

@coderabbitai
Copy link

coderabbitai bot commented Nov 25, 2025

Note

Docstrings generation - SUCCESS
Generated docstrings for this pull request at #549

coderabbitai bot added a commit that referenced this pull request Nov 25, 2025
Docstrings generation was requested by @johnnyshut.

* #548 (comment)

The following files were modified:

* `src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java`
* `src/main/java/com/github/_1c_syntax/bsl/reader/common/xstream/ExtendXStream.java`
@johnnyshut
Copy link
Contributor Author

@coderabbitai отмени свой pull request

@coderabbitai
Copy link

coderabbitai bot commented Nov 25, 2025

Tip

For best results, initiate chat on the files or code changes.

@johnnyshut, я не могу отменить этот pull request, потому что он был создан вами, а не мной.

PR #548 был создан пользователем johnnyshut (вами) из ветки feature/546 в develop. Я (CodeRabbit) являюсь ботом для проверки кода и не создаю pull request'ы.

Если вы хотите закрыть этот PR, вы можете сделать это самостоятельно:

  • Через GitHub UI: перейдите на страницу PR и нажмите кнопку "Close pull request" внизу страницы
  • Через GitHub CLI: выполните команду gh pr close 548

Если у вас есть другие вопросы или вам нужна помощь с этим PR, дайте мне знать! 😊

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java (1)

159-168: Cover both Designer and EDT flows in testCheckUniqueFalse

Right now testCheckUniqueFalse runs only the EDT variant ("true, ssl_3_1, Catalogs.Заметки, _edt"), while other tests in this class (test, testSSL, testSSLFixture) parameterize over both EDT and Designer with two CSV rows. Given the PR goal to support CheckUnique from both Designer (<CheckUnique>) and EDT (<checkUnique>), it’s worth adding the non‑EDT row here as well to exercise both parsing paths.

For consistency with testSSL, you can do:

  @ParameterizedTest
  @CsvSource({
-   "true, ssl_3_1, Catalogs.Заметки, _edt"
+   "true, ssl_3_1, Catalogs.Заметки, _edt",
+   "false, ssl_3_1, Catalogs.Заметки"
  })
  void testCheckUniqueFalse(ArgumentsAccessor argumentsAccessor) {
    var mdo = MDTestUtils.getMDWithSimpleTest(argumentsAccessor);
    assertThat(mdo).isInstanceOf(Catalog.class);
    var catalog = (Catalog) mdo;
    assertThat(catalog.isCheckUnique()).isFalse();
  }

This will validate that isCheckUnique() is false for both Designer and EDT metadata for Catalogs.Заметки, in line with the issue requirements. Based on learnings, MDTestUtils.getMDWithSimpleTest already supports this CSV shape without further changes.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 898986a and eea7d40.

⛔ Files ignored due to path filters (2)
  • src/test/resources/ext/edt/ssl_3_1 is excluded by !src/test/resources/**
  • src/test/resources/fixtures/ssl_3_1/Catalogs.Заметки_edt.json is excluded by !src/test/resources/**
📒 Files selected for processing (1)
  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-05T10:03:02.229Z
Learnt from: johnnyshut
Repo: 1c-syntax/mdclasses PR: 515
File: src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java:35-37
Timestamp: 2025-09-05T10:03:02.229Z
Learning: The MDTestUtils.getMDWithSimpleTest method already correctly handles optional 4th parameter through ArgumentsAccessor.size() check and argumentsAccessor.getString(3) call with null handling - no modification needed for CSV parameter processing.

Applied to files:

  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java
📚 Learning: 2025-09-05T10:03:02.229Z
Learnt from: johnnyshut
Repo: 1c-syntax/mdclasses PR: 515
File: src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java:35-37
Timestamp: 2025-09-05T10:03:02.229Z
Learning: The MDTestUtils.getMDWithSimpleTest method already correctly handles optional 4th parameter "_edt" through ArgumentsAccessor - it doesn't need modification to process the additional CSV parameter for subdirectory selection.

Applied to files:

  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eea7d40 and 054c62f.

📒 Files selected for processing (1)
  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-05T10:03:02.229Z
Learnt from: johnnyshut
Repo: 1c-syntax/mdclasses PR: 515
File: src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java:35-37
Timestamp: 2025-09-05T10:03:02.229Z
Learning: The MDTestUtils.getMDWithSimpleTest method already correctly handles optional 4th parameter through ArgumentsAccessor.size() check and argumentsAccessor.getString(3) call with null handling - no modification needed for CSV parameter processing.

Applied to files:

  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java
📚 Learning: 2025-09-05T10:03:02.229Z
Learnt from: johnnyshut
Repo: 1c-syntax/mdclasses PR: 515
File: src/test/java/com/github/_1c_syntax/bsl/mdo/AccountingRegisterTest.java:35-37
Timestamp: 2025-09-05T10:03:02.229Z
Learning: The MDTestUtils.getMDWithSimpleTest method already correctly handles optional 4th parameter "_edt" through ArgumentsAccessor - it doesn't need modification to process the additional CSV parameter for subdirectory selection.

Applied to files:

  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)

Добавлены поля для управления проверкой уникальности кода справочника:
- checkUnique: определяет, нужно ли проверять уникальность кода
- codeSeries: определяет область действия уникальности кода

Изменения:
- Добавлены поля checkUnique и codeSeries в класс Catalog с значениями по умолчанию
- Добавлена регистрация CodeSeries в ExtendXStream для сериализации
- Добавлен импорт CodeSeries в Catalog

Значение по умолчанию для checkUnique: false (код должен быть уникальным)
Значение по умолчанию для codeSeries: WHOLE_CATALOG
Обновлены JSON фикстуры для добавления полей checkUnique и codeSeries:
- mdclasses: Catalogs.Справочник1.json, Configuration.json
- mdclasses_3_24: Configuration_edt.json
- ssl_3_1: Catalogs.ВерсииФайлов.json, Catalogs.Заметки.json и их _edt версии

Исправлено значение checkUnique в фикстуре Catalogs.Заметки_edt.json
с true на false (соответствует реальному значению в XML файле)
Добавлен параметризованный тест testCheckUniqueFalse для проверки,
что поле checkUnique установлено в false для справочника "Заметки"
в обоих форматах (Designer и EDT).

Также выполнена очистка кода:
- Удален закомментированный метод checkExtInfo
- Обновлен .gitignore (добавлены bin/ и .vscode/)
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java (1)

24-26: Опционально: обезопасить CodeSeries.valueByName от null

valueByName без проверки вызывает string.toLowerCase(Locale.ROOT), что даст NullPointerException при null. Если входная строка может быть отсутствующей в XML/MDO, логичнее либо:

  • трактовать null как “не задано” и возвращать WHOLE_CATALOG, либо
  • явно задокументировать/аннотировать параметр как @NonNull и гарантировать, что парсер никогда не передаст null.

Можно, например:

public static CodeSeries valueByName(String string) {
  if (string == null) {
    return WHOLE_CATALOG;
  }
  return KEYS.getOrDefault(string.toLowerCase(Locale.ROOT), WHOLE_CATALOG);
}

Also applies to: 53-81

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 054c62f and d8e4aab.

⛔ Files ignored due to path filters (9)
  • src/test/resources/fixtures/mdclasses/Catalogs.Справочник1.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/mdclasses/Catalogs.Справочник1_edt.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/mdclasses/Configuration.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/mdclasses/Configuration_edt.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/mdclasses_3_24/Configuration_edt.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/ssl_3_1/Catalogs.ВерсииФайлов.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/ssl_3_1/Catalogs.ВерсииФайлов_edt.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/ssl_3_1/Catalogs.Заметки.json is excluded by !src/test/resources/**
  • src/test/resources/fixtures/ssl_3_1/Catalogs.Заметки_edt.json is excluded by !src/test/resources/**
📒 Files selected for processing (5)
  • .gitignore (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/Catalog.java (2 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/mdo/support/CodeSeries.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/reader/common/xstream/ExtendXStream.java (2 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .gitignore
  • src/test/java/com/github/_1c_syntax/bsl/mdo/CatalogTest.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
🔇 Additional comments (2)
src/main/java/com/github/_1c_syntax/bsl/reader/common/xstream/ExtendXStream.java (1)

34-34: Регистрация конвертера для CodeSeries согласована с остальными enum’ами

Импорт и registerConverter(new EnumConverter<>(CodeSeries.class)); добавлены в том же стиле, что и для других перечислений, инфраструктура XStream выглядит непротиворечиво.

При пробеге по тестам уже должно покрываться чтение/запись codeSeries, но на всякий случай проверьте, что есть хотя бы один тест, читающий/пишущий это поле из XML/MDO.

Also applies to: 257-278

src/main/java/com/github/_1c_syntax/bsl/mdo/Catalog.java (1)

27-27: Based on my verification, I have confirmed the semantic foundation of this review comment:

1C CheckUnique Semantics (Verified):

  • true = platform performs automatic uniqueness checks
  • false = no automatic uniqueness check

The review comment correctly identifies a semantic issue: if the JavaDoc states that false enables uniqueness checking, that contradicts the established 1C semantics where false means checking is disabled.

However, I cannot directly access the repository to verify:

  • The exact wording of the current JavaDoc
  • The actual default values in the implementation
  • Test expectations
  • The specific PR requirements

Ясно, что семантика CheckUnique в 1C строго определена: true = проверка включена, false = проверка отключена. Если JavaDoc указывает обратное (что false включает проверку), это действительно противоречие, которое может привести к ошибкам в API потребителей.

Необходимо вручную проверить в коде:

  • Текущую формулировку JavaDoc для checkUnique
  • Фактический default value (true или false)
  • Соответствие этого default требованиям из PR-описания
  • Тесты, проверяющие поведение

Уточнить правильную семантику согласно 1С и привести в соответствие JavaDoc, default value и тесты

@theshadowco theshadowco merged commit 4c2e544 into 1c-syntax:develop Nov 28, 2025
12 checks passed
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.

[NEW] Добавление метода для получения свойства CheckUnique в Catalog

2 participants