Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Plugin.Abstractions (IPlugin, IWorklogUploadPlugin, IWorkSuggestionPlugin, IStat
```

**Key layers:**
- **Domain** — Pure business rules, no dependencies. Defines `IWorkEntryRepository`.
- **Domain** — Pure business rules, no dependencies. Defines `IWorkEntryReader` and `IWorkEntryRepository`.
- **Application** — Orchestrates use cases. Uses `Result<T>` for error handling (no exceptions for business logic). Registers services via `DependencyInjection.AddApplication()`.
- **Infrastructure** — EF Core/SQLite, `PluginManager`, repository implementations. Registers everything via `DependencyInjection.AddInfrastructure()` (which calls `AddApplication()` internally).
- **Presentation** — Avalonia (cross-platform GUI: views, ViewModels on CommunityToolkit.Mvvm, Orchestrators that coordinate services, `ILocalizationService`, `ISettingsService`) and CLI (Spectre.Console, goes straight to Application). Each has its own DI setup in `Program.cs` / `App.axaml.cs`.
Expand Down Expand Up @@ -79,7 +79,7 @@ Existing plugins: `Plugin.Atlassian` (Tempo + Jira), `Plugin.Office365Calendar`,
- **ViewModels stay free of the UI framework** — `ViewModels/`, `Orchestrators/`, `Models/` and `Helpers/` in the Avalonia project don't use Avalonia or `App` (checked by `WorkTracker.Architecture.Tests`), so they can be tested without a UI. Threads go through `IUiDispatcher`, colors through styles.
- **DI registration** is centralized: `Application/DependencyInjection.cs` and `Infrastructure/DependencyInjection.cs`; orchestrators and some services register through `AddPresentationServices()` in `Avalonia/PresentationServices.cs`, the rest and all platform services in `App.ConfigureAppServices`. Infrastructure's `AddInfrastructure()` is the single entry point for non-UI services.
- **Database** uses `IDbContextFactory<WorkTrackerDbContext>` (not scoped DbContext). SQLite stored in `%LocalAppData%\WorkTracker\` (Debug builds: `worktracker-dev.db` next to the binary).
- **Unit of Work** (`IUnitOfWork` / `IUnitOfWorkFactory` in `Application/Interfaces/`) wraps every write of `WorkEntryService` and the checks it depends on in an explicit `IDbContextTransaction`, which takes the SQLite write lock up front so the GUI and the CLI can't both pass a check. `IUnitOfWorkFactory.CreateAsync` opens the transaction; `IUnitOfWork.SaveChangesAsync` flushes changes and commits; disposing without calling `SaveChangesAsync` triggers a transaction rollback. `WorkEntryRepository` has two modes: factory mode (standalone, each op auto-saves) and shared-context mode (inside UoW, SaveChanges deferred to the UoW). Only reads use the transient repository directly. Before pending migrations run, `DatabaseMigrationBackup` copies the database next to itself; migrations must cope with existing rows that today's rules wouldn't let in, and any that touch data get a case in `ExistingDatabaseMigrationTests`.
- **Unit of Work** (`IUnitOfWork` / `IUnitOfWorkFactory` in `Application/Interfaces/`) wraps every write of `WorkEntryService` and the checks it depends on in an explicit `IDbContextTransaction`, which takes the SQLite write lock up front so the GUI and the CLI can't both pass a check. `IUnitOfWorkFactory.CreateAsync` opens the transaction; `IUnitOfWork.SaveChangesAsync` flushes changes and commits; disposing without calling `SaveChangesAsync` triggers a transaction rollback. `IWorkEntryRepository` exists only inside a UoW, which owns its context and the commit. Reads outside of one go through the transient `IWorkEntryReader`, each opening its own context. Before pending migrations run, `DatabaseMigrationBackup` copies the database next to itself; migrations must cope with existing rows that today's rules wouldn't let in, and any that touch data get a case in `ExistingDatabaseMigrationTests`.
- **Secure storage** for API tokens via `ISecureStorage` (OS credential manager).

## CI/CD
Expand Down
17 changes: 6 additions & 11 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ Pokud tě zajímá **jak napsat vlastní plugin**, jdi rovnou na [plugin-develop
┌─────────────────────────────▼───────────────────────────────────────┐
│ Domain │
│ - WorkEntry (entity) │
│ - IWorkEntryRepository (interface) │
│ - IWorkEntryReader, IWorkEntryRepository (interface) │
│ - Business pravidla (validace časů, plán řešení překryvů) │
│ - Žádné závislosti navenek │
└─────────────────────────────┬───────────────────────────────────────┘
│ implementováno v
┌─────────────────────────────▼───────────────────────────────────────┐
│ Infrastructure │
│ - WorkTrackerDbContext (EF Core + SQLite) │
│ - WorkEntryRepository, UnitOfWork, UnitOfWorkFactory │
│ - WorkEntryReader, WorkEntryRepository, UnitOfWork(Factory) │
│ - CredentialStoreSecureStorage (GitCredentialManager) │
│ - PluginManager, PluginLoader, PluginLoadContext (ALC) │
│ - MsalTokenProvider, MsalTokenProviderFactory │
Expand Down Expand Up @@ -91,7 +91,7 @@ Stejně na Abstractions závisí i Plugin.StreamDeck.
Čistý business model bez jakýchkoli externích závislostí. Obsahuje:

- **`WorkEntry`** — agregát (`TicketId`, `StartTime`/`EndTime`, `Description`, `IsActive`). Settery jsou privátní, záznam vzniká přes `WorkEntry.Create(...)` a mění se přes metody (`Stop`, …).
- **`IWorkEntryRepository`** — interface pro persistenci, implementace je v Infrastructure.
- **`IWorkEntryReader`, `IWorkEntryRepository`** — interface pro čtení a pro zápisy v rámci Unit of Work, implementace jsou v Infrastructure.
- **Business pravidla** — `WorkEntry.IsValid()` (ticket nebo popis je povinný, konec nesmí být před začátkem) a `OverlapResolver`, který spočítá plán úprav kolidujících záznamů (`OverlapResolutionPlan`). Samotnou kontrolu překryvů proti databázi dělá `WorkEntryService` přes repository.

Domain layer **nezná** EF Core, plugins, DI, UI, nic. Je možné ji izolovaně unit‑testovat bez mockování.
Expand Down Expand Up @@ -120,7 +120,7 @@ Registrace služeb: `DependencyInjection.AddApplication(IServiceCollection)`. Vo
Implementace externích závislostí:

- **EF Core + SQLite** — `WorkTrackerDbContext`, `WorkEntryRepository`, `UnitOfWork`, `UnitOfWorkFactory`. Cesta k databázi se řídí `WorkTrackerPaths.DefaultDatabasePath` s možností přepsání přes `Database:Path` v configu (relativní cesty se vyhodnocují vůči `WorkTrackerPaths.WritableBaseDirectory` — adresáři aplikace, uvnitř macOS `.app` bundlu vůči `~/Library/Application Support/WorkTracker/`). `Database:Pooling` (default `true`) vypíná connection pooling pro databáze na removable médiích — bez poolingu se soubor zavírá po každé operaci a disk jde bezpečně vysunout. Při startu se vynucuje `PRAGMA journal_mode=DELETE` (WAL je na removable exFAT rizikový kvůli `-wal`/`-shm` souborům). Když databáze není dosažitelná (nepřipojený disk, IO chyba, read-only médium), `AddInfrastructure` i `InitializeDatabaseAsync` vyhodí `DatabaseUnavailableException` — Avalonia `App` na ni reaguje dialogem s tlačítkem *Zkusit znovu*, které zopakuje celý bootstrap; ostatní výjimky při startu jsou brány jako neopravitelné. Před čekající migrací se databáze zkopíruje vedle sebe (`DatabaseMigrationBackup`), a když se to nepovede, migrace neběží (`DatabaseBackupFailedException`).
- **`IDbContextFactory<WorkTrackerDbContext>`** — `WorkEntryRepository` ho používá místo scoped `DbContext`. Důvod: dlouho běžící služby (GUI) nemají HTTP request scope, takže scoped DbContext by vedl k leakům a concurrent‑use chybám.
- **`IDbContextFactory<WorkTrackerDbContext>`** — `WorkEntryReader` a `UnitOfWorkFactory` ho používají místo scoped `DbContext`. Důvod: dlouho běžící služby (GUI) nemají HTTP request scope, takže scoped DbContext by vedl k leakům a concurrent‑use chybám.
- **`CredentialStoreSecureStorage`** — implementace `ISecureStorage` nad `GitCredentialManager` (multiplatformní: Windows Credential Manager, macOS Keychain, Linux libsecret).
- **`PluginManager`, `PluginLoader`, `PluginLoadContext`** — načítání pluginů do vlastního `AssemblyLoadContext` (collectible) pro každou plugin assembly; všechny pluginy sdílejí jeden plugin `ServiceProvider`.
- **`MsalTokenProviderFactory`, `MsalTokenProvider`** — MSAL Public Client s cross‑platform token cache (`Microsoft.Identity.Client.Extensions.Msal`) a dvěma způsoby interaktivní autentizace podle `InteractiveAuthFlow`, který plugin zvolí: **device code flow** a **authorization code flow s PKCE** v systémovém prohlížeči (redirect na vlastní loopback listener `SystemBrowserWebUi`).
Expand Down Expand Up @@ -173,7 +173,7 @@ Presentation ──> Infrastructure (bootstrap: AddInfrastructure, InitializeD

Praktické důsledky:

- **Application nezná EF Core.** `WorkEntryService` používá `IWorkEntryRepository`, ne `DbContext`.
- **Application nezná EF Core.** `WorkEntryService` používá `IWorkEntryReader` a `IWorkEntryRepository`, ne `DbContext`.
- **Presentation nezná implementace pluginů.** Komunikuje přes `IWorklogSubmissionService`, `IPluginManager` (Application interfaces) a pracuje jen s typy z Plugin.Abstractions (`WorklogSubmissionMode`, `PluginConfigurationField`, …).
- **Plugin.Abstractions je samostatný nuget‑like projekt**, aby externí pluginy nemusely referencovat celé Application.

Expand Down Expand Up @@ -322,12 +322,7 @@ await uow.WorkEntries.UpdateAsync(trimmedOldEntry, ct);
await uow.SaveChangesAsync(ct); // commit
```

Pokud `SaveChangesAsync` není zavoláno a `uow` se dispose‑ne, transakce se rollbackne. `WorkEntryRepository` má dva režimy:

- **Factory režim** (standalone) — každá operace si sama otevře `DbContext` z factory a rovnou commituje.
- **Shared‑context režim** (v rámci UoW) — operace přispívají do `DbContext` drženého UoW, SaveChanges je odložen na UoW.

`WorkEntryService` používá transient repository přímo jen pro čtení.
Pokud `SaveChangesAsync` není zavoláno a `uow` se dispose‑ne, transakce se rollbackne. `WorkEntryRepository` pracuje na `DbContext` drženém UoW a SaveChanges nechává na něm. Mimo UoW se jen čte, přes `WorkEntryReader`, kde si každá operace sama otevře `DbContext` z factory.

### Factory místo scoped DbContext

Expand Down
4 changes: 2 additions & 2 deletions docs/developer-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ if (result.IsFailure) return result;
### Async

- I/O metody jsou async (`Task<T>` nebo `ValueTask<T>`). Výjimkou jsou například `ISecureStorage`, synchronní varianty v `SettingsService`, `AutostartManager` a rané čtení `settings.json` v `App`.
- `CancellationToken` jako **poslední parametr**. V novém kódu bez default value (`= default`), pokud nemá volající opravdu co předat. Starší API (`IWorkEntryRepository`, `IWorkEntryService`, část Plugin.Abstractions) ho zatím mají.
- `CancellationToken` jako **poslední parametr**. V novém kódu bez default value (`= default`), pokud nemá volající opravdu co předat. Starší API (`IWorkEntryService`, část Plugin.Abstractions) ho zatím mají.
- Pojmenování: metoda končí `Async`.

### Error handling
Expand Down Expand Up @@ -357,7 +357,7 @@ Pokud UoW dispose‑uješ bez `SaveChangesAsync`, transakce se **rollbackne**.

### Single‑operation: bez UoW

Pro jednoduché CRUD operace se UoW nepoužívá. `WorkEntryService` dostane injekovanou transient `IWorkEntryRepository` (factory režim, auto‑save po každé operaci) a rovnou ji volá.
Pro čtení se UoW nepoužívá: `WorkEntryService` dostane injekovaný transient `IWorkEntryReader`, kde si každé čtení otevře vlastní `DbContext`. `IWorkEntryRepository` je jen v UoW a jeho zápisy se projeví až po `SaveChangesAsync`.

---

Expand Down
26 changes: 13 additions & 13 deletions src/WorkTracker.Application/Services/WorkEntryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ namespace WorkTracker.Application.Services;
/// <remarks>
/// Every write runs in a unit of work, together with the checks it depends on. Those transactions take
/// the write lock of the database up front, so the GUI and the CLI can't both pass a check and then both
/// write. Only reads use the repository directly.
/// write.
/// </remarks>
public sealed class WorkEntryService : IWorkEntryService
{
private readonly IWorkEntryRepository _repository;
private readonly IWorkEntryReader _reader;
private readonly IUnitOfWorkFactory _unitOfWorkFactory;
private readonly TimeProvider _timeProvider;
private readonly ILogger<WorkEntryService> _logger;

public WorkEntryService(IWorkEntryRepository repository, IUnitOfWorkFactory unitOfWorkFactory, TimeProvider timeProvider, ILogger<WorkEntryService> logger)
public WorkEntryService(IWorkEntryReader reader, IUnitOfWorkFactory unitOfWorkFactory, TimeProvider timeProvider, ILogger<WorkEntryService> logger)
{
_repository = repository;
_reader = reader;
_unitOfWorkFactory = unitOfWorkFactory;
_timeProvider = timeProvider;
_logger = logger;
Expand Down Expand Up @@ -143,17 +143,17 @@ public async Task<Result<WorkEntry>> StopWorkAsync(DateTime? endTime = null, Can

public async Task<WorkEntry?> GetActiveWorkAsync(CancellationToken cancellationToken)
{
return await _repository.GetActiveWorkEntryAsync(cancellationToken);
return await _reader.GetActiveWorkEntryAsync(cancellationToken);
}

public async Task<WorkEntry?> GetWorkEntryByIdAsync(int id, CancellationToken cancellationToken)
{
return await _repository.GetByIdAsync(id, cancellationToken);
return await _reader.GetByIdAsync(id, cancellationToken);
}

public async Task<IEnumerable<WorkEntry>> GetWorkEntriesByDateAsync(DateTime date, CancellationToken cancellationToken)
{
return await _repository.GetByDateAsync(date, cancellationToken);
return await _reader.GetByDateAsync(date, cancellationToken);
}

public Task<Result<WorkEntry>> UpdateWorkEntryAsync(int id, string? ticketId, DateTime startTime, DateTime? endTime, string? description, CancellationToken cancellationToken)
Expand Down Expand Up @@ -257,22 +257,22 @@ public async Task<Result> DeleteWorkEntryAsync(int id, CancellationToken cancell

public async Task<IEnumerable<WorkEntry>> GetWorkEntriesByDateRangeAsync(DateTime startDate, DateTime endDate, CancellationToken cancellationToken)
{
return await _repository.GetByDateRangeAsync(startDate, endDate, cancellationToken);
return await _reader.GetByDateRangeAsync(startDate, endDate, cancellationToken);
}

public Task<OverlapResolutionPlan> ComputeOverlapResolutionAsync(int? excludeEntryId, DateTime startTime, DateTime? endTime, CancellationToken cancellationToken)
{
return BuildOverlapPlanAsync(_repository, excludeEntryId, DateTimeHelper.RoundToMinute(startTime), DateTimeHelper.RoundToMinute(endTime), cancellationToken);
return BuildOverlapPlanAsync(_reader, excludeEntryId, DateTimeHelper.RoundToMinute(startTime), DateTimeHelper.RoundToMinute(endTime), cancellationToken);
}

private static async Task<OverlapResolutionPlan> BuildOverlapPlanAsync(IWorkEntryRepository repository, int? excludeEntryId, DateTime roundedStart, DateTime? roundedEnd, CancellationToken cancellationToken)
private static async Task<OverlapResolutionPlan> BuildOverlapPlanAsync(IWorkEntryReader reader, int? excludeEntryId, DateTime roundedStart, DateTime? roundedEnd, CancellationToken cancellationToken)
{
// For the query: when endTime is null (active/ongoing entry), use +1 minute
// to detect overlaps at the exact start time (predicate uses StartTime < end)
// while avoiding matching all future entries
var queryEnd = roundedEnd ?? roundedStart.AddMinutes(1);

var overlapping = await repository.GetOverlappingEntriesAsync(excludeEntryId, roundedStart, queryEnd, cancellationToken);
var overlapping = await reader.GetOverlappingEntriesAsync(excludeEntryId, roundedStart, queryEnd, cancellationToken);

if (overlapping.Count == 0)
{
Expand All @@ -292,9 +292,9 @@ private static async Task<OverlapResolutionPlan> BuildOverlapPlanAsync(IWorkEntr
/// open: the CLI, a remote controller or the Pomodoro timer don't wait for the dialog. Applying it
/// then would delete or trim entries by what they used to be, so the transaction checks it first.
/// </summary>
private async Task<bool> IsPlanStillValidAsync(IWorkEntryRepository repository, OverlapResolutionPlan plan, int? excludeEntryId, DateTime roundedStart, DateTime? roundedEnd, CancellationToken cancellationToken)
private async Task<bool> IsPlanStillValidAsync(IWorkEntryReader reader, OverlapResolutionPlan plan, int? excludeEntryId, DateTime roundedStart, DateTime? roundedEnd, CancellationToken cancellationToken)
{
var currentPlan = await BuildOverlapPlanAsync(repository, excludeEntryId, roundedStart, roundedEnd, cancellationToken);
var currentPlan = await BuildOverlapPlanAsync(reader, excludeEntryId, roundedStart, roundedEnd, cancellationToken);
if (currentPlan.Adjustments.SequenceEqual(plan.Adjustments))
{
return true;
Expand Down
20 changes: 20 additions & 0 deletions src/WorkTracker.Domain/Interfaces/IWorkEntryReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using WorkTracker.Domain.Entities;

namespace WorkTracker.Domain.Interfaces;

/// <summary>
/// Reads work entries as they are stored at that moment. Anything that decides on a write reads through
/// the <see cref="IWorkEntryRepository"/> of its unit of work instead, where nothing can change in between.
/// </summary>
public interface IWorkEntryReader
{
Task<WorkEntry?> GetByIdAsync(int id, CancellationToken cancellationToken);

Task<WorkEntry?> GetActiveWorkEntryAsync(CancellationToken cancellationToken);

Task<IEnumerable<WorkEntry>> GetByDateAsync(DateTime date, CancellationToken cancellationToken);

Task<IEnumerable<WorkEntry>> GetByDateRangeAsync(DateTime startDate, DateTime endDate, CancellationToken cancellationToken);

Task<IReadOnlyList<WorkEntry>> GetOverlappingEntriesAsync(int? excludeEntryId, DateTime startTime, DateTime? endTime, CancellationToken cancellationToken);
}
Loading
Loading