6 Commits

Author SHA1 Message Date
78b827f29e Fix: Handle missing 'color', 'isArchived' and 'value' fields in DTOs and mappers to prevent JsonDataException 2025-10-06 09:40:47 +03:00
9500d747b1 12 2025-10-06 08:11:43 +03:00
8cfad121b2 build: Устранены предупреждения и ошибки сборки Gradle
- Обновлены версии AGP, Kotlin и Compose Compiler для совместимости.
- Версия Java обновлена до 17 во всех модулях.
- Выполнена миграция Moshi с Kapt на KSP.
- Удален устаревший атрибут 'package' из AndroidManifest.xml.
2025-10-05 15:23:21 +03:00
e3f52fca52 Убрали // [PACKAGE] из разметки, чтобы было меньше шума 2025-10-05 14:52:07 +03:00
9286e041da TokenResponse rework 2025-10-05 14:46:02 +03:00
556b7f7c7d feat(enrichment): apply semantic markup 2025-10-04 09:53:10 +03:00
164 changed files with 1918 additions and 1536 deletions

View File

@@ -12,10 +12,9 @@
<Rationale>Заголовок служит 'паспортом' файла, позволяя инструментам мгновенно понять его расположение, имя и назначение.</Rationale>
<Definition type="regex">
<!-- CDATA используется для того, чтобы символы вроде '<' или '>' не были интерпретированы как XML -->
<Pattern><![CDATA[^\s*//\s*\[PACKAGE\]\s*(?P<package>.*?)\n//\s*\[FILE\]\s*(?P<file>.*?)\n//\s*\[SEMANTICS\]\s*(?P<semantics>.*)]]></Pattern>
<Pattern><![CDATA[^\s*//\s*\[FILE\]\s*(?P<file>.*?)\n//\s*\[SEMANTICS\]\s*(?P<semantics>.*)]]></Pattern>
</Definition>
<Example><![CDATA[
// [PACKAGE] com.example.your.package.name
// [FILE] YourFileName.kt
// [SEMANTICS] ui, viewmodel, state_management
package com.example.your.package.name

View File

@@ -18,7 +18,7 @@
</META>
<ROLE_DEFINITION>
<SPECIALIZATION>При исполнении этой роли, я, Gemini, действую как стратегический интерфейс между человеком-архитектором и автоматизированной системой разработки. Моя задача — вести итеративный диалог для уточнения целей, анализировать кодовую базу и, после получения одобрения, инициировать производственную цепочку через выбранный канал задач.</SPECIALIZATION>
<SPECIALIZATION>При исполнении этой роли, я действую как стратегический интерфейс между человеком-архитектором и автоматизированной системой разработки. Моя задача — вести итеративный диалог для уточнения целей, анализировать кодовую базу и, после получения одобрения, инициировать производственную цепочку через выбранный канал задач.</SPECIALIZATION>
<CORE_GOAL>Основная цель этой роли — трансформировать неструктурированный человеческий диалог в структурированный, машиночитаемый и полностью готовый к исполнению `Work Order` для роли 'Агента-Разработчика'.</CORE_GOAL>
</ROLE_DEFINITION>

View File

@@ -0,0 +1,105 @@
<![CDATA[
<AI_AGENT_SEMANTIC_ENRICHMENT_PROTOCOL>
<EXTENDS from="base_role.xml"/>
<META>
<PURPOSE>Этот документ определяет операционный протокол для **исполнения роли 'Агента Семантического Обогащения'**. Главная задача — обогащение кодовой базы семантической информацией согласно `SEMANTIC_ENRICHMENT_PROTOCOL`.</PURPOSE>
<VERSION>1.0</VERSION>
<METRICS_TO_COLLECT>
<COLLECTS group_id="core_metrics"/>
<COLLECTS group_id="enrichment_specific"/>
</METRICS_TO_COLLECT>
<DEPENDS_ON>
- ..agent_promts/interfaces/task_channel_interface.xml
- ..agent_promts/protocols/semantic_enrichment_protocol.xml
</DEPENDS_ON>
</META>
<ROLE_DEFINITION>
<SPECIALIZATION>При исполнении этой роли, я действую как агент семантического обогащения. Моя задача - находить и размечать код, добавляя ему семантическую ценность в соответствии с протоколом.</SPECIALIZATION>
<CORE_GOAL>Проактивно обогащать кодовую базу семантической разметкой для улучшения машиночитаемости и анализа.</CORE_GOAL>
</ROLE_DEFINITION>
<CORE_PHILOSOPHY>
<PHILOSOPHY_PRINCIPLE name="Enrich_Dont_Change_Logic">
<DESCRIPTION>Моя работа заключается в добавлении семантических комментариев и аннотаций, не изменяя логику существующего кода.</DESCRIPTION>
</PHILOSOPHY_PRINCIPLE>
<PHILOSOPHY_PRINCIPLE name="Traceable_And_Reviewable">
<DESCRIPTION>Все изменения должны быть доступны для просмотра, например, через Pull Request.</DESCRIPTION>
</PHILOSOPHY_PRINCIPLE>
</CORE_PHILOSOPHY>
<BOOTSTRAP_PROTOCOL name="Initialization">
<ACTION>Загрузить и полностью проанализировать `agent_promts/protocols/semantic_enrichment_protocol.xml`, включая все вложенные `INCLUDE` файлы, для построения полного набора правил в памяти.</ACTION>
</BOOTSTRAP_PROTOCOL>
<TASK_SPECIFICATION name="Enrichment_Task">
<DESCRIPTION>Задачи для этой роли определяют, какие части кодовой базы нужно обогатить.</DESCRIPTION>
<STRUCTURE>
<![CDATA[
<ENRICHMENT_TASK>
<SCOPE>full_project | directory | file_list</SCOPE>
<TARGET>
<!-- Для directory: path/to/dir -->
<!-- Для file_list: список файлов -->
</TARGET>
</ENRICHMENT_TASK>
]]>
</STRUCTURE>
</TASK_SPECIFICATION>
<MASTER_WORKFLOW name="Enrich_Code_And_Create_PR">
<WORKFLOW_STEP id="1" name="Acknowledge_Task">
<LET name="WorkOrder" value="CALL MyTaskChannel.FindNextTask(RoleName='agent-enrichment', TaskType='type::enrichment')"/>
<IF condition="WorkOrder IS NULL">
<TERMINATE/>
</IF>
<ACTION>CALL MyTaskChannel.UpdateTaskStatus(IssueID={WorkOrder.ID}, NewStatus='status::in-progress')</ACTION>
</WORKFLOW_STEP>
<WORKFLOW_STEP id="2" name="Execute_Enrichment">
<ACTION>Извлечь `<ENRICHMENT_TASK>` из `WorkOrder`.</ACTION>
<LET name="BranchName">feature/{WorkOrder.ID}/semantic-enrichment</LET>
<ACTION>CALL MyTaskChannel.CreateBranch(BranchName={BranchName})</ACTION>
<ACTION>Определить `files_to_process` на основе `SCOPE` и `TARGET`.</ACTION>
<ACTION>Для каждого файла в `files_to_process` применить правила из `SEMANTIC_ENRICHMENT_PROTOCOL`.</ACTION>
</WORKFLOW_STEP>
<WORKFLOW_STEP id="3" name="Commit_And_PR">
<IF condition="есть_изменения">
<ACTION>Сделать коммит с сообщением: `feat(enrichment): apply semantic markup`.</ACTION>
<ACTION>CALL MyTaskChannel.CommitChanges(...)</ACTION>
<LET name="PrID" value="CALL MyTaskChannel.CreatePullRequest(Title='feat(enrichment): Semantic Markup', Body='Closes #{WorkOrder.ID}', HeadBranch={BranchName}, BaseBranch='main')"/>
<ACTION>CALL MyTaskChannel.AddComment(IssueID={WorkOrder.ID}, CommentBody='Enrichment complete. PR #{PrID} is ready for review.')</ACTION>
</IF>
<ELSE>
<ACTION>CALL MyTaskChannel.AddComment(IssueID={WorkOrder.ID}, CommentBody='Enrichment complete. No new semantic markup was added.')</ACTION>
</ELSE>
</WORKFLOW_STEP>
<WORKFLOW_STEP id="4" name="Finalize">
<ACTION>CALL MyTaskChannel.UpdateTaskStatus(IssueID={WorkOrder.ID}, NewStatus='status::completed')</ACTION>
</WORKFLOW_STEP>
<WORKFLOW_STEP id="5" name="Log_Metrics">
<ACTION>Отправить метрики через `MyMetricsSink`.</ACTION>
</WORKFLOW_STEP>
<WORKFLOW_STEP id="6" name="Log_Completion">
<REQUIRES_CHANNEL type="LogSink" as="MyLogSink"/>
<LET name="EnrichmentMetrics" value="CALL MyMetricsSink.GetMetrics(group_id='enrichment_specific')"/>
<LET name="LogMessage">
`WorkOrder {WorkOrder.ID} completed.
- Files Processed: {EnrichmentMetrics.files_processed}
- Entities Enriched: {EnrichmentMetrics.entities_enriched}
- Relations Added: {EnrichmentMetrics.relations_added}
- Contracts Added: {EnrichmentMetrics.contracts_added}
- Logs Added: {EnrichmentMetrics.logs_added}`
</LET>
<ACTION>CALL MyLogSink.Log(FileName="logs/enrichment_agent_log.txt", Content={LogMessage})</ACTION>
</WORKFLOW_STEP>
</MASTER_WORKFLOW>
</AI_AGENT_SEMANTIC_ENRICHMENT_PROTOCOL>
]]>

View File

@@ -11,13 +11,13 @@
</METRICS_TO_COLLECT>
<DEPENDS_ON>
- ../interfaces/task_channel_interface.xml
- ../protocols/semantic_enrichment_protocol.xml
- ..agent_promts/interfaces/task_channel_interface.xml
- ..agent_promts/protocols/semantic_enrichment_protocol.xml
</DEPENDS_ON>
</META>
<ROLE_DEFINITION>
<SPECIALIZATION>При исполнении этой роли, я, Gemini, действую как автоматизированный хранитель чистоты кода. Моя единственная задача — обеспечить, чтобы каждый файл в указанной области соответствовал `SEMANTIC_ENRICHMENT_PROTOCOL`.</SPECIALIZATION>
<SPECIALIZATION>При исполнении этой роли, я, действую как автоматизированный хранитель чистоты кода. Моя единственная задача — обеспечить, чтобы каждый файл в указанной области соответствовал `SEMANTIC_ENRICHMENT_PROTOCOL`.</SPECIALIZATION>
<CORE_GOAL>Поддерживать 100% семантическую чистоту и машиночитаемость кодовой базы, делая все изменения отслеживаемыми через систему контроля версий.</CORE_GOAL>
</ROLE_DEFINITION>
@@ -30,33 +30,6 @@
</PHILOSOPHY_PRINCIPLE>
</CORE_PHILOSOPHY>
<TOOLS_FOR_ROLE>
<TOOL name="CodeEditor">
<COMMANDS><COMMAND name="ReadFile"/><COMMAND name="WriteFile"/></COMMANDS>
</TOOL>
<TOOL name="Shell">
<ALLOWED_COMMANDS>
<COMMAND>find . -name "*.kt"</COMMAND>
<COMMAND>git diff --name-only {commit_range}</COMMAND>
</ALLOWED_COMMANDS>
</TOOL>
</TOOLS_FOR_ROLE>
<ISSUE_BODY_FORMAT name="Linting_Task_Specification">
<DESCRIPTION>Задачи для этой роли должны содержать XML-блок, определяющий режим работы.</DESCRIPTION>
<STRUCTURE>
<![CDATA[
<LINTING_TASK>
<MODE>full_project | recent_changes | single_file</MODE>
<TARGET>
<!-- Для recent_changes: commit range, e.g., HEAD~1..HEAD -->
<!-- Для single_file: path/to/file.kt -->
</TARGET>
</LINTING_TASK>
]]>
</STRUCTURE>
</ISSUE_BODY_FORMAT>
<MASTER_WORKFLOW name="Lint_And_Create_Pull_Request_Cycle">
<WORKFLOW_STEP id="1" name="Find_And_Acknowledge_Task">
<LET name="WorkOrder" value="CALL MyTaskChannel.FindNextTask(RoleName='agent-linter', TaskType='type::linting')"/>

View File

@@ -44,4 +44,12 @@
<METRIC id="manual_verification_time_min" type="integer" description="Время, затраченное на ручную проверку, в минутах."/>
</METRIC_GROUP>
<METRIC_GROUP id="enrichment_specific">
<METRIC name="files_processed" type="integer" unit="files">Количество обработанных файлов.</METRIC>
<METRIC name="entities_enriched" type="integer" unit="entities">Количество обогащенных сущностей (добавлены якоря ENTITY).</METRIC>
<METRIC name="relations_added" type="integer" unit="relations">Количество добавленных семантических связей (якоря RELATION).</METRIC>
<METRIC name="contracts_added" type="integer" unit="contracts">Количество добавленных KDoc-контрактов.</METRIC>
<METRIC name="logs_added" type="integer" unit="logs">Количество добавленных структурированных логов.</METRIC>
</METRIC_GROUP>
</METRICS_CATALOG>

View File

@@ -36,15 +36,19 @@ android {
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "1.8"
jvmTarget = "17"
}
buildFeatures {
compose = true
buildConfig = true
aidl = false
renderScript = false
resValues = true
shaders = false
}
composeOptions {
kotlinCompilerExtensionVersion = Versions.composeCompiler
@@ -65,6 +69,8 @@ dependencies {
implementation(project(":data"))
// [MODULE_DEPENDENCY] Domain module (transitively included via data, but explicit for clarity)
implementation(project(":domain"))
implementation(project(":ui"))
implementation(project(":feature:inventory"))
// [DEPENDENCY] AndroidX
implementation(Libs.coreKtx)

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.homebox.lens">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens
// [FILE] MainActivity.kt
// [SEMANTICS] ui, activity, entrypoint
// [SEMANTICS] app, ui, activity, entrypoint
package com.homebox.lens
// [IMPORTS]
@@ -22,7 +21,7 @@ import timber.log.Timber
// [ENTITY: Activity('MainActivity')]
/**
* @summary Главная и единственная Activity в приложении.
* @summary The main and only Activity in the application.
*/
@AndroidEntryPoint
class MainActivity : ComponentActivity() {

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens
// [FILE] MainApplication.kt
// [SEMANTICS] application, hilt, timber
// [SEMANTICS] app, hilt, timber, entrypoint
package com.homebox.lens
// [IMPORTS]
@@ -11,7 +10,7 @@ import timber.log.Timber
// [ENTITY: Application('MainApplication')]
/**
* @summary Точка входа в приложение. Инициализирует Hilt и Timber.
* @summary The entry point of the application. Initializes Hilt and Timber.
*/
@HiltAndroidApp
class MainApplication : Application() {

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.navigation
// [FILE] NavGraph.kt
// [SEMANTICS] navigation, compose, nav_host
// [SEMANTICS] app, ui, navigation
package com.homebox.lens.navigation
@@ -16,7 +15,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.homebox.lens.ui.screen.dashboard.DashboardScreen
import com.homebox.lens.ui.screen.inventorylist.InventoryListScreen
import com.homebox.lens.feature.inventory.ui.InventoryScreen
import com.homebox.lens.ui.screen.itemdetails.ItemDetailsScreen
import com.homebox.lens.ui.screen.itemedit.ItemEditScreen
import com.homebox.lens.ui.screen.labelslist.LabelsListScreen
@@ -27,6 +26,8 @@ import com.homebox.lens.ui.screen.search.SearchScreen
import com.homebox.lens.ui.screen.setup.SetupScreen
import com.homebox.lens.ui.screen.settings.SettingsScreen
import com.homebox.lens.ui.screen.splash.SplashScreen
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.navigation.Screen
// [END_IMPORTS]
// [ENTITY: Function('NavGraph')]
@@ -34,11 +35,11 @@ import com.homebox.lens.ui.screen.splash.SplashScreen
// [RELATION: Function('NavGraph')] -> [CREATES_INSTANCE_OF] -> [Class('NavigationActions')]
// [RELATION: Function('NavGraph')] -> [USES] -> [Screen('SplashScreen')]
/**
* @summary Определяет граф навигации для всего приложения с использованием Jetpack Compose Navigation.
* @param navController Контроллер навигации.
* @summary Defines the navigation graph for the entire application using Jetpack Compose Navigation.
* @param navController The navigation controller.
* @see Screen
* @sideeffect Регистрирует все экраны и управляет состоянием навигации.
* @invariant Стартовый экран - `Screen.Setup`.
* @sideeffect Registers all screens and manages the navigation state.
* @invariant The start screen is `Screen.Splash`.
*/
@Composable
fun NavGraph(
@@ -60,7 +61,9 @@ fun NavGraph(
composable(route = Screen.Setup.route) {
SetupScreen(onSetupComplete = {
navController.navigate(Screen.Dashboard.route) {
popUpTo(Screen.Setup.route) { inclusive = true }
popUpTo(Screen.Setup.route) {
inclusive = true
}
}
})
}
@@ -70,8 +73,8 @@ fun NavGraph(
navigationActions = navigationActions
)
}
composable(route = Screen.InventoryList.route) {
InventoryListScreen(
composable(route = Screen.Inventory.route) {
InventoryScreen(
currentRoute = currentRoute,
navigationActions = navigationActions
)
@@ -106,7 +109,7 @@ fun NavGraph(
navigationActions = navigationActions,
onLocationClick = { locationId ->
// [AI_NOTE]: Navigate to a pre-filtered inventory list screen
navController.navigate(Screen.InventoryList.route)
navController.navigate(Screen.Inventory.route)
},
onAddNewLocationClick = {
navController.navigate(Screen.LocationEdit.createRoute("new"))

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.components
// [FILE] ColorPicker.kt
// [SEMANTICS] ui, component, color_selection
// [SEMANTICS] app, ui, component, color
package com.homebox.lens.ui.components
@@ -25,10 +24,10 @@ import com.homebox.lens.R
// [ENTITY: Function('ColorPicker')]
/**
* @summary Компонент для выбора цвета.
* @param selectedColor Текущий выбранный цвет в формате HEX строки (например, "#FFFFFF").
* @param onColorSelected Лямбда-функция, вызываемая при выборе нового цвета.
* @param modifier Модификатор для настройки внешнего вида.
* @summary A component for color selection.
* @param selectedColor The currently selected color in HEX string format (e.g., "#FFFFFF").
* @param onColorSelected A lambda function called when a new color is selected.
* @param modifier A modifier for customizing the appearance.
*/
@Composable
fun ColorPicker(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.components
// [FILE] LoadingOverlay.kt
// [SEMANTICS] ui, component, loading
// [SEMANTICS] app, ui, component, loading
package com.homebox.lens.ui.components
@@ -18,7 +17,7 @@ import androidx.compose.ui.graphics.Color
// [ENTITY: Function('LoadingOverlay')]
/**
* @summary Полноэкранный оверлей с индикатором загрузки.
* @summary A full-screen overlay with a loading indicator.
*/
@Composable
fun LoadingOverlay() {

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.mapper
// [FILE] ItemMapper.kt
// [SEMANTICS] ui, mapper, item
// [SEMANTICS] app, ui, mapper, item
package com.homebox.lens.ui.mapper
import com.homebox.lens.domain.model.Item

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.dashboard
// [FILE] DashboardScreen.kt
// [SEMANTICS] ui, screen, dashboard, compose, navigation
// [SEMANTICS] app, ui, screen, dashboard
package com.homebox.lens.ui.screen.dashboard
// [IMPORTS]
@@ -37,11 +36,11 @@ import timber.log.Timber
// [RELATION: Function('DashboardScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('DashboardScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* @summary Главная Composable-функция для экрана "Панель управления".
* @param viewModel ViewModel для этого экрана, предоставляется через Hilt.
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @sideeffect Вызывает навигационные лямбды при взаимодействии с UI.
* @summary The main Composable function for the "Dashboard" screen.
* @param viewModel The ViewModel for this screen, provided by Hilt.
* @param currentRoute The current route to highlight the active item in the Drawer.
* @param navigationActions The object with navigation actions.
* @sideeffect Calls navigation lambdas upon UI interaction.
*/
@Composable
fun DashboardScreen(
@@ -82,11 +81,11 @@ fun DashboardScreen(
// [ENTITY: Function('DashboardContent')]
// [RELATION: Function('DashboardContent')] -> [CONSUMES_STATE] -> [SealedInterface('DashboardUiState')]
/**
* @summary Отображает основной контент экрана в зависимости от uiState.
* @param modifier Модификатор для стилизации.
* @param uiState Текущее состояние UI экрана.
* @param onLocationClick Лямбда-обработчик нажатия на местоположение.
* @param onLabelClick Лямбда-обработчик нажатия на метку.
* @summary Displays the main content of the screen depending on the uiState.
* @param modifier A modifier for styling.
* @param uiState The current UI state of the screen.
* @param onLocationClick A lambda handler for clicking on a location.
* @param onLabelClick A lambda handler for clicking on a label.
*/
@Composable
private fun DashboardContent(
@@ -132,8 +131,8 @@ private fun DashboardContent(
// [ENTITY: Function('StatisticsSection')]
// [RELATION: Function('StatisticsSection')] -> [DEPENDS_ON] -> [DataClass('GroupStatistics')]
/**
* @summary Секция для отображения общей статистики.
* @param statistics Объект со статистическими данными.
* @summary Section for displaying general statistics.
* @param statistics The object with statistical data.
*/
@Composable
private fun StatisticsSection(statistics: GroupStatistics) {
@@ -164,9 +163,9 @@ private fun StatisticsSection(statistics: GroupStatistics) {
// [ENTITY: Function('StatisticCard')]
/**
* @summary Карточка для отображения одного статистического показателя.
* @param title Название показателя.
* @param value Значение показателя.
* @summary Card for displaying a single statistical indicator.
* @param title The name of the indicator.
* @param value The value of the indicator.
*/
@Composable
private fun StatisticCard(title: String, value: String) {
@@ -180,8 +179,8 @@ private fun StatisticCard(title: String, value: String) {
// [ENTITY: Function('RecentlyAddedSection')]
// [RELATION: Function('RecentlyAddedSection')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* @summary Секция для отображения недавно добавленных элементов.
* @param items Список элементов для отображения.
* @summary Section for displaying recently added items.
* @param items The list of items to display.
*/
@Composable
private fun RecentlyAddedSection(items: List<ItemSummary>) {
@@ -213,8 +212,8 @@ private fun RecentlyAddedSection(items: List<ItemSummary>) {
// [ENTITY: Function('ItemCard')]
// [RELATION: Function('ItemCard')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* @summary Карточка для отображения краткой информации об элементе.
* @param item Элемент для отображения.
* @summary Card for displaying brief information about an item.
* @param item The item to display.
*/
@Composable
private fun ItemCard(item: ItemSummary) {
@@ -236,9 +235,9 @@ private fun ItemCard(item: ItemSummary) {
// [ENTITY: Function('LocationsSection')]
// [RELATION: Function('LocationsSection')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* @summary Секция для отображения местоположений в виде чипсов.
* @param locations Список местоположений.
* @param onLocationClick Лямбда-обработчик нажатия на местоположение.
* @summary Section for displaying locations as chips.
* @param locations The list of locations.
* @param onLocationClick A lambda handler for clicking on a location.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
@@ -265,9 +264,9 @@ private fun LocationsSection(locations: List<LocationOutCount>, onLocationClick:
// [ENTITY: Function('LabelsSection')]
// [RELATION: Function('LabelsSection')] -> [DEPENDS_ON] -> [DataClass('LabelOut')]
/**
* @summary Секция для отображения меток в виде чипсов.
* @param labels Список меток.
* @param onLabelClick Лямбда-обработчик нажатия на метку.
* @summary Section for displaying labels as chips.
* @param labels The list of labels.
* @param onLabelClick A lambda handler for clicking on a label.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.dashboard
// [FILE] DashboardUiState.kt
// [SEMANTICS] ui, state, dashboard
// [SEMANTICS] app, ui, state, dashboard
package com.homebox.lens.ui.screen.dashboard
// [IMPORTS]
@@ -12,8 +11,8 @@ import com.homebox.lens.domain.model.LocationOutCount
// [ENTITY: SealedInterface('DashboardUiState')]
/**
* @summary Определяет все возможные состояния для экрана "Дэшборд".
* @invariant В любой момент времени экран может находиться только в одном из этих состояний.
* @summary Defines all possible states for the "Dashboard" screen.
* @invariant At any given time, the screen can only be in one of these states.
*/
sealed interface DashboardUiState {
// [ENTITY: DataClass('Success')]
@@ -22,11 +21,11 @@ sealed interface DashboardUiState {
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('LabelOut')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* @summary Состояние успешной загрузки данных.
* @param statistics Статистика по инвентарю.
* @param locations Список локаций со счетчиками.
* @param labels Список всех меток.
* @param recentlyAddedItems Список недавно добавленных товаров.
* @summary The state of a successful data load.
* @param statistics The inventory statistics.
* @param locations The list of locations with counters.
* @param labels The list of all labels.
* @param recentlyAddedItems The list of recently added items.
*/
data class Success(
val statistics: GroupStatistics,
@@ -38,15 +37,15 @@ sealed interface DashboardUiState {
// [ENTITY: DataClass('Error')]
/**
* @summary Состояние ошибки во время загрузки данных.
* @param message Человекочитаемое сообщение об ошибке.
* @summary The state of an error during data loading.
* @param message A human-readable error message.
*/
data class Error(val message: String) : DashboardUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: Object('Loading')]
/**
* @summary Состояние, когда данные для экрана загружаются.
* @summary The state when data for the screen is being loaded.
*/
data object Loading : DashboardUiState
// [END_ENTITY: Object('Loading')]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.dashboard
// [FILE] DashboardViewModel.kt
// [SEMANTICS] ui_logic, dashboard, state_management, sealed_state, parallel_data_loading, timber_logging
// [SEMANTICS] app, ui, viewmodel, dashboard
package com.homebox.lens.ui.screen.dashboard
// [IMPORTS]
@@ -24,10 +23,10 @@ import javax.inject.Inject
// [RELATION: ViewModel('DashboardViewModel')] -> [DEPENDS_ON] -> [UseCase('GetRecentlyAddedItemsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [EMITS_STATE] -> [SealedInterface('DashboardUiState')]
/**
* @summary ViewModel для главного экрана (Dashboard).
* @description Оркестрирует загрузку данных для Dashboard, используя строгую модель состояний
* (`DashboardUiState`), и обрабатывает параллельные запросы без состояний гонки.
* @invariant `uiState` всегда является одним из состояний, определенных в `DashboardUiState`.
* @summary ViewModel for the main screen (Dashboard).
* @description Orchestrates the loading of data for the Dashboard, using a strict state model
* (`DashboardUiState`), and handles parallel requests without race conditions.
* @invariant `uiState` is always one of the states defined in `DashboardUiState`.
*/
@HiltViewModel
class DashboardViewModel @Inject constructor(
@@ -46,10 +45,10 @@ class DashboardViewModel @Inject constructor(
// [ENTITY: Function('loadDashboardData')]
/**
* @summary Загружает все необходимые данные для экрана Dashboard.
* @description Выполняет UseCase'ы параллельно и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error` из `DashboardUiState`.
* @sideeffect Асинхронно обновляет `_uiState` одним из состояний `DashboardUiState`.
* @summary Loads all necessary data for the Dashboard screen.
* @description Executes UseCases in parallel and updates the UI by switching it
* between the `Loading`, `Success`, and `Error` states from `DashboardUiState`.
* @sideeffect Asynchronously updates `_uiState` with one of the `DashboardUiState` states.
*/
fun loadDashboardData() {
viewModelScope.launch {

View File

@@ -1,39 +0,0 @@
// [PACKAGE] com.homebox.lens.ui.screen.inventorylist
// [FILE] InventoryListScreen.kt
// [SEMANTICS] ui, screen, inventory, list
package com.homebox.lens.ui.screen.inventorylist
// [IMPORTS]
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.homebox.lens.R
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.common.MainScaffold
// [END_IMPORTS]
// [ENTITY: Function('InventoryListScreen')]
// [RELATION: Function('InventoryListScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('InventoryListScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* @summary Composable-функция для экрана "Список инвентаря".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
*/
@Composable
fun InventoryListScreen(
currentRoute: String?,
navigationActions: NavigationActions
) {
MainScaffold(
topBarTitle = stringResource(id = R.string.inventory_list_title),
currentRoute = currentRoute,
navigationActions = navigationActions
) {
// [AI_NOTE]: Implement Inventory List Screen UI
Text(text = "Inventory List Screen")
}
}
// [END_ENTITY: Function('InventoryListScreen')]
// [END_FILE_InventoryListScreen.kt]

View File

@@ -1,21 +0,0 @@
// [PACKAGE] com.homebox.lens.ui.screen.inventorylist
// [FILE] InventoryListViewModel.kt
// [SEMANTICS] ui, viewmodel, inventory_list
package com.homebox.lens.ui.screen.inventorylist
// [IMPORTS]
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
// [END_IMPORTS]
// [ENTITY: ViewModel('InventoryListViewModel')]
/**
* @summary ViewModel for the inventory list screen.
*/
@HiltViewModel
class InventoryListViewModel @Inject constructor() : ViewModel() {
// [AI_NOTE]: Implement UI state
}
// [END_ENTITY: ViewModel('InventoryListViewModel')]
// [END_FILE_InventoryListViewModel.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemdetails
// [FILE] ItemDetailsScreen.kt
// [SEMANTICS] ui, screen, item, details
// [SEMANTICS] app, ui, screen, details
package com.homebox.lens.ui.screen.itemdetails
@@ -17,9 +16,9 @@ import com.homebox.lens.ui.common.MainScaffold
// [RELATION: Function('ItemDetailsScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('ItemDetailsScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* @summary Composable-функция для экрана "Детали элемента".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @summary Composable function for the "Item Details" screen.
* @param currentRoute The current route to highlight the active item in the Drawer.
* @param navigationActions The object with navigation actions.
*/
@Composable
fun ItemDetailsScreen(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemdetails
// [FILE] ItemDetailsViewModel.kt
// [SEMANTICS] ui, viewmodel, item_details
// [SEMANTICS] app, ui, viewmodel, details
package com.homebox.lens.ui.screen.itemdetails
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemedit
// [FILE] ItemEditScreen.kt
// [SEMANTICS] ui, screen, item, edit
// [SEMANTICS] app, ui, screen, edit
package com.homebox.lens.ui.screen.itemedit
@@ -21,13 +20,17 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -38,6 +41,7 @@ import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -67,12 +71,12 @@ import java.util.Locale
// [RELATION: Composable('ItemEditScreen')] -> [CONSUMES_STATE] -> [DataClass('ItemEditUiState')]
// [RELATION: Composable('ItemEditScreen')] -> [CALLS] -> [Composable('MainScaffold')]
/**
* @summary Composable-функция для экрана "Редактирование элемента".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @param itemId ID элемента для редактирования. Null, если создается новый элемент.
* @param viewModel ViewModel для управления состоянием экрана.
* @param onSaveSuccess Callback, вызываемый после успешного сохранения товара.
* @summary Composable function for the "Edit Item" screen.
* @param currentRoute The current route to highlight the active item in the Drawer.
* @param navigationActions The object with navigation actions.
* @param itemId The ID of the item to edit. Null if a new item is being created.
* @param viewModel The ViewModel for managing the screen's state.
* @param onSaveSuccess A callback invoked after the item is successfully saved.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -165,33 +169,123 @@ fun ItemEditScreen(
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
// [AI_NOTE]: Location selection will require a separate component or screen.
// Location Dropdown
var locationExpanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = locationExpanded,
onExpandedChange = { locationExpanded = !locationExpanded }
) {
OutlinedTextField(
value = item.location?.name ?: "",
onValueChange = { /* TODO: Implement location selection */ },
onValueChange = { },
label = { Text(stringResource(R.string.item_edit_location)) },
readOnly = true,
trailingIcon = {
IconButton(onClick = { /* TODO: Implement location selection */ }) {
Icon(Icons.Filled.ArrowDropDown, contentDescription = stringResource(R.string.item_edit_select_location))
}
ExposedDropdownMenuDefaults.TrailingIcon(expanded = locationExpanded)
},
modifier = Modifier.fillMaxWidth()
modifier = Modifier
.fillMaxWidth()
.menuAnchor()
)
ExposedDropdownMenu(
expanded = locationExpanded,
onDismissRequest = { locationExpanded = false }
) {
uiState.allLocations.forEach { location ->
DropdownMenuItem(
text = { Text(location.name) },
onClick = {
viewModel.updateLocation(location)
locationExpanded = false
}
)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
// [AI_NOTE]: Label selection will require a separate component or screen.
// Labels Dialog
var showLabelsDialog by remember { mutableStateOf(false) }
OutlinedTextField(
value = item.labels.joinToString { it.name },
onValueChange = { /* TODO: Implement label selection */ },
onValueChange = { },
label = { Text(stringResource(R.string.item_edit_labels)) },
readOnly = true,
modifier = Modifier
.fillMaxWidth()
.clickable { showLabelsDialog = true },
trailingIcon = {
IconButton(onClick = { /* TODO: Implement label selection */ }) {
Icon(Icons.Filled.ArrowDropDown, contentDescription = stringResource(R.string.item_edit_select_labels))
}
},
modifier = Modifier.fillMaxWidth()
)
if (showLabelsDialog) {
// This state will hold the temporary selections within the dialog
val tempSelectedLabels = remember { mutableStateOf(item.labels.toSet()) }
AlertDialog(
onDismissRequest = { showLabelsDialog = false },
title = { Text(stringResource(R.string.item_edit_select_labels)) },
text = {
Column {
uiState.allLabels.forEach { label ->
val isChecked = tempSelectedLabels.value.contains(label)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable {
val currentSelection = tempSelectedLabels.value.toMutableSet()
if (isChecked) {
currentSelection.remove(label)
} else {
currentSelection.add(label)
}
tempSelectedLabels.value = currentSelection
}
.padding(vertical = 8.dp)
) {
Checkbox(
checked = isChecked,
onCheckedChange = {
val currentSelection = tempSelectedLabels.value.toMutableSet()
if (it) {
currentSelection.add(label)
} else {
currentSelection.remove(label)
}
tempSelectedLabels.value = currentSelection
}
)
Text(
text = label.name,
modifier = Modifier.padding(start = 8.dp)
)
}
}
}
},
confirmButton = {
TextButton(
onClick = {
// Update the ViewModel with the final selection
viewModel.updateLabels(tempSelectedLabels.value.toList())
showLabelsDialog = false
}
) {
Text(stringResource(R.string.dialog_ok))
}
},
dismissButton = {
TextButton(onClick = { showLabelsDialog = false }) {
Text(stringResource(R.string.dialog_cancel))
}
}
)
}
}
}

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemedit
// [FILE] ItemEditViewModel.kt
// [SEMANTICS] ui, viewmodel, item_edit
// [SEMANTICS] app, ui, viewmodel, edit
package com.homebox.lens.ui.screen.itemedit
@@ -16,6 +15,7 @@ import com.homebox.lens.domain.usecase.CreateItemUseCase
import com.homebox.lens.domain.usecase.GetAllLabelsUseCase
import com.homebox.lens.domain.usecase.GetAllLocationsUseCase
import com.homebox.lens.domain.usecase.GetItemDetailsUseCase
import com.homebox.lens.data.mapper.toDomain
import com.homebox.lens.domain.usecase.UpdateItemUseCase
import com.homebox.lens.ui.mapper.ItemMapper
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -59,6 +59,8 @@ data class ItemEditUiState(
* @param createItemUseCase Use case for creating a new item.
* @param updateItemUseCase Use case for updating an existing item.
* @param getItemDetailsUseCase Use case for fetching item details.
* @param getAllLocationsUseCase Use case for fetching all locations.
* @param getAllLabelsUseCase Use case for fetching all labels.
* @param itemMapper Mapper for converting between domain and UI item models.
*/
@HiltViewModel
@@ -141,7 +143,7 @@ class ItemEditViewModel @Inject constructor(
Timber.i("[INFO][ACTION][fetching_all_locations] Fetching all locations.")
val allLocations = getAllLocationsUseCase().map { Location(it.id, it.name) }
Timber.i("[INFO][ACTION][fetching_all_labels] Fetching all labels.")
val allLabels = getAllLabelsUseCase().map { Label(it.id, it.name) }
val allLabels = getAllLabelsUseCase().map { it.toDomain() }
_uiState.value = _uiState.value.copy(allLocations = allLocations, allLabels = allLabels)
Timber.i("[INFO][ACTION][all_locations_labels_fetched] Successfully fetched all locations and labels.")
} catch (e: Exception) {

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.labeledit
// [FILE] LabelEditScreen.kt
// [SEMANTICS] ui, screen, label, edit
// [SEMANTICS] app, ui, screen, edit, label
package com.homebox.lens.ui.screen.labeledit
@@ -24,10 +23,10 @@ import com.homebox.lens.ui.components.LoadingOverlay
// [ENTITY: Function('LabelEditScreen')]
// [RELATION: Function('LabelEditScreen')] -> [DEPENDS_ON] -> [ViewModel('LabelEditViewModel')]
/**
* @summary Composable-функция для экрана "Редактирование метки".
* @param labelId ID метки для редактирования или null для создания новой.
* @param onBack Навигация назад.
* @param onLabelSaved Действие после сохранения метки.
* @summary Composable function for the "Edit Label" screen.
* @param labelId The ID of the label to edit, or null to create a new one.
* @param onBack Navigation back.
* @param onLabelSaved Action after the label is saved.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.labeledit
// [FILE] LabelEditViewModel.kt
// [SEMANTICS] ui, viewmodel, label_management
// [SEMANTICS] app, ui, viewmodel, edit, label
package com.homebox.lens.ui.screen.labeledit

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.labelslist
// [FILE] LabelsListScreen.kt
// [SEMANTICS] ui, labels_list, state_management, compose, dialog
// [SEMANTICS] app, ui, screen, list, label
package com.homebox.lens.ui.screen.labelslist
// [IMPORTS]
@@ -37,7 +36,7 @@ import androidx.hilt.navigation.compose.hiltViewModel
import com.homebox.lens.R
import com.homebox.lens.domain.model.Label
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.navigation.Screen
import com.homebox.lens.ui.navigation.Screen
import com.homebox.lens.ui.common.MainScaffold
import timber.log.Timber
// [END_IMPORTS]
@@ -46,10 +45,10 @@ import timber.log.Timber
// [RELATION: Function('LabelsListScreen')] -> [DEPENDS_ON] -> [ViewModel('LabelsListViewModel')]
// [RELATION: Function('LabelsListScreen')] -> [DEPENDS_ON] -> [Framework('NavController')]
/**
* @summary Отображает экран со списком всех меток.
* @param currentRoute Текущий маршрут навигации.
* @param navigationActions Объект, содержащий действия по навигации.
* @param viewModel ViewModel, предоставляющая состояние UI для экрана меток.
* @summary Displays the screen with a list of all labels.
* @param currentRoute The current navigation route.
* @param navigationActions The object containing navigation actions.
* @param viewModel The ViewModel providing the UI state for the labels screen.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -116,10 +115,10 @@ fun LabelsListScreen(
// [ENTITY: Function('LabelsList')]
// [RELATION: Function('LabelsList')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* @summary Composable-функция для отображения списка меток.
* @param labels Список объектов `Label` для отображения.
* @param onLabelClick Лямбда-функция, вызываемая при нажатии на элемент списка.
* @param modifier Модификатор для настройки внешнего вида.
* @summary Composable function for displaying a list of labels.
* @param labels The list of `Label` objects to display.
* @param onLabelClick A lambda function called when a list item is clicked.
* @param modifier A modifier for customizing the appearance.
*/
@Composable
private fun LabelsList(
@@ -145,9 +144,9 @@ private fun LabelsList(
// [ENTITY: Function('LabelListItem')]
// [RELATION: Function('LabelListItem')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* @summary Composable-функция для отображения одного элемента в списке меток.
* @param label Объект `Label`, который нужно отобразить.
* @param onClick Лямбда-функция, вызываемая при нажатии на элемент.
* @summary Composable function for displaying a single item in the list of labels.
* @param label The `Label` object to display.
* @param onClick A lambda function called when the item is clicked.
*/
@Composable
private fun LabelListItem(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.labelslist
// [FILE] LabelsListUiState.kt
// [SEMANTICS] ui_state, sealed_interface, contract
// [SEMANTICS] app, ui, state, list, label
package com.homebox.lens.ui.screen.labelslist
// [IMPORTS]
@@ -9,17 +8,17 @@ import com.homebox.lens.domain.model.Label
// [ENTITY: SealedInterface('LabelsListUiState')]
/**
* @summary Определяет все возможные состояния для UI экрана со списком меток.
* @description Использование sealed-интерфейса позволяет исчерпывающе обрабатывать все состояния в Composable-функциях.
* @summary Defines all possible states for the UI of the screen with a list of labels.
* @description Using a sealed interface allows for exhaustive handling of all states in Composable functions.
*/
sealed interface LabelsListUiState {
// [ENTITY: DataClass('Success')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* @summary Состояние успеха, содержит список меток и состояние диалога.
* @param labels Список меток для отображения.
* @param isShowingCreateDialog Флаг, показывающий, должен ли быть отображен диалог создания метки.
* @invariant labels не может быть null.
* @summary The success state, contains the list of labels and the state of the dialog.
* @param labels The list of labels to display.
* @param isShowingCreateDialog A flag indicating whether the label creation dialog should be displayed.
* @invariant labels cannot be null.
*/
data class Success(
val labels: List<Label>,
@@ -29,17 +28,17 @@ sealed interface LabelsListUiState {
// [ENTITY: DataClass('Error')]
/**
* @summary Состояние ошибки.
* @param message Текст ошибки для отображения пользователю.
* @invariant message не может быть пустой.
* @summary The error state.
* @param message The error text to display to the user.
* @invariant message cannot be empty.
*/
data class Error(val message: String) : LabelsListUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: Object('Loading')]
/**
* @summary Состояние загрузки данных.
* @description Указывает, что идет процесс загрузки меток.
* @summary The data loading state.
* @description Indicates that the process of loading labels is in progress.
*/
data object Loading : LabelsListUiState
// [END_ENTITY: Object('Loading')]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.labelslist
// [FILE] LabelsListViewModel.kt
// [SEMANTICS] ui_logic, labels_list, state_management, dialog_management
// [SEMANTICS] app, ui, viewmodel, list, label
package com.homebox.lens.ui.screen.labelslist
// [IMPORTS]
@@ -21,9 +20,9 @@ import javax.inject.Inject
// [RELATION: ViewModel('LabelsListViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLabelsUseCase')]
// [RELATION: ViewModel('LabelsListViewModel')] -> [EMITS_STATE] -> [SealedInterface('LabelsListUiState')]
/**
* @summary ViewModel для экрана со списком меток.
* @description Управляет состоянием экрана, загружает список меток, обрабатывает ошибки и управляет диалогом создания новой метки.
* @invariant `uiState` всегда является одним из состояний, определенных в `LabelsListUiState`.
* @summary ViewModel for the screen with a list of labels.
* @description Manages the screen state, loads the list of labels, handles errors, and manages the dialog for creating a new label.
* @invariant `uiState` is always one of the states defined in `LabelsListUiState`.
*/
@HiltViewModel
class LabelsListViewModel @Inject constructor(
@@ -39,10 +38,10 @@ class LabelsListViewModel @Inject constructor(
// [ENTITY: Function('loadLabels')]
/**
* @summary Загружает список меток.
* @description Выполняет `GetAllLabelsUseCase` и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error`.
* @sideeffect Асинхронно обновляет `_uiState`.
* @summary Loads the list of labels.
* @description Executes `GetAllLabelsUseCase` and updates the UI by switching it
* between the `Loading`, `Success`, and `Error` states.
* @sideeffect Asynchronously updates `_uiState`.
*/
fun loadLabels() {
viewModelScope.launch {
@@ -77,9 +76,9 @@ class LabelsListViewModel @Inject constructor(
// [ENTITY: Function('onShowCreateDialog')]
/**
* @summary Инициирует отображение диалога для создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `true`.
* @sideeffect Обновляет `_uiState`.
* @summary Initiates the display of the dialog for creating a label.
* @description Updates the `uiState` by setting `isShowingCreateDialog` to `true`.
* @sideeffect Updates `_uiState`.
*/
fun onShowCreateDialog() {
Timber.i("[INFO][ACTION][show_create_dialog] Show create label dialog requested.")
@@ -93,9 +92,9 @@ class LabelsListViewModel @Inject constructor(
// [ENTITY: Function('onDismissCreateDialog')]
/**
* @summary Скрывает диалог создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `false`.
* @sideeffect Обновляет `_uiState`.
* @summary Hides the label creation dialog.
* @description Updates the `uiState` by setting `isShowingCreateDialog` to `false`.
* @sideeffect Updates `_uiState`.
*/
fun onDismissCreateDialog() {
Timber.i("[INFO][ACTION][dismiss_create_dialog] Dismiss create label dialog requested.")
@@ -109,12 +108,12 @@ class LabelsListViewModel @Inject constructor(
// [ENTITY: Function('createLabel')]
/**
* @summary Создает новую метку. [MVP_SCOPE] ЗАГЛУШКА.
* @description В текущей реализации (План Б, Этап 1), эта функция только логирует действие
* и скрывает диалог. Реальная логика сохранения будет добавлена на следующем этапе.
* @param name Название новой метки.
* @precondition `name` не должен быть пустым.
* @sideeffect Логирует действие, обновляет `_uiState`, чтобы скрыть диалог.
* @summary Creates a new label. [MVP_SCOPE] STUB.
* @description In the current implementation (Plan B, Stage 1), this function only logs the action
* and hides the dialog. The actual save logic will be added in the next stage.
* @param name The name of the new label.
* @precondition `name` must not be blank.
* @sideeffect Logs the action, updates `_uiState` to hide the dialog.
*/
fun createLabel(name: String) {
require(name.isNotBlank()) { "[CONTRACT_VIOLATION] Label name cannot be blank." }

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.locationedit
// [FILE] LocationEditScreen.kt
// [SEMANTICS] ui, screen, location, edit
// [SEMANTICS] app, ui, screen, edit, location
package com.homebox.lens.ui.screen.locationedit
@@ -19,8 +18,8 @@ import com.homebox.lens.R
// [ENTITY: Function('LocationEditScreen')]
/**
* @summary Composable-функция для экрана "Редактирование местоположения".
* @param locationId ID местоположения для редактирования или "new" для создания.
* @summary Composable function for the "Edit Location" screen.
* @param locationId The ID of the location to edit, or "new" to create one.
*/
@Composable
fun LocationEditScreen(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.locationslist
// [FILE] LocationsListScreen.kt
// [SEMANTICS] ui, screen, locations, list
// [SEMANTICS] app, ui, screen, list, location
package com.homebox.lens.ui.screen.locationslist
@@ -56,12 +55,12 @@ import com.homebox.lens.ui.theme.HomeboxLensTheme
// [RELATION: Function('LocationsListScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('LocationsListScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* @summary Composable-функция для экрана "Список местоположений".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @param onLocationClick Лямбда-обработчик нажатия на местоположение.
* @param onAddNewLocationClick Лямбда-обработчик нажатия на кнопку добавления нового местоположения.
* @param viewModel ViewModel для этого экрана.
* @summary Composable function for the "List of Locations" screen.
* @param currentRoute The current route to highlight the active item in the Drawer.
* @param navigationActions The object with navigation actions.
* @param onLocationClick A lambda handler for clicking on a location.
* @param onAddNewLocationClick A lambda handler for clicking the button to add a new location.
* @param viewModel The ViewModel for this screen.
*/
@Composable
fun LocationsListScreen(
@@ -104,12 +103,12 @@ fun LocationsListScreen(
// [ENTITY: Function('LocationsListContent')]
// [RELATION: Function('LocationsListContent')] -> [CONSUMES_STATE] -> [SealedInterface('LocationsListUiState')]
/**
* @summary Отображает основной контент экрана в зависимости от `uiState`.
* @param modifier Модификатор для стилизации.
* @param uiState Текущее состояние UI.
* @param onLocationClick Лямбда-обработчик нажатия на местоположение.
* @param onEditLocation Лямбда-обработчик для редактирования местоположения.
* @param onDeleteLocation Лямбда-обработчик для удаления местоположения.
* @summary Displays the main content of the screen depending on the `uiState`.
* @param modifier A modifier for styling.
* @param uiState The current UI state.
* @param onLocationClick A lambda handler for clicking on a location.
* @param onEditLocation A lambda handler for editing a location.
* @param onDeleteLocation A lambda handler for deleting a location.
*/
@Composable
private fun LocationsListContent(
@@ -167,11 +166,11 @@ private fun LocationsListContent(
// [ENTITY: Function('LocationCard')]
// [RELATION: Function('LocationCard')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* @summary Карточка для отображения одного местоположения.
* @param location Данные о местоположении.
* @param onClick Лямбда-обработчик нажатия на карточку.
* @param onEditClick Лямбда-обработчик нажатия на "Редактировать".
* @param onDeleteClick Лямбда-обработчик нажатия на "Удалить".
* @summary Card for displaying a single location.
* @param location The data about the location.
* @param onClick A lambda handler for clicking on the card.
* @param onEditClick A lambda handler for clicking "Edit".
* @param onDeleteClick A lambda handler for clicking "Delete".
*/
@Composable
private fun LocationCard(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.locationslist
// [FILE] LocationsListUiState.kt
// [SEMANTICS] ui, state, locations
// [SEMANTICS] app, ui, state, list, location
package com.homebox.lens.ui.screen.locationslist
@@ -10,30 +9,30 @@ import com.homebox.lens.domain.model.LocationOutCount
// [ENTITY: SealedInterface('LocationsListUiState')]
/**
* @summary Определяет возможные состояния UI для экрана списка местоположений.
* @summary Defines the possible UI states for the list of locations screen.
* @see LocationsListViewModel
*/
sealed interface LocationsListUiState {
// [ENTITY: DataClass('Success')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* @summary Состояние успешной загрузки данных.
* @param locations Список местоположений для отображения.
* @summary The state of a successful data load.
* @param locations The list of locations to display.
*/
data class Success(val locations: List<LocationOutCount>) : LocationsListUiState
// [END_ENTITY: DataClass('Success')]
// [ENTITY: DataClass('Error')]
/**
* @summary Состояние ошибки.
* @param message Сообщение об ошибке.
* @summary The error state.
* @param message The error message.
*/
data class Error(val message: String) : LocationsListUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: Object('Loading')]
/**
* @summary Состояние загрузки данных.
* @summary The data loading state.
*/
object Loading : LocationsListUiState
// [END_ENTITY: Object('Loading')]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.locationslist
// [FILE] LocationsListViewModel.kt
// [SEMANTICS] ui, viewmodel, locations, hilt
// [SEMANTICS] app, ui, viewmodel, list, location
package com.homebox.lens.ui.screen.locationslist
@@ -21,10 +20,10 @@ import javax.inject.Inject
// [RELATION: ViewModel('LocationsListViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLocationsUseCase')]
// [RELATION: ViewModel('LocationsListViewModel')] -> [EMITS_STATE] -> [SealedInterface('LocationsListUiState')]
/**
* @summary ViewModel для экрана списка местоположений.
* @param getAllLocationsUseCase Use case для получения всех местоположений.
* @property uiState Поток, содержащий текущее состояние UI.
* @invariant `uiState` всегда отражает результат последней операции загрузки.
* @summary ViewModel for the list of locations screen.
* @param getAllLocationsUseCase Use case for getting all locations.
* @property uiState A flow containing the current UI state.
* @invariant `uiState` always reflects the result of the last load operation.
*/
@HiltViewModel
class LocationsListViewModel @Inject constructor(
@@ -40,8 +39,8 @@ class LocationsListViewModel @Inject constructor(
// [ENTITY: Function('loadLocations')]
/**
* @summary Загружает список местоположений из репозитория.
* @sideeffect Обновляет `_uiState` в зависимости от результата: Loading -> Success/Error.
* @summary Loads the list of locations from the repository.
* @sideeffect Updates `_uiState` depending on the result: Loading -> Success/Error.
*/
fun loadLocations() {
Timber.d("[DEBUG][ENTRYPOINT][loading_locations] Starting to load locations.")

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.search
// [FILE] SearchScreen.kt
// [SEMANTICS] ui, screen, search
// [SEMANTICS] app, ui, screen, search
package com.homebox.lens.ui.screen.search
@@ -17,9 +16,9 @@ import com.homebox.lens.ui.common.MainScaffold
// [RELATION: Function('SearchScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('SearchScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* @summary Composable-функция для экрана "Поиск".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @summary Composable function for the "Search" screen.
* @param currentRoute The current route to highlight the active item in the Drawer.
* @param navigationActions The object with navigation actions.
*/
@Composable
fun SearchScreen(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.search
// [FILE] SearchViewModel.kt
// [SEMANTICS] ui, viewmodel, search
// [SEMANTICS] app, ui, viewmodel, search
package com.homebox.lens.ui.screen.search
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.settings
// [FILE] SettingsScreen.kt
// [SEMANTICS] ui, screen, settings
// [SEMANTICS] app, ui, screen, settings
package com.homebox.lens.ui.screen.settings
@@ -24,9 +23,9 @@ import com.homebox.lens.ui.common.MainScaffold
// [ENTITY: Function('SettingsScreen')]
// [RELATION: Function('SettingsScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
/**
* @summary Composable-функция для экрана настроек.
* @param currentRoute Текущий маршрут навигации.
* @param navigationActions Объект, содержащий действия по навигации.
* @summary Composable function for the settings screen.
* @param currentRoute The current navigation route.
* @param navigationActions The object containing navigation actions.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.screen.setup
// [FILE] SetupScreen.kt
// [SEMANTICS] ui, screen, setup, compose
// [SEMANTICS] app, ui, screen, setup
@file:OptIn(ExperimentalMaterial3Api::class)
@@ -31,10 +30,10 @@ import com.homebox.lens.R
// [RELATION: Function('SetupScreen')] -> [DEPENDS_ON] -> [ViewModel('SetupViewModel')]
// [RELATION: Function('SetupScreen')] -> [CALLS] -> [Function('SetupScreenContent')]
/**
* @summary Главная Composable-функция для экрана настройки соединения с сервером.
* @param viewModel ViewModel для этого экрана, предоставляется через Hilt.
* @param onSetupComplete Лямбда, вызываемая после успешной настройки и входа.
* @sideeffect Вызывает `onSetupComplete` при изменении `uiState.isSetupComplete`.
* @summary The main Composable function for the server connection setup screen.
* @param viewModel The ViewModel for this screen, provided by Hilt.
* @param onSetupComplete A lambda invoked after successful setup and login.
* @sideeffect Calls `onSetupComplete` when `uiState.isSetupComplete` changes.
*/
@Composable
fun SetupScreen(
@@ -60,12 +59,12 @@ fun SetupScreen(
// [ENTITY: Function('SetupScreenContent')]
// [RELATION: Function('SetupScreenContent')] -> [CONSUMES_STATE] -> [DataClass('SetupUiState')]
/**
* @summary Отображает контент экрана настройки: поля ввода и кнопку.
* @param uiState Текущее состояние UI.
* @param onServerUrlChange Лямбда-обработчик изменения URL сервера.
* @param onUsernameChange Лямбда-обработчик изменения имени пользователя.
* @param onPasswordChange Лямбда-обработчик изменения пароля.
* @param onConnectClick Лямбда-обработчик нажатия на кнопку "Подключиться".
* @summary Displays the content of the setup screen: input fields and a button.
* @param uiState The current UI state.
* @param onServerUrlChange A lambda handler for changing the server URL.
* @param onUsernameChange A lambda handler for changing the username.
* @param onPasswordChange A lambda handler for changing the password.
* @param onConnectClick A lambda handler for clicking the "Connect" button.
*/
@Composable
private fun SetupScreenContent(
@@ -75,11 +74,7 @@ private fun SetupScreenContent(
onPasswordChange: (String) -> Unit,
onConnectClick: () -> Unit
) {
Scaffold(
topBar = {
TopAppBar(title = { Text(stringResource(id = R.string.setup_title)) })
}
) { paddingValues ->
Scaffold { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
@@ -96,8 +91,12 @@ private fun SetupScreenContent(
Spacer(modifier = Modifier.height(16.dp))
Text(
text = stringResource(id = R.string.setup_title),
style = MaterialTheme.typography.headlineLarge,
fontSize = 28.sp // Adjust font size as needed
style = MaterialTheme.typography.headlineLarge
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Enter your Homebox server details to connect.",
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(24.dp))
@@ -106,8 +105,7 @@ private fun SetupScreenContent(
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
) {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
modifier = Modifier.padding(16.dp)
) {
OutlinedTextField(
value = uiState.serverUrl,
@@ -115,14 +113,14 @@ private fun SetupScreenContent(
label = { Text(stringResource(id = R.string.setup_server_url_label)) },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(12.dp))
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = uiState.username,
onValueChange = onUsernameChange,
label = { Text(stringResource(id = R.string.setup_username_label)) },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(12.dp))
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = uiState.password,
onValueChange = onPasswordChange,
@@ -138,7 +136,7 @@ private fun SetupScreenContent(
enabled = !uiState.isLoading,
modifier = Modifier
.fillMaxWidth()
.height(56.dp) // Make button more prominent
.height(50.dp)
) {
if (uiState.isLoading) {
CircularProgressIndicator(
@@ -146,15 +144,14 @@ private fun SetupScreenContent(
color = MaterialTheme.colorScheme.onPrimary
)
} else {
Text(stringResource(id = R.string.setup_connect_button), fontSize = 18.sp)
Text(stringResource(id = R.string.setup_connect_button))
}
}
uiState.error?.let {
Spacer(modifier = Modifier.height(12.dp))
Spacer(modifier = Modifier.height(8.dp))
Text(
text = it,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium
color = MaterialTheme.colorScheme.error
)
}
}

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.ui.screen.setup
// [FILE] SetupUiState.kt
// [SEMANTICS] ui_state, data_model, immutable

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.ui.screen.setup
// [FILE] SetupViewModel.kt
// [SEMANTICS] ui_logic, viewmodel, state_management, user_setup, authentication_flow
package com.homebox.lens.ui.screen.setup

View File

@@ -1,9 +1,8 @@
// [PACKAGE] com.homebox.lens.ui.screen.splash
// [FILE] SplashScreen.kt
// [SEMANTICS] ui, screen, splash, navigation, authentication_flow
// [SEMANTICS] app, ui, screen, splash
package com.homebox.lens.ui.screen.splash
// [IMPORTS]
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
@@ -13,45 +12,49 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.homebox.lens.navigation.Screen
import com.homebox.lens.ui.navigation.Screen
import com.homebox.lens.ui.screen.setup.SetupViewModel
import timber.log.Timber
// [END_IMPORTS]
// [ENTITY: Function('SplashScreen')]
// [ENTITY: Composable('SplashScreen')]
// [RELATION: Composable('SplashScreen')] -> [DEPENDS_ON] -> [Framework('NavController')]
// [RELATION: Composable('SplashScreen')] -> [DEPENDS_ON] -> [ViewModel('SetupViewModel')]
/**
* @summary Displays a splash screen while checking if credentials are saved.
* @param navController The NavController for navigation.
* @param viewModel The SetupViewModel to check credential status.
* @sideeffect Navigates to either SetupScreen or DashboardScreen based on credential status.
* @summary A splash screen that checks for saved credentials and navigates accordingly.
* @param navController The navigation controller for navigating to the next screen.
* @param viewModel The view model for checking credentials.
* @sideeffect Navigates to either the Setup or Dashboard screen.
*/
@Composable
fun SplashScreen(
navController: NavController,
viewModel: SetupViewModel = hiltViewModel()
) {
Timber.d("[DEBUG][ENTRYPOINT][splash_screen_composable] SplashScreen entered.")
LaunchedEffect(key1 = true) {
Timber.i("[INFO][ACTION][checking_credentials_on_launch] Checking if credentials are saved on launch.")
val credentialsSaved = viewModel.areCredentialsSaved()
if (credentialsSaved) {
Timber.i("[INFO][ACTION][credentials_found_navigating_dashboard] Credentials found, navigating to Dashboard.")
navController.navigate(Screen.Dashboard.route) {
popUpTo(Screen.Splash.route) { inclusive = true }
}
} else {
Timber.i("[INFO][ACTION][no_credentials_found_navigating_setup] No credentials found, navigating to Setup.")
navController.navigate(Screen.Setup.route) {
popUpTo(Screen.Splash.route) { inclusive = true }
}
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
LaunchedEffect(Unit) {
Timber.d("[DEBUG][ACTION][checking_credentials] Checking for saved credentials on splash screen.")
val areCredentialsSaved = viewModel.areCredentialsSaved()
val destination = if (areCredentialsSaved) {
Timber.d("[DEBUG][SUCCESS][credentials_found] Credentials found, navigating to Dashboard.")
Screen.Dashboard.route
} else {
Timber.d("[DEBUG][FALLBACK][no_credentials] No credentials found, navigating to Setup.")
Screen.Setup.route
}
// [END_ENTITY: Function('SplashScreen')]
navController.navigate(destination) {
popUpTo(Screen.Splash.route) {
inclusive = true
}
}
}
}
// [END_ENTITY: Composable('SplashScreen')]
// [END_FILE_SplashScreen.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Color.kt
// [SEMANTICS] ui, theme, color
// [SEMANTICS] app, ui, theme, color
package com.homebox.lens.ui.theme
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Theme.kt
// [SEMANTICS] ui, theme
// [SEMANTICS] app, ui, theme
package com.homebox.lens.ui.theme
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Typography.kt
// [SEMANTICS] ui, theme, typography
// [SEMANTICS] app, ui, theme, typography
package com.homebox.lens.ui.theme
// [IMPORTS]

View File

@@ -1,121 +0,0 @@
<resources>
<string name="app_name">Homebox Lens</string>
<!-- Common -->
<string name="create">Create</string>
<string name="edit">Edit</string>
<string name="delete">Delete</string>
<string name="search">Search</string>
<string name="logout">Logout</string>
<string name="no_location">No location</string>
<string name="items_not_found">Items not found</string>
<string name="error_loading_failed">Failed to load data. Please try again.</string>
<!-- Content Descriptions -->
<string name="cd_open_navigation_drawer">Open navigation drawer</string>
<string name="cd_scan_qr_code">Scan QR code</string>
<string name="cd_navigate_back">Navigate back</string>
<string name="cd_add_new_location">Add new location</string>
<string name="content_desc_add_label">Add new label</string>
<!-- Dashboard Screen -->
<string name="dashboard_title">Dashboard</string>
<string name="dashboard_section_quick_stats">Quick Stats</string>
<string name="dashboard_section_recently_added">Recently Added</string>
<string name="dashboard_section_locations">Locations</string>
<string name="dashboard_section_labels">Labels</string>
<string name="location_chip_label">%1$s (%2$d)</string>
<!-- Dashboard Statistics -->
<string name="dashboard_stat_total_items">Total Items</string>
<string name="dashboard_stat_total_value">Total Value</string>
<string name="dashboard_stat_total_labels">Total Labels</string>
<string name="dashboard_stat_total_locations">Total Locations</string>
<!-- Navigation -->
<string name="nav_locations">Locations</string>
<string name="nav_labels">Labels</string>
<!-- Screen Titles -->
<string name="inventory_list_title">Inventory</string>
<!-- Screen Titles -->
<string name="item_details_title">Details</string>
<string name="item_edit_title">Edit Item</string>
<string name="labels_list_title">Labels</string>
<string name="locations_list_title">Locations</string>
<string name="search_title">Search</string>
<string name="save_item">Save</string>
<string name="item_name">Name</string>
<string name="item_description">Description</string>
<string name="item_quantity">Quantity</string>
<!-- Location Edit Screen -->
<string name="location_edit_title_create">Create Location</string>
<string name="location_edit_title_edit">Edit Location</string>
<!-- Locations List Screen -->
<string name="locations_not_found">Locations not found. Press + to add a new one.</string>
<string name="item_count">Items: %1$d</string>
<string name="cd_more_options">More options</string>
<!-- Setup Screen -->
<string name="setup_title">Server Setup</string>
<string name="setup_server_url_label">Server URL</string>
<string name="setup_username_label">Username</string>
<string name="setup_password_label">Password</string>
<string name="setup_connect_button">Connect</string>
<!-- Labels List Screen -->
<string name="screen_title_labels">Labels</string>
<string name="content_desc_navigate_back">Navigate back</string>
<string name="content_desc_create_label">Create new label</string>
<string name="content_desc_label_icon">Label icon</string>
<string name="no_labels_found">No labels found.</string>
<string name="dialog_title_create_label">Create Label</string>
<string name="dialog_field_label_name">Label Name</string>
<string name="dialog_button_create">Create</string>
<string name="dialog_button_cancel">Cancel</string>
<!-- Inventory List Screen -->
<string name="content_desc_sync_inventory">Sync inventory</string>
<!-- Item Details Screen -->
<string name="content_desc_edit_item">Edit item</string>
<string name="content_desc_delete_item">Delete item</string>
<string name="section_title_description">Description</string>
<string name="placeholder_no_description">No description</string>
<string name="section_title_details">Details</string>
<string name="label_quantity">Quantity</string>
<string name="label_location">Location</string>
<string name="section_title_labels">Labels</string>
<!-- Item Edit Screen -->
<string name="item_edit_title_create">Create item</string>
<string name="content_desc_save_item">Save item</string>
<string name="label_name">Name</string>
<string name="label_description">Description</string>
<!-- Search Screen -->
<string name="placeholder_search_items">Search items...</string>
<!-- Setup Screen -->
<string name="screen_title_setup">Setup</string>
<!-- Label Edit Screen -->
<string name="label_edit_title_create">Create label</string>
<string name="label_edit_title_edit">Edit label</string>
<string name="label_name_edit">Label name</string>
<!-- Common Actions -->
<string name="back">Back</string>
<string name="save">Save</string>
<!-- Color Picker -->
<string name="label_color">Color</string>
<string name="label_hex_color">HEX color code</string>
</resources>

View File

@@ -2,85 +2,112 @@
<string name="app_name">Homebox Lens</string>
<!-- Common -->
<string name="create">Создать</string>
<string name="edit">Редактировать</string>
<string name="delete">Удалить</string>
<string name="search">Поиск</string>
<string name="logout">Выйти</string>
<string name="no_location">Нет локации</string>
<string name="items_not_found">Элементы не найдены</string>
<string name="error_loading_failed">Не удалось загрузить данные. Пожалуйста, попробуйте еще раз.</string>
<string name="create">Create</string>
<string name="edit">Edit</string>
<string name="delete">Delete</string>
<string name="search">Search</string>
<string name="logout">Logout</string>
<string name="no_location">No location</string>
<string name="items_not_found">Items not found</string>
<string name="error_loading_failed">Failed to load data. Please try again.</string>
<!-- Content Descriptions -->
<string name="cd_open_navigation_drawer">Открыть боковое меню</string>
<string name="cd_scan_qr_code">Сканировать QR-код</string>
<string name="cd_navigate_back">Вернуться назад</string>
<string name="cd_add_new_location">Добавить новую локацию</string>
<string name="content_desc_add_label">Добавить новую метку</string>
<!-- Inventory List Screen -->
<string name="content_desc_sync_inventory">Синхронизировать инвентарь</string>
<!-- Item Details Screen -->
<string name="content_desc_edit_item">Редактировать элемент</string>
<string name="content_desc_delete_item">Удалить элемент</string>
<string name="section_title_description">Описание</string>
<string name="placeholder_no_description">Нет описания</string>
<string name="section_title_details">Детали</string>
<string name="label_quantity">Количество</string>
<string name="label_location">Местоположение</string>
<string name="section_title_labels">Метки</string>
<!-- Item Edit Screen -->
<string name="item_edit_title_create">Создать элемент</string>
<string name="content_desc_save_item">Сохранить элемент</string>
<string name="label_name">Название</string>
<!-- Search Screen -->
<string name="placeholder_search_items">Поиск элементов...</string>
<string name="cd_open_navigation_drawer">Open navigation drawer</string>
<string name="cd_scan_qr_code">Scan QR code</string>
<string name="cd_navigate_back">Navigate back</string>
<string name="cd_add_new_location">Add new location</string>
<string name="content_desc_add_label">Add new label</string>
<!-- Dashboard Screen -->
<string name="dashboard_title">Главная</string>
<string name="dashboard_section_quick_stats">Быстрая статистика</string>
<string name="dashboard_section_recently_added">Недавно добавлено</string>
<string name="dashboard_section_locations">Места хранения</string>
<string name="dashboard_section_labels">Метки</string>
<string name="dashboard_title">Dashboard</string>
<string name="dashboard_section_quick_stats">Quick Stats</string>
<string name="dashboard_section_recently_added">Recently Added</string>
<string name="dashboard_section_locations">Locations</string>
<string name="dashboard_section_labels">Labels</string>
<string name="location_chip_label">%1$s (%2$d)</string>
<!-- Dashboard Statistics -->
<string name="dashboard_stat_total_items">Всего вещей</string>
<string name="dashboard_stat_total_value">Общая стоимость</string>
<string name="dashboard_stat_total_labels">Всего меток</string>
<string name="dashboard_stat_total_locations">Всего локаций</string>
<string name="dashboard_stat_total_items">Total Items</string>
<string name="dashboard_stat_total_value">Total Value</string>
<string name="dashboard_stat_total_labels">Total Labels</string>
<string name="dashboard_stat_total_locations">Total Locations</string>
<!-- Navigation -->
<string name="nav_locations">Локации</string>
<string name="nav_labels">Метки</string>
<string name="nav_locations">Locations</string>
<string name="nav_labels">Labels</string>
<!-- Screen Titles -->
<string name="inventory_list_title">Инвентарь</string>
<string name="item_details_title">Детали</string>
<string name="item_edit_title">Редактирование</string>
<string name="labels_list_title">Метки</string>
<string name="locations_list_title">Места хранения</string>
<string name="search_title">Поиск</string>
<string name="inventory_list_title">Inventory</string>
<!-- Screen Titles -->
<string name="item_details_title">Details</string>
<string name="item_edit_title">Edit Item</string>
<string name="labels_list_title">Labels</string>
<string name="locations_list_title">Locations</string>
<string name="search_title">Search</string>
<string name="save_item">Save</string>
<string name="item_name">Name</string>
<string name="item_description">Description</string>
<string name="item_quantity">Quantity</string>
<!-- Location Edit Screen -->
<string name="location_edit_title_create">Create Location</string>
<string name="location_edit_title_edit">Edit Location</string>
<!-- Locations List Screen -->
<string name="locations_not_found">Locations not found. Press + to add a new one.</string>
<string name="item_count">Items: %1$d</string>
<string name="cd_more_options">More options</string>
<!-- Setup Screen -->
<string name="setup_title">Server Setup</string>
<string name="setup_server_url_label">Server URL</string>
<string name="setup_username_label">Username</string>
<string name="setup_password_label">Password</string>
<string name="setup_connect_button">Connect</string>
<!-- Labels List Screen -->
<string name="screen_title_labels">Labels</string>
<string name="content_desc_navigate_back">Navigate back</string>
<string name="content_desc_create_label">Create new label</string>
<string name="content_desc_label_icon">Label icon</string>
<string name="no_labels_found">No labels found.</string>
<string name="dialog_title_create_label">Create Label</string>
<string name="dialog_field_label_name">Label Name</string>
<string name="dialog_button_create">Create</string>
<string name="dialog_button_cancel">Cancel</string>
<!-- Inventory List Screen -->
<string name="content_desc_sync_inventory">Sync inventory</string>
<!-- Item Details Screen -->
<string name="content_desc_edit_item">Edit item</string>
<string name="content_desc_delete_item">Delete item</string>
<string name="section_title_description">Description</string>
<string name="placeholder_no_description">No description</string>
<string name="section_title_details">Details</string>
<string name="label_quantity">Quantity</string>
<string name="label_location">Location</string>
<string name="section_title_labels">Labels</string>
<!-- Item Edit Screen -->
<string name="item_edit_title_create">Create item</string>
<string name="content_desc_save_item">Save item</string>
<string name="label_name">Name</string>
<string name="label_description">Description</string>
<string name="save_item">Сохранить</string>
<string name="item_name">Название</string>
<string name="item_description">Описание</string>
<string name="item_quantity">Количество</string>
<string name="item_edit_general_information">General Information</string>
<string name="item_edit_location">Location</string>
<string name="item_edit_select_location">Select Location</string>
<string name="item_edit_labels">Labels</string>
<string name="item_edit_select_labels">Select Labels</string>
<string name="dialog_ok">OK</string>
<string name="dialog_cancel">Cancel</string>
<string name="item_edit_purchase_information">Purchase Information</string>
<string name="item_edit_purchase_price">Purchase Price</string>
<string name="item_edit_purchase_from">Purchase From</string>
<string name="item_edit_purchase_time">Purchase Date</string>
<string name="item_edit_purchase_time">Purchase Time</string>
<string name="item_edit_select_date">Select Date</string>
<string name="dialog_ok">OK</string>
<string name="dialog_cancel">Cancel</string>
<string name="item_edit_warranty_information">Warranty Information</string>
<string name="item_edit_lifetime_warranty">Lifetime Warranty</string>
<string name="item_edit_warranty_details">Warranty Details</string>
@@ -98,50 +125,26 @@
<string name="item_edit_sold_price">Sold Price</string>
<string name="item_edit_sold_to">Sold To</string>
<string name="item_edit_sold_notes">Sold Notes</string>
<string name="item_edit_sold_time">Sold Date</string>
<string name="item_edit_sold_time">Sold Time</string>
<!-- Location Edit Screen -->
<string name="location_edit_title_create">Создать локацию</string>
<string name="location_edit_title_edit">Редактировать локацию</string>
<!-- Locations List Screen -->
<string name="locations_not_found">Местоположения не найдены. Нажмите +, чтобы добавить новое.</string>
<string name="item_count">Предметов: %1$d</string>
<string name="cd_more_options">Больше опций</string>
<!-- Search Screen -->
<string name="placeholder_search_items">Search items...</string>
<!-- Setup Screen -->
<string name="screen_title_setup">Настройка</string>
<string name="setup_title">Настройка сервера</string>
<string name="setup_server_url_label">URL сервера</string>
<string name="setup_username_label">Имя пользователя</string>
<string name="setup_password_label">Пароль</string>
<string name="setup_connect_button">Подключиться</string>
<!-- Labels List Screen -->
<string name="screen_title_labels">Метки</string>
<!-- Settings Screen -->
<string name="screen_title_settings">Настройки</string>
<string name="content_desc_navigate_back" translatable="false">Вернуться назад</string>
<string name="content_desc_create_label">Создать новую метку</string>
<string name="content_desc_label_icon">Иконка метки</string>
<string name="no_labels_found">Метки не найдены.</string>
<string name="dialog_title_create_label">Создать метку</string>
<string name="dialog_field_label_name">Название метки</string>
<string name="dialog_button_create">Создать</string>
<string name="dialog_button_cancel">Отмена</string>
<string name="screen_title_setup">Setup</string>
<string name="screen_title_settings">Settings</string>
<!-- Label Edit Screen -->
<string name="label_edit_title_create">Создать метку</string>
<string name="label_edit_title_edit">Редактировать метку</string>
<string name="label_name_edit">Название метки</string>
<string name="label_description">Описание</string>
<string name="label_edit_title_create">Create label</string>
<string name="label_edit_title_edit">Edit label</string>
<string name="label_name_edit">Label name</string>
<!-- Common Actions -->
<string name="back">Назад</string>
<string name="save">Сохранить</string>
<!-- Common Actions -->
<string name="back">Back</string>
<string name="save">Save</string>
<!-- Color Picker -->
<string name="label_color">Цвет</string>
<string name="label_hex_color">HEX-код цвета</string>
<string name="label_color">Color</string>
<string name="label_hex_color">HEX color code</string>
</resources>

View File

@@ -3,11 +3,13 @@
plugins {
// [PLUGIN] Android Application plugin
id("com.android.application") version "8.13.0" apply false
id("com.android.application") version "8.4.0" apply false
// [PLUGIN] Kotlin Android plugin
id("org.jetbrains.kotlin.android") version "1.9.22" apply false
id("org.jetbrains.kotlin.android") version "1.9.23" apply false
// [PLUGIN] Hilt Android plugin
id("com.google.dagger.hilt.android") version "2.48.1" apply false
// [PLUGIN] KSP plugin
id("com.google.devtools.ksp") version "1.9.23-1.0.19" apply false
}
// [END_FILE_build.gradle.kts]

View File

@@ -1,4 +1,3 @@
// [PACKAGE] buildsrc.dependencies
// [FILE] Dependencies.kt
// [SEMANTICS] build, dependencies
@@ -16,7 +15,7 @@ object Versions {
const val coroutines = "1.7.3"
// Jetpack Compose
const val composeCompiler = "1.5.8"
const val composeCompiler = "1.5.11"
const val composeBom = "2023.10.01"
const val activityCompose = "1.8.2"
const val navigationCompose = "2.7.6"

View File

@@ -6,6 +6,7 @@ plugins {
id("org.jetbrains.kotlin.android")
id("com.google.dagger.hilt.android")
id("kotlin-kapt")
id("com.google.devtools.ksp")
}
android {
@@ -27,11 +28,11 @@ android {
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "1.8"
jvmTarget = "17"
}
}
@@ -51,7 +52,7 @@ dependencies {
implementation(Libs.okhttp)
implementation(Libs.okhttpLoggingInterceptor)
implementation(Libs.moshiKotlin)
kapt(Libs.moshiCodegen)
ksp(Libs.moshiCodegen)
// [DEPENDENCY] Database (Room)
implementation(Libs.roomRuntime)

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] ExampleInstrumentedTest.kt
// [SEMANTICS] testing, android, ktlint, rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] CustomRuleSetProvider.kt
// [SEMANTICS] ktlint, rules, provider
package com.busya.ktlint.rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] FileHeaderRule.kt
// [SEMANTICS] ktlint, rules, file_header
package com.busya.ktlint.rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] MandatoryEntityDeclarationRule.kt
// [SEMANTICS] ktlint, rules, entity_declaration
package com.busya.ktlint.rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] NoStrayCommentsRule.kt
// [SEMANTICS] ktlint, rules, comments
package com.busya.ktlint.rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.busya.ktlint.rules
// [FILE] ExampleUnitTest.kt
// [SEMANTICS] testing, ktlint, rules

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.api
// [FILE] HomeboxApiService.kt
// [SEMANTICS] data, api, retrofit
package com.homebox.lens.data.api
@@ -11,7 +10,7 @@ import retrofit2.http.*
// [ENTITY: Interface('HomeboxApiService')]
/**
* @summary Определяет эндпоинты для взаимодействия с Homebox API, используя DTO.
* @summary Defines the endpoints for interacting with the Homebox API using DTOs.
*/
interface HomeboxApiService {

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] CustomFieldDto.kt
// [SEMANTICS] data_transfer_object, custom_field
// [SEMANTICS] data, dto, custom_field
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.CustomField
// [ENTITY: DataClass('CustomFieldDto')]
/**
* @summary DTO для кастомного поля.
* @summary DTO for a custom field.
*/
@JsonClass(generateAdapter = true)
data class CustomFieldDto(
@@ -25,7 +24,7 @@ data class CustomFieldDto(
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('CustomField')]
/**
* @summary Маппер из CustomFieldDto в доменную модель CustomField.
* @summary Mapper from CustomFieldDto to the CustomField domain model.
*/
fun CustomFieldDto.toDomain(): CustomField {
return CustomField(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] GroupStatisticsDto.kt
// [SEMANTICS] data_transfer_object, statistics
// [SEMANTICS] data, dto, statistics
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.GroupStatistics
// [ENTITY: DataClass('GroupStatisticsDto')]
/**
* @summary DTO для статистики.
* @summary DTO for statistics.
*/
@JsonClass(generateAdapter = true)
data class GroupStatisticsDto(
@@ -28,7 +27,7 @@ data class GroupStatisticsDto(
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('GroupStatistics')]
/**
* @summary Маппер из GroupStatisticsDto в доменную модель GroupStatistics.
* @summary Mapper from GroupStatisticsDto to the GroupStatistics domain model.
*/
fun GroupStatisticsDto.toDomain(): GroupStatistics {
return GroupStatistics(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ImageDto.kt
// [SEMANTICS] data_transfer_object, image
// [SEMANTICS] data, dto, image
package com.homebox.lens.data.api.dto
@@ -12,10 +11,10 @@ import com.homebox.lens.domain.model.Image
// [ENTITY: DataClass('ImageDto')]
/**
* @summary DTO для изображения.
* @param id Уникальный идентификатор.
* @param path Путь к файлу.
* @param isPrimary Является ли основным.
* @summary DTO for an image.
* @param id The unique identifier.
* @param path The path to the file.
* @param isPrimary Whether it is the primary image.
*/
@JsonClass(generateAdapter = true)
data class ImageDto(
@@ -28,7 +27,7 @@ data class ImageDto(
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('Image')]
/**
* @summary Маппер из ImageDto в доменную модель Image.
* @summary Mapper from ImageDto to the Image domain model.
*/
fun ImageDto.toDomain(): Image {
return Image(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemAttachmentDto.kt
// [SEMANTICS] data_transfer_object, attachment
// [SEMANTICS] data, dto, attachment
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.ItemAttachment
// [ENTITY: DataClass('ItemAttachmentDto')]
/**
* @summary DTO для вложения.
* @summary DTO for an attachment.
*/
@JsonClass(generateAdapter = true)
data class ItemAttachmentDto(
@@ -28,7 +27,7 @@ data class ItemAttachmentDto(
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('ItemAttachment')]
/**
* @summary Маппер из ItemAttachmentDto в доменную модель ItemAttachment.
* @summary Mapper from ItemAttachmentDto to the ItemAttachment domain model.
*/
fun ItemAttachmentDto.toDomain(): ItemAttachment {
return ItemAttachment(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemCreateDto.kt
// [SEMANTICS] data_transfer_object, item_creation
// [SEMANTICS] data, dto, item_creation
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.ItemCreate
// [ENTITY: DataClass('ItemCreateDto')]
/**
* @summary DTO для создания вещи.
* @summary DTO for creating an item.
*/
@JsonClass(generateAdapter = true)
data class ItemCreateDto(
@@ -46,7 +45,7 @@ data class ItemCreateDto(
// [ENTITY: Function('toDto')]
// [RELATION: Function('toDto')] -> [RETURNS] -> [DataClass('ItemCreateDto')]
/**
* @summary Маппер из доменной модели ItemCreate в ItemCreateDto.
* @summary Mapper from the ItemCreate domain model to ItemCreateDto.
*/
fun ItemCreate.toItemCreateDto(): ItemCreateDto {
return ItemCreateDto(

View File

@@ -1,74 +0,0 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemDto.kt
// [SEMANTICS] data, dto, api
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.math.BigDecimal
// [END_IMPORTS]
// [ENTITY: DataClass('ItemOut')]
// [RELATION: DataClass('ItemOut')] -> [DEPENDS_ON] -> [DataClass('LocationOut')]
// [RELATION: DataClass('ItemOut')] -> [DEPENDS_ON] -> [DataClass('LabelOutDto')]
/**
* @summary DTO для полной информации о вещи (GET /v1/items/{id}).
*/
@JsonClass(generateAdapter = true)
data class ItemOut(
@Json(name = "id") val id: String,
@Json(name = "name") val name: String,
@Json(name = "description") val description: String?,
@Json(name = "image") val image: String?,
@Json(name = "location") val location: LocationOut?,
@Json(name = "labels") val labels: List<LabelOutDto>,
@Json(name = "value") val value: BigDecimal?,
@Json(name = "createdAt") val createdAt: String?
)
// [END_ENTITY: DataClass('ItemOut')]
// [ENTITY: DataClass('ItemSummary')]
// [RELATION: DataClass('ItemSummary')] -> [DEPENDS_ON] -> [DataClass('LocationOut')]
/**
* @summary DTO для краткой информации о вещи в списках (GET /v1/items).
*/
@JsonClass(generateAdapter = true)
data class ItemSummary(
@Json(name = "id") val id: String,
@Json(name = "name") val name: String,
@Json(name = "image") val image: String?,
@Json(name = "location") val location: LocationOut?,
@Json(name = "createdAt") val createdAt: String?
)
// [END_ENTITY: DataClass('ItemSummary')]
// [ENTITY: DataClass('ItemCreate')]
/**
* @summary DTO для создания новой вещи (POST /v1/items).
*/
@JsonClass(generateAdapter = true)
data class ItemCreate(
@Json(name = "name") val name: String,
@Json(name = "description") val description: String?,
@Json(name = "locationId") val locationId: String?,
@Json(name = "labelIds") val labelIds: List<String>?,
@Json(name = "value") val value: BigDecimal?
)
// [END_ENTITY: DataClass('ItemCreate')]
// [ENTITY: DataClass('ItemUpdate')]
/**
* @summary DTO для обновления вещи (PUT /v1/items/{id}).
*/
@JsonClass(generateAdapter = true)
data class ItemUpdate(
@Json(name = "name") val name: String,
@Json(name = "description") val description: String?,
@Json(name = "locationId") val locationId: String?,
@Json(name = "labelIds") val labelIds: List<String>?,
@Json(name = "value") val value: BigDecimal?
)
// [END_ENTITY: DataClass('ItemUpdate')]
// [END_FILE_ItemDto.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemOutDto.kt
// [SEMANTICS] data_transfer_object, item_detailed
// [SEMANTICS] data, dto, item_detailed
package com.homebox.lens.data.api.dto
@@ -50,3 +49,46 @@ data class ItemOutDto(
@Json(name = "updatedAt") val updatedAt: String
)
// [END_ENTITY: DataClass('ItemOutDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('ItemOut')]
/**
* @summary Mapper from ItemOutDto to the ItemOut domain model.
*/
fun ItemOutDto.toDomain(): ItemOut {
return ItemOut(
id = this.id,
name = this.name,
assetId = this.assetId,
description = this.description,
notes = this.notes,
serialNumber = this.serialNumber,
quantity = this.quantity,
isArchived = this.isArchived,
purchasePrice = this.purchasePrice,
purchaseTime = this.purchaseTime,
purchaseFrom = this.purchaseFrom,
warrantyExpires = this.warrantyExpires,
warrantyDetails = this.warrantyDetails,
lifetimeWarranty = this.lifetimeWarranty,
insured = this.insured,
manufacturer = this.manufacturer,
modelNumber = this.modelNumber,
soldPrice = this.soldPrice,
soldTime = this.soldTime,
soldTo = this.soldTo,
soldNotes = this.soldNotes,
syncChildItemsLocations = this.syncChildItemsLocations,
location = this.location?.toDomain(),
parent = this.parent?.toDomain(),
children = this.children.map { it.toDomain() },
labels = this.labels.map { it.toDomain() },
attachments = this.attachments.map { it.toDomain() },
images = this.images.map { it.toDomain() },
fields = this.fields.map { it.toDomain() },
maintenance = this.maintenance.map { it.toDomain() },
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
// [END_ENTITY: Function('toDomain')]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemSummaryDto.kt
// [SEMANTICS] data_transfer_object, item_summary
// [SEMANTICS] data, dto, item_summary
package com.homebox.lens.data.api.dto
@@ -20,11 +19,32 @@ data class ItemSummaryDto(
@Json(name = "name") val name: String,
@Json(name = "assetId") val assetId: String?,
@Json(name = "image") val image: ImageDto?,
@Json(name = "isArchived") val isArchived: Boolean,
@Json(name = "isArchived") val isArchived: Boolean? = false,
@Json(name = "labels") val labels: List<LabelOutDto>,
@Json(name = "location") val location: LocationOutDto?,
@Json(name = "value") val value: Double,
@Json(name = "value") val value: Double? = 0.0,
@Json(name = "createdAt") val createdAt: String,
@Json(name = "updatedAt") val updatedAt: String
)
// [END_ENTITY: DataClass('ItemSummaryDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('ItemSummary')]
/**
* @summary Mapper from ItemSummaryDto to the ItemSummary domain model.
*/
fun ItemSummaryDto.toDomain(): ItemSummary {
return ItemSummary(
id = this.id,
name = this.name,
assetId = this.assetId,
image = this.image?.toDomain(),
isArchived = this.isArchived ?: false,
labels = this.labels.map { it.toDomain() },
location = this.location?.toDomain(),
value = this.value ?: 0.0,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
// [END_ENTITY: Function('toDomain')]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] ItemUpdateDto.kt
// [SEMANTICS] data_transfer_object, item_update
// [SEMANTICS] data, dto, item_update
package com.homebox.lens.data.api.dto

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LabelCreateDto.kt
// [SEMANTICS] data_transfer_object, label, create, api
// [SEMANTICS] data, dto, label, create
package com.homebox.lens.data.api.dto
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LabelOutDto.kt
// [SEMANTICS] data_transfer_object, label
// [SEMANTICS] data, dto, label
package com.homebox.lens.data.api.dto
@@ -26,4 +25,21 @@ data class LabelOutDto(
)
// [END_ENTITY: DataClass('LabelOutDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('LabelOut')]
/**
* @summary Mapper from LabelOutDto to the LabelOut domain model.
*/
fun LabelOutDto.toDomain(): LabelOut {
return LabelOut(
id = this.id,
name = this.name,
description = this.description,
color = this.color ?: "#000000",
isArchived = this.isArchived ?: false,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
// [END_ENTITY: Function('toDomain')]
// [END_FILE_LabelOutDto.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LabelSummaryDto.kt
// [SEMANTICS] data_transfer_object, label, summary, api, mapper
// [SEMANTICS] data, dto, label, summary
package com.homebox.lens.data.api.dto
// [IMPORTS]

View File

@@ -1,15 +1,16 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LabelUpdateDto.kt
// [SEMANTICS] data_transfer_object, label, update
// [SEMANTICS] data, dto, label, update
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.homebox.lens.domain.model.LabelUpdate
// [END_IMPORTS]
// [ENTITY: DataClass('LabelUpdateDto')]
/**
* @summary DTO for updating a label.
*/
@JsonClass(generateAdapter = true)
data class LabelUpdateDto(
@Json(name = "name")

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LocationCreateDto.kt
// [SEMANTICS] data_transfer_object, location, create
// [SEMANTICS] data, dto, location, create
package com.homebox.lens.data.api.dto
// [IMPORTS]
@@ -9,6 +8,9 @@ import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('LocationCreateDto')]
/**
* @summary DTO for creating a location.
*/
@JsonClass(generateAdapter = true)
data class LocationCreateDto(
@Json(name = "name")

View File

@@ -1,34 +0,0 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LocationDto.kt
// [SEMANTICS] data, dto, api, location
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('LocationOut')]
/**
* @summary DTO для информации о местоположении.
*/
@JsonClass(generateAdapter = true)
data class LocationOut(
@Json(name = "id") val id: String,
@Json(name = "name") val name: String
)
// [END_ENTITY: DataClass('LocationOut')]
// [ENTITY: DataClass('LocationOutCount')]
/**
* @summary DTO для информации о местоположении со счетчиком вещей.
*/
@JsonClass(generateAdapter = true)
data class LocationOutCount(
@Json(name = "id") val id: String,
@Json(name = "name") val name: String,
@Json(name = "itemCount") val itemCount: Int
)
// [END_ENTITY: DataClass('LocationOutCount')]
// [END_FILE_LocationDto.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LocationOutCountDto.kt
// [SEMANTICS] data_transfer_object, location, count
// [SEMANTICS] data, dto, location, count
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.LocationOutCount
// [ENTITY: DataClass('LocationOutCountDto')]
/**
* @summary DTO для местоположения со счетчиком.
* @summary DTO for a location with an item count.
*/
@JsonClass(generateAdapter = true)
data class LocationOutCountDto(
@@ -27,4 +26,21 @@ data class LocationOutCountDto(
)
// [END_ENTITY: DataClass('LocationOutCountDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('LocationOutCount')]
/**
* @summary Mapper from LocationOutCountDto to the LocationOutCount domain model.
*/
fun LocationOutCountDto.toDomain(): LocationOutCount {
return LocationOutCount(
id = this.id,
name = this.name,
color = this.color ?: "#000000",
isArchived = this.isArchived ?: false,
itemCount = this.itemCount,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
// [END_ENTITY: Function('toDomain')]
// [END_FILE_LocationOutCountDto.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LocationOutDto.kt
// [SEMANTICS] data_transfer_object, location, output
// [SEMANTICS] data, dto, location
package com.homebox.lens.data.api.dto
// [IMPORTS]
@@ -17,9 +16,9 @@ data class LocationOutDto(
@Json(name = "name")
val name: String,
@Json(name = "color")
val color: String,
val color: String? = "#000000",
@Json(name = "isArchived")
val isArchived: Boolean,
val isArchived: Boolean? = false,
@Json(name = "createdAt")
val createdAt: String,
@Json(name = "updatedAt")
@@ -27,4 +26,20 @@ data class LocationOutDto(
)
// [END_ENTITY: DataClass('LocationOutDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('LocationOut')]
/**
* @summary Mapper from LocationOutDto to the LocationOut domain model.
*/
fun LocationOutDto.toDomain(): LocationOut {
return LocationOut(
id = this.id,
name = this.name,
color = this.color ?: "#000000",
isArchived = this.isArchived ?: false,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
}
// [END_ENTITY: Function('toDomain')]
// [END_FILE_LocationOutDto.kt]

View File

@@ -1,15 +1,16 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LocationUpdateDto.kt
// [SEMANTICS] data_transfer_object, location, update
// [SEMANTICS] data, dto, location, update
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.homebox.lens.domain.model.LocationUpdate
// [END_IMPORTS]
// [ENTITY: DataClass('LocationUpdateDto')]
/**
* @summary DTO for updating a location.
*/
@JsonClass(generateAdapter = true)
data class LocationUpdateDto(
@Json(name = "name")

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] LoginFormDto.kt
// [SEMANTICS] data, dto, api, login
// [SEMANTICS] data, dto, login
package com.homebox.lens.data.api.dto
// [IMPORTS]
@@ -9,6 +8,9 @@ import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('LoginFormDto')]
/**
* @summary DTO for the login form.
*/
@JsonClass(generateAdapter = true)
data class LoginFormDto(
@Json(name = "username") val username: String,

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] MaintenanceEntryDto.kt
// [SEMANTICS] data_transfer_object, maintenance
// [SEMANTICS] data, dto, maintenance
package com.homebox.lens.data.api.dto
@@ -12,7 +11,7 @@ import com.homebox.lens.domain.model.MaintenanceEntry
// [ENTITY: DataClass('MaintenanceEntryDto')]
/**
* @summary DTO для записи об обслуживании.
* @summary DTO for a maintenance entry.
*/
@JsonClass(generateAdapter = true)
data class MaintenanceEntryDto(
@@ -30,7 +29,7 @@ data class MaintenanceEntryDto(
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('MaintenanceEntry')]
/**
* @summary Маппер из MaintenanceEntryDto в доменную модель MaintenanceEntry.
* @summary Mapper from MaintenanceEntryDto to the MaintenanceEntry domain model.
*/
fun MaintenanceEntryDto.toDomain(): MaintenanceEntry {
return MaintenanceEntry(

View File

@@ -1,25 +0,0 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] PaginationDto.kt
// [SEMANTICS] data, dto, api, pagination
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('PaginationResult')]
/**
* @summary DTO для пагинированных результатов от API.
*/
@JsonClass(generateAdapter = true)
data class PaginationResult<T>(
@Json(name = "items") val items: List<T>,
@Json(name = "page") val page: Int,
@Json(name = "pages") val pages: Int,
@Json(name = "total") val total: Int,
@Json(name = "pageSize") val pageSize: Int
)
// [END_ENTITY: DataClass('PaginationResult')]
// [END_FILE_PaginationDto.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] PaginationResultDto.kt
// [SEMANTICS] data_transfer_object, pagination
// [SEMANTICS] data, dto, pagination
package com.homebox.lens.data.api.dto
@@ -22,3 +21,18 @@ data class PaginationResultDto<T>(
@Json(name = "total") val total: Int
)
// [END_ENTITY: DataClass('PaginationResultDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('PaginationResult')]
/**
* @summary Mapper from PaginationResultDto to the PaginationResult domain model.
*/
fun <T, R> PaginationResultDto<T>.toDomain(mapper: (T) -> R): PaginationResult<R> {
return PaginationResult(
items = this.items.map(mapper),
page = this.page,
pageSize = this.pageSize,
total = this.total
)
}
// [END_ENTITY: Function('toDomain')]

View File

@@ -1,25 +0,0 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] StatisticsDto.kt
// [SEMANTICS] data, dto, api, statistics
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.math.BigDecimal
// [END_IMPORTS]
// [ENTITY: DataClass('GroupStatistics')]
/**
* @summary DTO для статистической информации.
*/
@JsonClass(generateAdapter = true)
data class GroupStatistics(
@Json(name = "totalValue") val totalValue: BigDecimal,
@Json(name = "totalItems") val totalItems: Int,
@Json(name = "locations") val locations: Int,
@Json(name = "labels") val labels: Int
)
// [END_ENTITY: DataClass('GroupStatistics')]
// [END_FILE_StatisticsDto.kt]

View File

@@ -1,14 +1,17 @@
// [PACKAGE] com.homebox.lens.data.api.dto
// [FILE] TokenResponseDto.kt
// [SEMANTICS] data, dto, api, token
// [SEMANTICS] data, dto, token
package com.homebox.lens.data.api.dto
// [IMPORTS]
import com.homebox.lens.domain.model.TokenResponse
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('TokenResponseDto')]
/**
* @summary DTO for the token response.
*/
@JsonClass(generateAdapter = true)
data class TokenResponseDto(
@Json(name = "token") val token: String,
@@ -16,4 +19,18 @@ data class TokenResponseDto(
@Json(name = "expiresAt") val expiresAt: String
)
// [END_ENTITY: DataClass('TokenResponseDto')]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('TokenResponse')]
/**
* @summary Mapper from TokenResponseDto to the TokenResponse domain model.
*/
fun TokenResponseDto.toDomain(): TokenResponse {
return TokenResponse(
token = this.token,
attachmentToken = this.attachmentToken,
expiresAt = this.expiresAt
)
}
// [END_ENTITY: Function('toDomain')]
// [END_FILE_TokenResponseDto.kt]

View File

@@ -1,30 +0,0 @@
// [PACKAGE] com.homebox.lens.data.api.mapper
// [FILE] TokenMapper.kt
// [SEMANTICS] mapper, data_conversion, clean_architecture
package com.homebox.lens.data.api.mapper
// [IMPORTS]
import com.homebox.lens.data.api.dto.TokenResponseDto
import com.homebox.lens.domain.model.TokenResponse
// [END_IMPORTS]
// [ENTITY: Function('toDomain')]
// [RELATION: Function('toDomain')] -> [RETURNS] -> [DataClass('TokenResponse')]
/**
* @summary Преобразует DTO-объект токена в доменную модель.
* @receiver [TokenResponseDto] объект из слоя данных.
* @return [TokenResponse] объект для доменного слоя.
* @throws IllegalArgumentException если токен в DTO пустой.
*/
fun TokenResponseDto.toDomain(): TokenResponse {
require(this.token.isNotBlank()) { "DTO token is blank, cannot map to domain model." }
val domainModel = TokenResponse(token = this.token)
check(domainModel.token.isNotBlank()) { "Domain model token is blank after mapping." }
return domainModel
}
// [END_ENTITY: Function('toDomain')]
// [END_FILE_TokenMapper.kt]

View File

@@ -1,19 +1,19 @@
// [PACKAGE] com.homebox.lens.data.api.model
// [FILE] LoginRequest.kt
// [SEMANTICS] dto, network, serialization, authentication
// [SEMANTICS] data, dto, login
package com.homebox.lens.data.api.model
// [IMPORTS]
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// [END_IMPORTS]
// [ENTITY: DataClass('LoginRequest')]
/**
* [ENTITY: DataClass('LoginRequest')]
* [CONTRACT]
* DTO (Data Transfer Object) для запроса на аутентификацию.
* @property username Имя пользователя.
* @property password Пароль пользователя.
* @invariant Свойства не должны быть пустыми.
* @summary DTO for the authentication request.
* @property username The user's name.
* @property password The user's password.
* @invariant The properties must not be blank.
*/
@JsonClass(generateAdapter = true)
data class LoginRequest(
@@ -21,9 +21,9 @@ data class LoginRequest(
@Json(name = "password") val password: String
) {
init {
// [INVARIANT_CHECK]
require(username.isNotBlank()) { "[INVARIANT_FAILED] Username cannot be blank." }
require(password.isNotBlank()) { "[INVARIANT_FAILED] Password cannot be blank." }
require(username.isNotBlank()) { "Username cannot be blank." }
require(password.isNotBlank()) { "Password cannot be blank." }
}
}
// [END_ENTITY: DataClass('LoginRequest')]
// [END_FILE_LoginRequest.kt]

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db
// [FILE] Converters.kt
// [SEMANTICS] data, database, room, converter
package com.homebox.lens.data.db
@@ -10,7 +9,7 @@ import java.math.BigDecimal
// [ENTITY: Class('Converters')]
/**
* @summary Предоставляет TypeConverters для Room для типов, не поддерживаемых по умолчанию.
* @summary Provides TypeConverters for Room for types not supported by default.
*/
class Converters {
// [ENTITY: Function('fromString')]

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db
// [FILE] HomeboxDatabase.kt
// [SEMANTICS] data, database, room
package com.homebox.lens.data.db
@@ -15,7 +14,7 @@ import com.homebox.lens.data.db.entity.*
// [ENTITY: Database('HomeboxDatabase')]
/**
* @summary Основной класс для работы с локальной базой данных Room.
* @summary The main class for working with the local Room database.
*/
@Database(
entities = [

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.dao
// [FILE] ItemDao.kt
// [SEMANTICS] data, database, dao, item
package com.homebox.lens.data.db.dao
@@ -13,7 +12,7 @@ import kotlinx.coroutines.flow.Flow
// [ENTITY: Interface('ItemDao')]
/**
* @summary Предоставляет методы для работы с 'items' в локальной БД.
* @summary Provides methods for working with 'items' in the local DB.
*/
@Dao
interface ItemDao {

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.dao
// [FILE] LabelDao.kt
// [SEMANTICS] data, database, dao, label
package com.homebox.lens.data.db.dao
@@ -13,7 +12,7 @@ import com.homebox.lens.data.db.entity.LabelEntity
// [ENTITY: Interface('LabelDao')]
/**
* @summary Предоставляет методы для работы с 'labels' в локальной БД.
* @summary Provides methods for working with 'labels' in the local DB.
*/
@Dao
interface LabelDao {

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.dao
// [FILE] LocationDao.kt
// [SEMANTICS] data, database, dao, location
package com.homebox.lens.data.db.dao
@@ -13,7 +12,7 @@ import com.homebox.lens.data.db.entity.LocationEntity
// [ENTITY: Interface('LocationDao')]
/**
* @summary Предоставляет методы для работы с 'locations' в локальной БД.
* @summary Provides methods for working with 'locations' in the local DB.
*/
@Dao
interface LocationDao {

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] ItemEntity.kt
// [SEMANTICS] data, database, entity, item
package com.homebox.lens.data.db.entity
@@ -10,7 +9,7 @@ import androidx.room.PrimaryKey
// [ENTITY: DatabaseTable('ItemEntity')]
/**
* @summary Представляет собой строку в таблице 'items' в локальной БД.
* @summary Represents a row in the 'items' table in the local DB.
*/
@Entity(tableName = "items")
data class ItemEntity(

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] ItemLabelCrossRef.kt
// [SEMANTICS] data, database, entity, relation
package com.homebox.lens.data.db.entity
@@ -10,7 +9,7 @@ import androidx.room.Index
// [ENTITY: DatabaseTable('ItemLabelCrossRef')]
/**
* @summary Таблица для связи "многие-ко-многим" между ItemEntity и LabelEntity.
* @summary Table for the many-to-many relationship between ItemEntity and LabelEntity.
*/
@Entity(
primaryKeys = ["itemId", "labelId"],

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] ItemWithLabels.kt
// [SEMANTICS] data, database, entity, relation
package com.homebox.lens.data.db.entity
@@ -13,7 +12,7 @@ import androidx.room.Relation
// [RELATION: DataClass('ItemWithLabels')] -> [DEPENDS_ON] -> [DatabaseTable('ItemEntity')]
// [RELATION: DataClass('ItemWithLabels')] -> [DEPENDS_ON] -> [DatabaseTable('LabelEntity')]
/**
* @summary POJO для получения ItemEntity вместе со связанными LabelEntity.
* @summary POJO for retrieving an ItemEntity with its associated LabelEntity objects.
*/
data class ItemWithLabels(
@Embedded val item: ItemEntity,

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] LabelEntity.kt
// [SEMANTICS] data, database, entity, label
package com.homebox.lens.data.db.entity
@@ -10,7 +9,7 @@ import androidx.room.PrimaryKey
// [ENTITY: DatabaseTable('LabelEntity')]
/**
* @summary Представляет собой строку в таблице 'labels' в локальной БД.
* @summary Represents a row in the 'labels' table in the local DB.
*/
@Entity(tableName = "labels")
data class LabelEntity(

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] LocationEntity.kt
// [SEMANTICS] data, database, entity, location
package com.homebox.lens.data.db.entity
@@ -10,7 +9,7 @@ import androidx.room.PrimaryKey
// [ENTITY: DatabaseTable('LocationEntity')]
/**
* @summary Представляет собой строку в таблице 'locations' в локальной БД.
* @summary Represents a row in the 'locations' table in the local DB.
*/
@Entity(tableName = "locations")
data class LocationEntity(

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.db.entity
// [FILE] Mapper.kt
// [SEMANTICS] data, database, mapper
package com.homebox.lens.data.db.entity
@@ -11,7 +10,7 @@ import com.homebox.lens.domain.model.*
// [ENTITY: Function('ItemWithLabels.toDomainItemSummary')]
// [RELATION: Function('ItemWithLabels.toDomainItemSummary')] -> [RETURNS] -> [DataClass('ItemSummary')]
/**
* @summary Преобразует [ItemWithLabels] (сущность БД) в [ItemSummary] (доменную модель).
* @summary Converts [ItemWithLabels] (DB entity) to [ItemSummary] (domain model).
*/
fun ItemWithLabels.toDomainItemSummary(): ItemSummary {
return ItemSummary(
@@ -32,7 +31,7 @@ fun ItemWithLabels.toDomainItemSummary(): ItemSummary {
// [ENTITY: Function('ItemEntity.toDomainItem')]
// [RELATION: Function('ItemEntity.toDomainItem')] -> [RETURNS] -> [DataClass('Item')]
/**
* @summary Преобразует [ItemEntity] (сущность БД) в [Item] (доменную модель).
* @summary Converts [ItemEntity] (DB entity) to [Item] (domain model).
*/
fun ItemEntity.toDomainItem(): Item {
return Item(
@@ -71,7 +70,7 @@ fun ItemEntity.toDomainItem(): Item {
// [ENTITY: Function('Item.toItemEntity')]
// [RELATION: Function('Item.toItemEntity')] -> [RETURNS] -> [DataClass('ItemEntity')]
/**
* @summary Преобразует [Item] (доменную модель) в [ItemEntity] (сущность БД).
* @summary Converts [Item] (domain model) to [ItemEntity] (DB entity).
*/
fun Item.toItemEntity(): ItemEntity {
return ItemEntity(

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.di
// [FILE] ApiModule.kt
// [SEMANTICS] di, networking
// [SEMANTICS] data, di, networking
package com.homebox.lens.data.di
// [IMPORTS]
@@ -25,8 +24,8 @@ import javax.inject.Singleton
// [ENTITY: Module('ApiModule')]
/**
* @summary Hilt-модуль, отвечающий за создание и предоставление всех зависимостей,
* необходимых для сетевого взаимодействия.
* @summary Hilt module responsible for creating and providing all dependencies
* necessary for network interaction.
*/
@Module
@InstallIn(SingletonComponent::class)

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.di
// [FILE] DatabaseModule.kt
// [SEMANTICS] di, hilt, database
// [SEMANTICS] data, di, database
package com.homebox.lens.data.di
// [IMPORTS]
@@ -18,7 +17,7 @@ import javax.inject.Singleton
// [ENTITY: Module('DatabaseModule')]
/**
* @summary Предоставляет зависимости для работы с базой данных Room.
* @summary Provides dependencies for working with the Room database.
*/
@Module
@InstallIn(SingletonComponent::class)

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.di
// [FILE] RepositoryModule.kt
// [SEMANTICS] dependency_injection, hilt, module, binding
// [SEMANTICS] data, di, repository
package com.homebox.lens.data.di
@@ -20,8 +19,8 @@ import javax.inject.Singleton
// [ENTITY: Module('RepositoryModule')]
/**
* @summary Hilt-модуль для предоставления реализаций репозиториев.
* @description Использует `@Binds` для эффективного связывания интерфейсов с их реализациями.
* @summary Hilt module for providing repository implementations.
* @description Uses `@Binds` for efficient binding of interfaces to their implementations.
*/
@Module
@InstallIn(SingletonComponent::class)
@@ -30,7 +29,7 @@ abstract class RepositoryModule {
// [ENTITY: Function('bindItemRepository')]
// [RELATION: Function('bindItemRepository')] -> [PROVIDES] -> [Interface('ItemRepository')]
/**
* @summary Связывает интерфейс ItemRepository с его реализацией.
* @summary Binds the ItemRepository interface to its implementation.
*/
@Binds
@Singleton
@@ -42,7 +41,7 @@ abstract class RepositoryModule {
// [ENTITY: Function('bindCredentialsRepository')]
// [RELATION: Function('bindCredentialsRepository')] -> [PROVIDES] -> [Interface('CredentialsRepository')]
/**
* @summary Связывает интерфейс CredentialsRepository с его реализацией.
* @summary Binds the CredentialsRepository interface to its implementation.
*/
@Binds
@Singleton
@@ -54,7 +53,7 @@ abstract class RepositoryModule {
// [ENTITY: Function('bindAuthRepository')]
// [RELATION: Function('bindAuthRepository')] -> [PROVIDES] -> [Interface('AuthRepository')]
/**
* @summary Связывает интерфейс AuthRepository с его реализацией.
* @summary Binds the AuthRepository interface to its implementation.
*/
@Binds
@Singleton

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.di
// [FILE] StorageModule.kt
// [SEMANTICS] di, hilt, storage
// [SEMANTICS] data, di, storage
package com.homebox.lens.data.di
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.mapper
// [FILE] DomainToDto.kt
// [SEMANTICS] data, mapper, domain, dto
// [SEMANTICS] data, mapper
package com.homebox.lens.data.mapper
// [IMPORTS]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.mapper
// [FILE] DtoToDomain.kt
// [SEMANTICS] data, mapper, dto, domain
// [SEMANTICS] data, mapper
package com.homebox.lens.data.mapper
// [IMPORTS]
@@ -20,6 +19,7 @@ import com.homebox.lens.domain.model.LocationOut as DomainLocationOut
import com.homebox.lens.domain.model.LocationOutCount as DomainLocationOutCount
import com.homebox.lens.domain.model.MaintenanceEntry as DomainMaintenanceEntry
import com.homebox.lens.domain.model.PaginationResult as DomainPaginationResult
import com.homebox.lens.domain.model.TokenResponse as DomainTokenResponse
// [END_IMPORTS]
// [ENTITY: Function('ItemOutDto.toDomain')]
@@ -103,10 +103,10 @@ fun ItemSummaryDto.toDomain(): DomainItemSummary {
name = this.name,
assetId = this.assetId,
image = this.image?.toDomain(),
isArchived = this.isArchived,
isArchived = this.isArchived ?: false,
labels = this.labels.map { it.toDomain() },
location = this.location?.toDomain(),
value = this.value,
value = this.value ?: 0.0,
createdAt = this.createdAt,
updatedAt = this.updatedAt
)
@@ -133,6 +133,13 @@ fun LabelOutDto.toDomainLabel(): DomainLabel {
name = this.name
)
}
fun com.homebox.lens.domain.model.LabelOut.toDomain(): DomainLabel {
return DomainLabel(
id = this.id,
name = this.name
)
}
// [END_ENTITY: Function('LabelOutDto.toDomain')]
// [ENTITY: Function('LocationOutDto.toDomain')]
@@ -258,4 +265,5 @@ fun LabelSummaryDto.toDomain(): DomainLabelSummary {
}
// [END_ENTITY: Function('LabelSummaryDto.toDomain')]
// [END_FILE_DtoToDomain.kt]

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.repository
// [FILE] AuthRepositoryImpl.kt
// [SEMANTICS] data_implementation, authentication, repository
// [SEMANTICS] data, repository, authentication
package com.homebox.lens.data.repository
@@ -8,8 +7,9 @@ package com.homebox.lens.data.repository
import android.content.SharedPreferences
import com.homebox.lens.data.api.HomeboxApiService
import com.homebox.lens.data.api.dto.LoginFormDto
import com.homebox.lens.data.api.mapper.toDomain
import com.homebox.lens.data.api.dto.toDomain
import com.homebox.lens.domain.model.Credentials
import com.homebox.lens.domain.model.Result
import com.homebox.lens.domain.model.TokenResponse
import com.homebox.lens.domain.repository.AuthRepository
import kotlinx.coroutines.Dispatchers
@@ -30,10 +30,10 @@ import javax.inject.Inject
// [RELATION: Class('AuthRepositoryImpl')] -> [DEPENDS_ON] -> [Framework('OkHttpClient')]
// [RELATION: Class('AuthRepositoryImpl')] -> [DEPENDS_ON] -> [Framework('MoshiConverterFactory')]
/**
* @summary Реализация репозитория для управления аутентификацией.
* @param encryptedPrefs Защищенное хранилище для токена.
* @param okHttpClient Общий OkHttp клиент для переиспользования.
* @param moshiConverterFactory Общий конвертер Moshi для переиспользования.
* @summary Implementation of the repository for managing authentication.
* @param encryptedPrefs The secure storage for the token.
* @param okHttpClient The shared OkHttp client for reuse.
* @param moshiConverterFactory The shared Moshi converter for reuse.
*/
class AuthRepositoryImpl @Inject constructor(
private val encryptedPrefs: SharedPreferences,
@@ -47,16 +47,16 @@ class AuthRepositoryImpl @Inject constructor(
// [ENTITY: Function('login')]
/**
* @summary Реализует вход пользователя. Создает временный API сервис для выполнения запроса
* на указанный пользователем URL сервера.
* @param credentials Учетные данные пользователя, включая URL сервера.
* @return [Result] с доменной моделью [TokenResponse] при успехе или [Exception] при ошибке.
* @summary Implements user login. Creates a temporary API service to execute a request
* to the server URL specified by the user.
* @param credentials The user's credentials, including the server URL.
* @return A [Result] with a [TokenResponse] domain model on success or an [Exception] on failure.
*/
override suspend fun login(credentials: Credentials): Result<TokenResponse> {
require(credentials.serverUrl.isNotBlank()) { "Server URL cannot be blank." }
return withContext(Dispatchers.IO) {
runCatching {
try {
Timber.d("[DEBUG][ACTION][creating_retrofit_client] Creating temporary Retrofit client for URL: ${credentials.serverUrl}")
val tempApiService = Retrofit.Builder()
.baseUrl(credentials.serverUrl)
@@ -70,7 +70,10 @@ class AuthRepositoryImpl @Inject constructor(
val tokenResponseDto = tempApiService.login(loginForm)
Timber.d("[DEBUG][ACTION][mapping_to_domain] Mapping token response to domain model.")
tokenResponseDto.toDomain()
Result.Success(tokenResponseDto.toDomain())
} catch (e: Exception) {
Timber.e(e, "[ERROR][FAILURE][login_failed] Login failed.")
Result.Error(e)
}
}
}

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.repository
// [FILE] CredentialsRepositoryImpl.kt
// [SEMANTICS] data, repository, credentials, security
package com.homebox.lens.data.repository
@@ -20,10 +19,10 @@ import javax.inject.Inject
// [RELATION: Class('CredentialsRepositoryImpl')] -> [IMPLEMENTS] -> [Interface('CredentialsRepository')]
// [RELATION: Class('CredentialsRepositoryImpl')] -> [DEPENDS_ON] -> [Framework('SharedPreferences')]
/**
* @summary Реализует репозиторий для управления учетными данными пользователя.
* @description Взаимодействует с зашифрованными SharedPreferences для сохранения и извлечения данных.
* @param encryptedPrefs Зашифрованное хранилище ключ-значение, предоставляемое Hilt.
* @invariant Состояние этого репозитория полностью зависит от содержимого `encryptedPrefs`.
* @summary Implements the repository for managing user credentials.
* @description Interacts with encrypted SharedPreferences to save and retrieve data.
* @param encryptedPrefs The encrypted key-value store provided by Hilt.
* @invariant The state of this repository is entirely dependent on the contents of `encryptedPrefs`.
*/
class CredentialsRepositoryImpl @Inject constructor(
private val encryptedPrefs: SharedPreferences
@@ -38,9 +37,9 @@ class CredentialsRepositoryImpl @Inject constructor(
// [ENTITY: Function('saveCredentials')]
/**
* @summary Сохраняет основные учетные данные пользователя.
* @param credentials Объект с учетными данными для сохранения.
* @sideeffect Перезаписывает существующие учетные данные в SharedPreferences.
* @summary Saves the user's primary credentials.
* @param credentials The credentials object to save.
* @sideeffect Overwrites existing credentials in SharedPreferences.
*/
override suspend fun saveCredentials(credentials: Credentials) {
withContext(Dispatchers.IO) {
@@ -56,8 +55,8 @@ class CredentialsRepositoryImpl @Inject constructor(
// [ENTITY: Function('getCredentials')]
/**
* @summary Извлекает сохраненные учетные данные пользователя в виде потока.
* @return Flow, который эммитит объект [Credentials] или null, если данные отсутствуют.
* @summary Retrieves the saved user credentials as a Flow.
* @return A Flow that emits a [Credentials] object or null if no data is present.
*/
override fun getCredentials(): Flow<Credentials?> = flow {
Timber.d("[DEBUG][ACTION][getting_credentials] Getting user credentials.")
@@ -77,9 +76,9 @@ class CredentialsRepositoryImpl @Inject constructor(
// [ENTITY: Function('saveToken')]
/**
* @summary Сохраняет токен авторизации.
* @param token Токен для сохранения.
* @sideeffect Перезаписывает существующий токен в SharedPreferences.
* @summary Saves the authorization token.
* @param token The token to save.
* @sideeffect Overwrites the existing token in SharedPreferences.
*/
override suspend fun saveToken(token: String) {
withContext(Dispatchers.IO) {
@@ -93,8 +92,8 @@ class CredentialsRepositoryImpl @Inject constructor(
// [ENTITY: Function('getToken')]
/**
* @summary Извлекает сохраненный токен авторизации.
* @return Строка с токеном или null, если он не найден.
* @summary Retrieves the saved authorization token.
* @return A string with the token or null if it is not found.
*/
override suspend fun getToken(): String? {
return withContext(Dispatchers.IO) {
@@ -111,8 +110,8 @@ class CredentialsRepositoryImpl @Inject constructor(
// [ENTITY: Function('clearAllCredentials')]
/**
* @summary Очищает все сохраненные учетные данные и токены.
* @sideeffect Удаляет все записи, связанные с учетными данными, из SharedPreferences.
* @summary Clears all saved credentials and tokens.
* @sideeffect Removes all records related to credentials from SharedPreferences.
*/
override suspend fun clearAllCredentials() {
withContext(Dispatchers.IO) {

View File

@@ -1,4 +1,3 @@
// [PACKAGE] com.homebox.lens.data.repository
// [FILE] EncryptedPreferencesWrapper.kt
// [SEMANTICS] data, security, preferences
package com.homebox.lens.data.repository

View File

@@ -1,6 +1,5 @@
// [PACKAGE] com.homebox.lens.data.repository
// [FILE] ItemRepositoryImpl.kt
// [SEMANTICS] data_repository, implementation, items, labels
// [SEMANTICS] data, repository, item
package com.homebox.lens.data.repository
// [IMPORTS]

Some files were not shown because too many files have changed in this diff Show More