From 0d6160ceac0bdb967c7867a3e5c98c89801d7f26 Mon Sep 17 00:00:00 2001 From: DidoraRudenko Date: Mon, 23 Nov 2026 14:51:20 +0200 Subject: [PATCH] feat(desktop): add interview preparation tab, fix installer runtime dependencies, and add CI artifact build --- .github/workflows/desktop-release.yml | 13 + README.md | 64 +- apps/desktop/CMakeLists.txt | 13 + .../include/models/PreparationModels.hpp | 42 ++ .../services/DemoPreparationService.hpp | 63 ++ .../include/services/IPreparationService.hpp | 22 + .../viewmodels/NavigationViewModel.hpp | 4 +- .../viewmodels/PreparationViewModel.hpp | 121 ++++ apps/desktop/qml/Main.qml | 13 +- apps/desktop/qml/components/Sidebar.qml | 11 + apps/desktop/qml/views/PreparationView.qml | 644 ++++++++++++++++++ apps/desktop/src/main.cpp | 25 + .../src/services/DemoPreparationService.cpp | 602 ++++++++++++++++ .../src/viewmodels/NavigationViewModel.cpp | 4 + .../src/viewmodels/PreparationViewModel.cpp | 237 +++++++ .../src/viewmodels/ReportViewModel.cpp | 17 + apps/desktop/tests/main.cpp | 7 +- apps/desktop/tests/unit/TestPreparation.cpp | 352 ++++++++++ installer/dev-dialogue.iss | 2 +- scripts/package-desktop.ps1 | 62 +- 20 files changed, 2282 insertions(+), 36 deletions(-) create mode 100644 apps/desktop/include/models/PreparationModels.hpp create mode 100644 apps/desktop/include/services/DemoPreparationService.hpp create mode 100644 apps/desktop/include/services/IPreparationService.hpp create mode 100644 apps/desktop/include/viewmodels/PreparationViewModel.hpp create mode 100644 apps/desktop/qml/views/PreparationView.qml create mode 100644 apps/desktop/src/services/DemoPreparationService.cpp create mode 100644 apps/desktop/src/viewmodels/PreparationViewModel.cpp create mode 100644 apps/desktop/tests/unit/TestPreparation.cpp diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 5e1a1d9..e934093 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -3,6 +3,8 @@ name: Desktop Installer Release (main) on: push: branches: [main] + pull_request: + branches: [main] workflow_dispatch: permissions: @@ -49,7 +51,18 @@ jobs: $ver = "1.0.$env:GITHUB_RUN_NUMBER" & .\scripts\package-desktop.ps1 -Configuration Release -AppVersion $ver -ReleaseTag latest + - name: Upload Installer Artifact + uses: actions/upload-artifact@v4 + with: + name: DevDialogue-Setup-x64 + path: | + dist/DevDialogue-Setup-*.exe + dist/DevDialogue-Bootstrap-*-x64.exe + dist/latest.json + if-no-files-found: error + - name: Publish Release to GitHub Releases (tag: latest) + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' uses: softprops/action-gh-release@v2 with: tag_name: latest diff --git a/README.md b/README.md index 1a0cc18..1e767cf 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ An interactive technical, behavioral, and language interview simulation platform | :------------------- | :--------------------------------------- | :------------------------------------------------------------------------------ | | **Monorepo** | **Turborepo** + **pnpm v12** | Fast caching, script orchestration, and workspace isolation | | **Frontend** | **Next.js 14** (App Router) + TypeScript | Responsive UI, interactive chat room, scorecard dashboard | -| **Design System** | **Tailwind CSS** + **Geist Font** | High-craft UI based on David Sanders Taste & Anthropic Frontend standards | +| **Desktop Client** | **Qt 6 (QML)** + **C++20** | Native high-performance client, offline AI engine, 3D avatar, DirectShow webcam | +| **Design System** | **Tailwind CSS** / **Geist Design** | High-craft UI based on David Sanders Taste & Anthropic Frontend standards | | **State Management** | **Zustand** | Session persistence, client tokens, and instantaneous Admin/User mode toggle | | **Backend** | **ASP.NET Core (.NET 9)** + C# | High-performance REST API, session state machine, rate limits, security | | **Database & Auth** | **Supabase** (PostgreSQL 16 + JWT) | Relational storage for users, question banks, and JSONB transcripts | @@ -37,12 +38,17 @@ dev-dialogue/ │ │ ├── src/components/ # UI components (Navbar, ChatRoom, PerformanceReport, etc.) │ │ ├── src/lib/ # Typed API client, Supabase client, utilities │ │ └── src/store/ # Zustand auth & dynamic view-mode store -│ └── api/ # ASP.NET Core Web API -│ ├── Controllers/ # Auth, Interviews, AdminQuestions, Health -│ ├── Data/ # AppDbContext (PostgreSQL / In-Memory fallback) -│ ├── Models/ # Entities (User, Interview, QuestionBank) & DTOs -│ ├── Security/ # JWT validation & [RequireRole("admin")] attribute -│ └── Services/AI/ # IAiService (MockAiService + CloudAiService) +│ ├── api/ # ASP.NET Core Web API +│ │ ├── Controllers/ # Auth, Interviews, AdminQuestions, Health +│ │ ├── Data/ # AppDbContext (PostgreSQL / In-Memory fallback) +│ │ ├── Models/ # Entities (User, Interview, QuestionBank) & DTOs +│ │ ├── Security/ # JWT validation & [RequireRole("admin")] attribute +│ │ └── Services/AI/ # IAiService (MockAiService + CloudAiService) +│ └── desktop/ # Native Qt 6 / C++20 desktop client (Offline & i18n) +│ ├── include/ # Models, Services, ViewModels +│ ├── src/ # Implementation files +│ ├── qml/ # Views, Styles, Components (Geist UI) +│ └── tests/ # GoogleTest & Qt Test suite │ ├── packages/ │ └── api-contracts/ # Shared TypeScript interfaces & DTO contracts @@ -56,6 +62,18 @@ dev-dialogue/ --- +### 💻 Desktop Client & Windows Installer + +For desktop users, pre-built standalone Windows installers are distributed directly via **GitHub Releases** and **Pull Request Artifacts** — **no terminal commands, SDKs, or manual building required**: + +- **Latest Windows Installer:** [Download `DevDialogue-Setup-x64.exe`](https://github.com/iberikofer/dev-dialogue/releases/latest) +- **Online Bootstrapper (2 MB):** [Download `DevDialogue-Bootstrap-x64.exe`](https://github.com/iberikofer/dev-dialogue/releases/latest) +- **Pull Request Builds:** Download the ready-to-test installer artifact directly from the **Summary → Artifacts** tab of any Pull Request. + +Simply double-click the `.exe` installer. It sets up shortcuts in the Start Menu and Desktop, bundled with the Qt 6 runtime, DirectShow webcam, Speech-to-Text, and the **Interview Preparation** («Підготовка до співбесід») module. + +--- + ### 🛠 Quick Start for Development #### 1. Install Dependencies @@ -143,7 +161,8 @@ The AI subsystem is engineered for zero-dependency offline prototyping and seaml | :------------------- | :------------------------------------------- | :-------------------------------------------------------------------- | | **Монорепозиторій** | **Turborepo** + **pnpm v12** | Кешування, оркестрація збірок, лінтингу та воркспейсів | | **Frontend** | **Next.js 14** (App Router) + TypeScript | Користувацький інтерфейс, інтерактивний чат, дашборд | -| **Дизайн-система** | **Tailwind CSS** + **Шрифт Geist** | High-craft дизайн на базі стандартів David Sanders Taste та Anthropic | +| **Десктоп-клієнт** | **Qt 6 (QML)** + **C++20** | Нативний застосунок, офлайн AI-рушій, 3D-аватар, DirectShow веб-камера | +| **Дизайн-система** | **Tailwind CSS** / **Geist Design** | High-craft дизайн на базі стандартів David Sanders Taste та Anthropic | | **State Management** | **Zustand** | Стан сесії, збереження токенів, миттєвий перемикач режимів адміна | | **Backend** | **ASP.NET Core (.NET 9)** + C# | REST API, життєвий цикл сесій, ліміти, рольова безпека | | **Database & Auth** | **Supabase** (PostgreSQL 16 + JWT) | Збереження користувачів, банку питань, транскриптів (JSONB) | @@ -163,12 +182,17 @@ dev-dialogue/ │ │ ├── src/components/ # UI компоненти (Navbar, ChatRoom, PerformanceReport, тощо) │ │ ├── src/lib/ # Typed API client, Supabase клієнт, утиліти │ │ └── src/store/ # Zustand auth & view-mode store -│ └── api/ # ASP.NET Core Web API -│ ├── Controllers/ # Auth, Interviews, AdminQuestions, Health -│ ├── Data/ # AppDbContext (PostgreSQL / In-Memory fallback) -│ ├── Models/ # Entities (User, Interview, QuestionBank) & DTOs -│ ├── Security/ # JWT валідація, [RequireRole("admin")] атрибут -│ └── Services/AI/ # IAiService (MockAiService + CloudAiService) +│ ├── api/ # ASP.NET Core Web API +│ │ ├── Controllers/ # Auth, Interviews, AdminQuestions, Health +│ │ ├── Data/ # AppDbContext (PostgreSQL / In-Memory fallback) +│ │ ├── Models/ # Entities (User, Interview, QuestionBank) & DTOs +│ │ ├── Security/ # JWT валідація, [RequireRole("admin")] атрибут +│ │ └── Services/AI/ # IAiService (MockAiService + CloudAiService) +│ └── desktop/ # Нативний клієнт Qt 6 / C++20 (Офлайн та i18n) +│ ├── include/ # Моделі, сервіси, ViewModels +│ ├── src/ # C++ реалізація +│ ├── qml/ # Екрани, стилі, компоненти (Geist UI) +│ └── tests/ # Набір тестів GoogleTest та Qt Test │ ├── packages/ │ └── api-contracts/ # Спільні TypeScript типи та DTO контракти @@ -182,6 +206,18 @@ dev-dialogue/ --- +### 💻 Десктопний клієнт та Windows-інсталятор + +Для користувачів десктопної версії готові інсталятори поширюються автоматично через **GitHub Releases** та артефакти **Pull Request** — **без потреби виконувати будь-які команди в терміналі чи встановлювати SDK**: + +- **Останній Windows-інсталятор:** [Завантажити `DevDialogue-Setup-x64.exe`](https://github.com/iberikofer/dev-dialogue/releases/latest) +- **Легкий онлайн-завантажувач (2 МБ):** [Завантажити `DevDialogue-Bootstrap-x64.exe`](https://github.com/iberikofer/dev-dialogue/releases/latest) +- **Збірки з Pull Request:** Завантажуйте готовий для тестування інсталятор прямо із вкладки **Summary → Artifacts** на сторінці будь-якого Pull Request. + +Просто двічі клікніть по завантаженому файлу `.exe` інсталятора. Він автоматично створить ярлики в меню «Пуск» та на робочому столі, встановить середовище Qt 6, DirectShow веб-камеру, Speech-to-Text та новий модуль **«Підготовка до співбесід»**. + +--- + ### 🛠 Швидкий старт для розробки #### 1. Встановлення залежностей diff --git a/apps/desktop/CMakeLists.txt b/apps/desktop/CMakeLists.txt index ef92d8e..82a7efe 100644 --- a/apps/desktop/CMakeLists.txt +++ b/apps/desktop/CMakeLists.txt @@ -55,6 +55,7 @@ set(DESKTOP_UI_VIEWMODEL_SOURCES src/viewmodels/FormValidator.cpp src/viewmodels/InterviewListModel.cpp src/viewmodels/MessageListModel.cpp + src/viewmodels/PreparationViewModel.cpp src/viewmodels/QuestionListModel.cpp src/viewmodels/ReportViewModel.cpp src/viewmodels/SettingsViewModel.cpp @@ -70,6 +71,7 @@ set(DESKTOP_UI_VIEWMODEL_HEADERS include/viewmodels/FormValidator.hpp include/viewmodels/InterviewListModel.hpp include/viewmodels/MessageListModel.hpp + include/viewmodels/PreparationViewModel.hpp include/viewmodels/QuestionListModel.hpp include/viewmodels/ReportViewModel.hpp include/viewmodels/SettingsViewModel.hpp @@ -88,6 +90,7 @@ add_executable(DevDialogue # Models & Contracts include/models/ApiContracts.hpp + include/models/PreparationModels.hpp # Network src/network/ApiClient.cpp @@ -104,6 +107,8 @@ add_executable(DevDialogue include/services/AvatarWebViewHost.hpp include/services/MicrophoneService.hpp include/services/WebcamService.hpp + include/services/IPreparationService.hpp + include/services/DemoPreparationService.hpp src/services/InMemorySecureStorage.cpp src/services/QtKeychainSecureStorage.cpp src/services/AuthService.cpp @@ -112,6 +117,7 @@ add_executable(DevDialogue src/services/AvatarWebViewHost.cpp src/services/MicrophoneService.cpp src/services/WebcamService.cpp + src/services/DemoPreparationService.cpp # ViewModels src/viewmodels/AuthViewModel.cpp @@ -129,6 +135,7 @@ endif() target_include_directories(DevDialogue PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/third_party ${CMAKE_CURRENT_SOURCE_DIR}/third_party/webview2/build/native/include ) @@ -250,6 +257,7 @@ qt_add_qml_module(DevDialogue qml/views/LoginView.qml qml/views/DashboardView.qml qml/views/SetupView.qml + qml/views/PreparationView.qml qml/views/ChatRoomView.qml qml/views/ReportView.qml qml/views/AdminView.qml @@ -279,11 +287,13 @@ if(GTest_FOUND) tests/unit/TestFormValidator.cpp tests/unit/TestListModels.cpp tests/unit/TestViewModels.cpp + tests/unit/TestPreparation.cpp # Headers for AUTOMOC include/core/AppConfig.hpp include/core/Constants.hpp include/models/ApiContracts.hpp + include/models/PreparationModels.hpp include/network/ApiClient.hpp include/network/NetworkEndpoints.hpp include/services/ISecureStorage.hpp @@ -292,6 +302,8 @@ if(GTest_FOUND) include/services/AuthService.hpp include/services/InterviewService.hpp include/services/AdminService.hpp + include/services/IPreparationService.hpp + include/services/DemoPreparationService.hpp include/viewmodels/NavigationViewModel.hpp ${DESKTOP_UI_VIEWMODEL_HEADERS} @@ -303,6 +315,7 @@ if(GTest_FOUND) src/services/AuthService.cpp src/services/InterviewService.cpp src/services/AdminService.cpp + src/services/DemoPreparationService.cpp src/viewmodels/NavigationViewModel.cpp ${DESKTOP_UI_VIEWMODEL_SOURCES} ) diff --git a/apps/desktop/include/models/PreparationModels.hpp b/apps/desktop/include/models/PreparationModels.hpp new file mode 100644 index 0000000..ee121fd --- /dev/null +++ b/apps/desktop/include/models/PreparationModels.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +namespace devdialogue::models { + +enum class PreparationTopicStatus { + Known, + NotMentioned, + Unclear +}; + +enum class TopicPriority { + High, + Medium, + Low +}; + +struct StudyMaterial { + QString title; + QString url; +}; + +struct PreparationTopic { + QString id; + QString title; + QString category; + PreparationTopicStatus status{PreparationTopicStatus::NotMentioned}; + QString reason; + TopicPriority priority{TopicPriority::Medium}; + QVector materials; +}; + +struct PreparationPlanResult { + QString summary; + QVector topics; + int totalTopics{0}; + int coveredTopics{0}; +}; + +} // namespace devdialogue::models diff --git a/apps/desktop/include/services/DemoPreparationService.hpp b/apps/desktop/include/services/DemoPreparationService.hpp new file mode 100644 index 0000000..f3e1c9d --- /dev/null +++ b/apps/desktop/include/services/DemoPreparationService.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include "services/IPreparationService.hpp" + +namespace devdialogue::services { + +class DemoPreparationService : public QObject, public IPreparationService { + Q_OBJECT + +public: + explicit DemoPreparationService(QObject* parent = nullptr); + ~DemoPreparationService() override = default; + + void analyzeProfile( + const QString& direction, + const QString& level, + const QString& userDescription, + const QString& language, + std::function callback + ) override; + + // Helper for direct deterministic synchronous evaluation (useful for unit tests without waiting) + models::PreparationPlanResult evaluateSynchronously( + const QString& direction, + const QString& level, + const QString& userDescription, + const QString& language + ) const; + +private: + struct TopicDefinition { + QString id; + QString titleEn; + QString titleUk; + QString categoryEn; + QString categoryUk; + models::TopicPriority basePriority; + QStringList keywords; + QVector materialsEn; + QVector materialsUk; + bool isAdvanced; + bool isFundamental; + }; + + QVector getDefinitionsForDirection(const QString& direction) const; + models::PreparationTopicStatus evaluateStatus( + const QString& descriptionLower, + const QStringList& keywords, + QString& outReason, + bool isUk + ) const; + + models::TopicPriority adjustPriority( + models::TopicPriority base, + bool isFundamental, + bool isAdvanced, + const QString& level + ) const; +}; + +} // namespace devdialogue::services diff --git a/apps/desktop/include/services/IPreparationService.hpp b/apps/desktop/include/services/IPreparationService.hpp new file mode 100644 index 0000000..1da9ed6 --- /dev/null +++ b/apps/desktop/include/services/IPreparationService.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include "models/PreparationModels.hpp" + +namespace devdialogue::services { + +class IPreparationService { +public: + virtual ~IPreparationService() = default; + + virtual void analyzeProfile( + const QString& direction, + const QString& level, + const QString& userDescription, + const QString& language, + std::function callback + ) = 0; +}; + +} // namespace devdialogue::services diff --git a/apps/desktop/include/viewmodels/NavigationViewModel.hpp b/apps/desktop/include/viewmodels/NavigationViewModel.hpp index 857c576..2c75d38 100644 --- a/apps/desktop/include/viewmodels/NavigationViewModel.hpp +++ b/apps/desktop/include/viewmodels/NavigationViewModel.hpp @@ -19,7 +19,8 @@ class NavigationViewModel : public QObject { Setup = 2, ChatRoom = 3, Report = 4, - Admin = 5 + Admin = 5, + Preparation = 6 }; Q_ENUM(ViewIndex) @@ -36,6 +37,7 @@ class NavigationViewModel : public QObject { Q_INVOKABLE void navigateToChat(const QString &interviewId); Q_INVOKABLE void navigateToReport(const QString &interviewId); Q_INVOKABLE void navigateToAdmin(); + Q_INVOKABLE void navigateToPreparation(); signals: void currentViewIndexChanged(int newIndex); diff --git a/apps/desktop/include/viewmodels/PreparationViewModel.hpp b/apps/desktop/include/viewmodels/PreparationViewModel.hpp new file mode 100644 index 0000000..e6c31f3 --- /dev/null +++ b/apps/desktop/include/viewmodels/PreparationViewModel.hpp @@ -0,0 +1,121 @@ +#pragma once + +#include +#include +#include +#include +#include "services/IPreparationService.hpp" +#include "viewmodels/NavigationViewModel.hpp" + +namespace devdialogue::viewmodels { + +class PreparationViewModel : public QObject { + Q_OBJECT + Q_PROPERTY(QString direction READ direction WRITE setDirection NOTIFY directionChanged) + Q_PROPERTY(QString level READ level WRITE setLevel NOTIFY levelChanged) + Q_PROPERTY(QString language READ language WRITE setLanguage NOTIFY languageChanged) + Q_PROPERTY(QString uiLanguage READ uiLanguage WRITE setUiLanguage NOTIFY uiLanguageChanged) + Q_PROPERTY(QString userDescription READ userDescription WRITE setUserDescription NOTIFY userDescriptionChanged) + Q_PROPERTY(int charCount READ charCount NOTIFY userDescriptionChanged) + Q_PROPERTY(int minCharCount READ minCharCount CONSTANT) + Q_PROPERTY(int maxCharCount READ maxCharCount CONSTANT) + Q_PROPERTY(bool isValidInput READ isValidInput NOTIFY validationChanged) + Q_PROPERTY(QString validationMessage READ validationMessage NOTIFY validationChanged) + Q_PROPERTY(bool isAnalyzing READ isAnalyzing NOTIFY analyzingChanged) + Q_PROPERTY(bool hasResult READ hasResult NOTIFY resultChanged) + Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) + Q_PROPERTY(QString summaryText READ summaryText NOTIFY resultChanged) + Q_PROPERTY(int totalTopicsCount READ totalTopicsCount NOTIFY resultChanged) + Q_PROPERTY(int coveredTopicsCount READ coveredTopicsCount NOTIFY resultChanged) + Q_PROPERTY(QVariantList recommendedTopics READ recommendedTopics NOTIFY resultChanged) + Q_PROPERTY(QVariantList coveredTopics READ coveredTopics NOTIFY resultChanged) + +public: + static constexpr int MinDescriptionLength = 30; + static constexpr int MaxDescriptionLength = 3000; + + explicit PreparationViewModel( + std::shared_ptr service, + NavigationViewModel* navigation = nullptr, + QObject* parent = nullptr + ); + ~PreparationViewModel() override = default; + + QString direction() const { return m_direction; } + void setDirection(const QString& dir); + + QString level() const { return m_level; } + void setLevel(const QString& lvl); + + QString language() const { return m_language; } + void setLanguage(const QString& lang); + + QString uiLanguage() const { return language(); } + void setUiLanguage(const QString& lang); + + QString userDescription() const { return m_userDescription; } + void setUserDescription(const QString& desc); + + int charCount() const { return static_cast(m_userDescription.trimmed().length()); } + int minCharCount() const { return MinDescriptionLength; } + int maxCharCount() const { return MaxDescriptionLength; } + + bool isValidInput() const; + QString validationMessage() const; + + bool isAnalyzing() const { return m_isAnalyzing; } + bool hasResult() const { return m_hasResult; } + QString errorMessage() const { return m_errorMessage; } + QString summaryText() const { return m_summaryText; } + int totalTopicsCount() const { return m_totalTopicsCount; } + int coveredTopicsCount() const { return m_coveredTopicsCount; } + + QVariantList recommendedTopics() const { return m_recommendedTopics; } + QVariantList coveredTopics() const { return m_coveredTopics; } + + Q_INVOKABLE void analyze(); + Q_INVOKABLE void reset(); + Q_INVOKABLE void refineDescription(); + +signals: + void directionChanged(); + void levelChanged(); + void languageChanged(); + void uiLanguageChanged(); + void userDescriptionChanged(); + void validationChanged(); + void analyzingChanged(); + void resultChanged(); + void errorMessageChanged(); + +private: + void updateValidation(); + void setAnalyzing(bool analyzing); + void setErrorMessage(const QString& msg); + void onAnalysisCompleted(const models::PreparationPlanResult& result, const QString& error); + + std::shared_ptr m_service; + NavigationViewModel* m_navigation{nullptr}; + + QString m_direction{QStringLiteral("frontend")}; + QString m_level{QStringLiteral("junior")}; + QString m_language{QStringLiteral("uk")}; + QString m_userDescription; + + bool m_isValidInput{false}; + QString m_validationMessage; + + bool m_isAnalyzing{false}; + bool m_hasResult{false}; + QString m_errorMessage; + QString m_summaryText; + int m_totalTopicsCount{0}; + int m_coveredTopicsCount{0}; + + QVariantList m_recommendedTopics; + QVariantList m_coveredTopics; + + uint64_t m_currentRequestId{0}; +}; + +} // namespace devdialogue::viewmodels diff --git a/apps/desktop/qml/Main.qml b/apps/desktop/qml/Main.qml index 3334a07..5b5dcc2 100644 --- a/apps/desktop/qml/Main.qml +++ b/apps/desktop/qml/Main.qml @@ -62,7 +62,7 @@ ApplicationWindow { // Stack index per NavigationViewModel::ViewIndex. Landing (0) has no // screen in the app and shows Home. - readonly property int pageIndex: accountOpen ? 6 + readonly property int pageIndex: accountOpen ? 7 : (navVM.currentViewIndex === 0 ? 1 : navVM.currentViewIndex) readonly property string sidebarSection: { @@ -73,6 +73,7 @@ ApplicationWindow { case 3: return "session" case 4: return "home" case 5: return "admin" + case 6: return "preparation" default: return "" } } @@ -82,6 +83,7 @@ ApplicationWindow { switch (target) { case "home": navVM.navigateToDashboard(); break case "setup": navVM.navigateToSetup(); break + case "preparation": navVM.navigateToPreparation(); break case "session": if (chatVM.hasActiveSession) { backendVM.ensureAllServicesRunning() @@ -138,6 +140,7 @@ ApplicationWindow { // Sample content shown without a backend follows the interface language. Binding { target: reportVM; property: "uiLanguage"; value: I18n.language } Binding { target: adminVM; property: "uiLanguage"; value: I18n.language } + Binding { target: preparationVM; property: "uiLanguage"; value: I18n.language } Component.onCompleted: { if (navVM.currentViewIndex === 0) @@ -253,6 +256,11 @@ ApplicationWindow { enabled: authVM.isAuthenticated onActivated: rootWindow.go("setup") } + Shortcut { + sequences: ["Ctrl+P"] + enabled: authVM.isAuthenticated + onActivated: rootWindow.go("preparation") + } Shortcut { sequence: "Ctrl+3" enabled: authVM.isAuthenticated && chatVM.hasActiveSession @@ -337,7 +345,8 @@ ApplicationWindow { } // 3 ReportView {} // 4 AdminView {} // 5 - AccountView {} // 6: local page, see accountOpen + PreparationView {} // 6 + AccountView {} // 7: local page, see accountOpen } } } diff --git a/apps/desktop/qml/components/Sidebar.qml b/apps/desktop/qml/components/Sidebar.qml index 1728274..bc045b0 100644 --- a/apps/desktop/qml/components/Sidebar.qml +++ b/apps/desktop/qml/components/Sidebar.qml @@ -57,6 +57,7 @@ Rectangle { switch (current) { case "home": return homeItem case "setup": return setupItem + case "preparation": return preparationItem case "session": return sessionItem.visible ? sessionItem : null case "admin": return adminItem.visible ? adminItem : null case "account": return accountItem @@ -138,6 +139,16 @@ Rectangle { active: sidebar.current === "setup" onClicked: sidebar.navigate("setup") } + SidebarItem { + id: preparationItem + Layout.fillWidth: true + expanded: sidebar.expanded + text: qsTr("Preparation") + iconName: "book-open" + shortcutHint: "Ctrl+P" + active: sidebar.current === "preparation" + onClicked: sidebar.navigate("preparation") + } SidebarItem { id: sessionItem Layout.fillWidth: true diff --git a/apps/desktop/qml/views/PreparationView.qml b/apps/desktop/qml/views/PreparationView.qml new file mode 100644 index 0000000..fb4d586 --- /dev/null +++ b/apps/desktop/qml/views/PreparationView.qml @@ -0,0 +1,644 @@ +pragma ComponentBehavior: Bound +import QtQuick +import QtQuick.Controls.Basic +import QtQuick.Layouts +import DevDialogue.App + +// Interview Preparation screen: +// Select track and level, enter free-form knowledge description, +// and receive tailored recommendations with authoritative study links. +AppPage { + id: page + + active: StackLayout.isCurrentItem + title: qsTr("Interview Preparation") + subtitle: preparationVM.hasResult + ? qsTr("Curated knowledge analysis & targeted preparation roadmap.") + : qsTr("Describe what you know in your specialty, and we'll analyze what to learn next.") + badgeText: qsTr("Demo Mode · Local Analysis") + + readonly property var directions: [ + { id: "frontend", icon: "code-xml", title: qsTr("Frontend"), + desc: qsTr("React, Next.js, TypeScript, browser APIs, CSS architecture") }, + { id: "backend", icon: "server", title: qsTr("Backend"), + desc: qsTr("ASP.NET Core, C#, databases, REST, async, system design") }, + { id: "devops", icon: "cloud-cog", title: qsTr("DevOps"), + desc: qsTr("Docker, CI/CD, Kubernetes, monitoring, cloud") }, + { id: "qa", icon: "circle-check", title: qsTr("Quality Assurance"), + desc: qsTr("Test design, automation, regression, API testing") }, + { id: "pm", icon: "briefcase", title: qsTr("Project Management"), + desc: qsTr("Agile, backlog, risk management, team dynamics") } + ] + + readonly property var levels: [ + { id: "trainee", title: "Trainee", subtitle: qsTr("Core principles and syntax") }, + { id: "junior", title: "Junior", subtitle: qsTr("Hands-on development and APIs") }, + { id: "middle", title: "Middle", subtitle: qsTr("Architecture and internals") } + ] + + function lookup(list, id) { + for (let i = 0; i < list.length; ++i) { + if (list[i].id === id) + return list[i] + } + return list[0] + } + + actions: [ + TactileButton { + visible: preparationVM.hasResult + variant: "secondary" + text: qsTr("Refine description") + iconLeft: "rotate-ccw" + implicitHeight: 40 + onClicked: preparationVM.refineDescription() + }, + TactileButton { + visible: preparationVM.hasResult + text: qsTr("Practice this track") + iconRight: "arrow-right" + implicitHeight: 40 + glow: true + onClicked: { + setupVM.direction = preparationVM.direction + setupVM.level = preparationVM.level + navVM.navigateToSetup() + } + } + ] + + component SectionLabel: MonoText { + Layout.fillWidth: true + caps: true + font.weight: Typography.semibold + } + + // ------------------------------------------------------------- + // STATE 1: Input & Configuration Form + // ------------------------------------------------------------- + RowLayout { + visible: !preparationVM.hasResult && !preparationVM.isAnalyzing + Layout.fillWidth: true + Layout.fillHeight: true + spacing: 24 + + // Choices Column + Flickable { + id: choicesFlickable + Layout.fillWidth: true + Layout.fillHeight: true + contentWidth: width + contentHeight: formColumn.implicitHeight + clip: true + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ThemedScrollBar {} + + ColumnLayout { + id: formColumn + width: choicesFlickable.width - 12 + spacing: 16 + + AlertBox { + visible: preparationVM.errorMessage !== "" + Layout.fillWidth: true + Layout.bottomMargin: 8 + text: preparationVM.errorMessage + } + + SectionLabel { text: qsTr("Select Track") } + GridLayout { + id: trackGrid + Layout.fillWidth: true + columns: width > 760 ? 3 : 2 + columnSpacing: 12 + rowSpacing: 12 + + Repeater { + model: page.directions + SelectCard { + id: trackCard + required property var modelData + Layout.fillWidth: true + Layout.fillHeight: true + Layout.minimumWidth: 0 + Layout.preferredWidth: (trackGrid.width - trackGrid.columnSpacing * (trackGrid.columns - 1)) / trackGrid.columns + selected: preparationVM.direction === modelData.id + onClicked: preparationVM.direction = modelData.id + + contentItem: RowLayout { + spacing: 14 + Rectangle { + Layout.alignment: Qt.AlignTop + implicitWidth: 40 + implicitHeight: 40 + radius: Theme.radiusMd + color: trackCard.selected ? Theme.primary : Theme.zinc800 + Behavior on color { ColorAnimation { duration: Theme.durationFast } } + Icon { + anchors.centerIn: parent + name: trackCard.modelData.icon + size: 20 + color: trackCard.selected ? Theme.textOnAccent : Theme.zinc400 + } + } + ColumnLayout { + Layout.fillWidth: true + Layout.alignment: Qt.AlignTop + spacing: 4 + AppText { + Layout.fillWidth: true + text: trackCard.modelData.title + font.weight: Typography.semibold + elide: Text.ElideRight + } + AppText { + Layout.fillWidth: true + text: trackCard.modelData.desc + color: Theme.zinc400 + font.pixelSize: Typography.xs + lineHeight: Typography.leadingNormal + wrapMode: Text.WordWrap + } + } + } + } + } + } + + SectionLabel { Layout.topMargin: 12; text: qsTr("Experience Level") } + RowLayout { + Layout.fillWidth: true + Layout.maximumWidth: 540 + spacing: 12 + + Repeater { + model: page.levels + SelectCard { + id: levelCard + required property var modelData + Layout.fillWidth: true + Layout.fillHeight: true + Layout.preferredWidth: 1 + selected: preparationVM.level === modelData.id + onClicked: preparationVM.level = modelData.id + + contentItem: ColumnLayout { + spacing: 4 + AppText { + Layout.fillWidth: true + text: levelCard.modelData.title + font.weight: Typography.semibold + } + AppText { + Layout.fillWidth: true + text: levelCard.modelData.subtitle + color: Theme.zinc400 + font.pixelSize: Typography.xs + wrapMode: Text.WordWrap + } + Item { Layout.fillHeight: true } + } + } + } + } + + SectionLabel { Layout.topMargin: 12; text: qsTr("Your Skills & Experience") } + DarkCard { + Layout.fillWidth: true + padding: 16 + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + spacing: 8 + + DarkTextArea { + id: descInput + Layout.fillWidth: true + implicitHeight: 140 + text: preparationVM.userDescription + onTextChanged: preparationVM.userDescription = text + placeholderText: qsTr("Describe your skills in free form. For example:\n\"I have been developing with C# and ASP.NET Core for 2 years, worked with PostgreSQL and Entity Framework Core. Built REST APIs and wrote unit tests. Never used Docker or Kubernetes, and haven't worked with microservices yet...\"") + invalid: !preparationVM.isValidInput && preparationVM.charCount > 0 + } + + RowLayout { + Layout.fillWidth: true + spacing: 8 + + Icon { + name: preparationVM.isValidInput ? "circle-check" : "info" + size: 14 + color: preparationVM.isValidInput ? Theme.emerald400 + : (preparationVM.charCount > preparationVM.maxCharCount ? Theme.rose400 : Theme.zinc500) + } + AppText { + Layout.fillWidth: true + text: preparationVM.validationMessage + color: preparationVM.isValidInput ? Theme.emerald400 + : (preparationVM.charCount > preparationVM.maxCharCount ? Theme.rose400 : Theme.zinc500) + font.pixelSize: Typography.tiny + } + MonoText { + text: preparationVM.charCount + " / " + preparationVM.maxCharCount + color: preparationVM.charCount > preparationVM.maxCharCount ? Theme.rose400 : Theme.zinc500 + font.pixelSize: Typography.tiny + } + } + } + } + + Item { implicitHeight: 16 } + } + } + + // Summary Sidebar + DarkCard { + Layout.preferredWidth: 320 + Layout.alignment: Qt.AlignTop + padding: 24 + fillColor: Theme.alpha(Theme.zinc900, 0.7) + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + spacing: 0 + + MonoText { + caps: true + text: qsTr("Summary") + font.weight: Typography.semibold + } + + RowLayout { + Layout.fillWidth: true + Layout.topMargin: 16 + AppText { Layout.fillWidth: true; text: qsTr("Track"); color: Theme.zinc400 } + AppText { text: page.lookup(page.directions, preparationVM.direction).title; font.weight: Typography.semibold } + } + + RowLayout { + Layout.fillWidth: true + Layout.topMargin: 12 + AppText { Layout.fillWidth: true; text: qsTr("Level"); color: Theme.zinc400 } + AppText { text: page.lookup(page.levels, preparationVM.level).title; font.weight: Typography.semibold } + } + + Rectangle { + Layout.fillWidth: true + Layout.topMargin: 18 + Layout.bottomMargin: 18 + implicitHeight: 1 + color: Theme.borderFaint + } + + RowLayout { + Layout.fillWidth: true + spacing: 10 + Icon { Layout.alignment: Qt.AlignTop; name: "info"; size: 16; color: Theme.blue400 } + AppText { + Layout.fillWidth: true + text: qsTr("The analyzer checks for keywords and context. Anything not mentioned in your description will be suggested as study material.") + color: Theme.zinc400 + font.pixelSize: Typography.xs + lineHeight: Typography.leadingNormal + wrapMode: Text.WordWrap + } + } + + Item { implicitHeight: 12 } + + Badge { + Layout.fillWidth: true + tone: "neutral" + text: qsTr("Local keyword analyzer · Zero network required") + fontSize: Typography.tiny + } + + TactileButton { + Layout.fillWidth: true + Layout.topMargin: 20 + text: preparationVM.isAnalyzing ? qsTr("Analyzing skills...") : qsTr("Generate study plan") + iconRight: preparationVM.isAnalyzing ? "" : "arrow-right" + busy: preparationVM.isAnalyzing + enabled: preparationVM.isValidInput && !preparationVM.isAnalyzing + implicitHeight: 46 + glow: true + onClicked: preparationVM.analyze() + } + } + } + } + + // ------------------------------------------------------------- + // STATE 2: Loading Analysis Spinner + // ------------------------------------------------------------- + ColumnLayout { + visible: preparationVM.isAnalyzing + Layout.fillWidth: true + Layout.topMargin: 120 + spacing: 16 + + Spinner { + Layout.alignment: Qt.AlignHCenter + size: 36 + color: Theme.blue400 + } + AppText { + Layout.alignment: Qt.AlignHCenter + text: qsTr("Analyzing your skills and mapping out a preparation roadmap…") + color: Theme.zinc300 + font.pixelSize: Typography.sm + } + } + + // ------------------------------------------------------------- + // STATE 3: Results & Study Roadmap + // ------------------------------------------------------------- + Flickable { + id: resultsScroller + visible: preparationVM.hasResult && !preparationVM.isAnalyzing + Layout.fillWidth: true + Layout.fillHeight: true + contentWidth: width + contentHeight: resultsColumn.implicitHeight + 24 + clip: true + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ThemedScrollBar {} + + ColumnLayout { + id: resultsColumn + width: resultsScroller.width - 12 + spacing: 20 + + // 1. Overview Banner + DarkCard { + Layout.fillWidth: true + padding: 24 + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + spacing: 12 + + RowLayout { + Layout.fillWidth: true + spacing: 12 + + Icon { name: "book-open"; size: 22; color: Theme.blue400 } + AppText { + Layout.fillWidth: true + text: qsTr("Roadmap Overview") + font.pixelSize: Typography.lg + font.weight: Typography.bold + } + Badge { + tone: preparationVM.coveredTopicsCount === preparationVM.totalTopicsCount ? "emerald" : "blue" + text: qsTr("%1 / %2 topics covered").arg(preparationVM.coveredTopicsCount).arg(preparationVM.totalTopicsCount) + fontWeight: Typography.bold + } + } + + AppText { + Layout.fillWidth: true + text: preparationVM.summaryText + color: Theme.zinc300 + font.pixelSize: Typography.sm + lineHeight: Typography.leadingRelaxed + wrapMode: Text.WordWrap + } + } + } + + // 2. Recommended Topics (Study Gaps) + DarkCard { + visible: preparationVM.recommendedTopics.length > 0 + Layout.fillWidth: true + padding: 24 + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + spacing: 16 + + RowLayout { + Layout.fillWidth: true + spacing: 10 + + Icon { name: "book-open"; size: 18; color: Theme.amber400 } + AppText { + Layout.fillWidth: true + text: qsTr("What to Study Next") + font.pixelSize: Typography.base + font.weight: Typography.bold + } + Badge { + tone: "amber" + text: qsTr("%1 recommendations").arg(preparationVM.recommendedTopics.length) + } + } + + Repeater { + model: preparationVM.recommendedTopics + Rectangle { + id: topicBox + required property var modelData + Layout.fillWidth: true + implicitHeight: topicCol.implicitHeight + 24 + radius: Theme.radiusMd + color: Theme.alpha(Theme.zinc950, 0.6) + border.width: 1 + border.color: Theme.borderGlass + + ColumnLayout { + id: topicCol + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: 14 + spacing: 8 + + RowLayout { + Layout.fillWidth: true + spacing: 8 + + AppText { + Layout.fillWidth: true + text: topicBox.modelData.title + font.weight: Typography.semibold + font.pixelSize: Typography.sm + } + Badge { + tone: topicBox.modelData.priority === "high" ? "rose" : (topicBox.modelData.priority === "medium" ? "amber" : "blue") + text: topicBox.modelData.priorityText + fontSize: Typography.tiny + } + Badge { + tone: topicBox.modelData.status === "unclear" ? "amber" : "neutral" + text: topicBox.modelData.statusText + fontSize: Typography.tiny + } + } + + AppText { + Layout.fillWidth: true + text: topicBox.modelData.reason + color: Theme.zinc400 + font.pixelSize: Typography.xs + wrapMode: Text.WordWrap + } + + // Materials list + Repeater { + model: topicBox.modelData.materials + AbstractButton { + id: matLink + required property var modelData + Layout.fillWidth: true + implicitHeight: 44 + hoverEnabled: true + onClicked: Qt.openUrlExternally(matLink.modelData.url) + HoverHandler { cursorShape: Qt.PointingHandCursor } + + background: Rectangle { + radius: Theme.radiusSm + color: matLink.hovered ? Theme.zinc900 : Theme.alpha(Theme.zinc900, 0.4) + border.width: 1 + border.color: matLink.hovered ? Theme.alpha(Theme.blue500, 0.4) : Theme.borderFaint + } + + contentItem: RowLayout { + spacing: 10 + Item { implicitWidth: 4 } + Icon { name: "external-link"; size: 14; color: matLink.hovered ? Theme.blue400 : Theme.zinc500 } + ColumnLayout { + Layout.fillWidth: true + spacing: 1 + AppText { + Layout.fillWidth: true + text: matLink.modelData.title + font.pixelSize: Typography.xs + font.weight: Typography.medium + color: matLink.hovered ? Theme.blue300 : Theme.zinc200 + elide: Text.ElideRight + } + AppText { + Layout.fillWidth: true + text: matLink.modelData.url + font.pixelSize: Typography.tiny + color: Theme.textMuted + elide: Text.ElideRight + } + } + Item { implicitWidth: 4 } + } + } + } + } + } + } + } + } + + // 3. Covered Topics + DarkCard { + visible: preparationVM.coveredTopics.length > 0 + Layout.fillWidth: true + padding: 20 + + ColumnLayout { + anchors.left: parent.left + anchors.right: parent.right + spacing: 12 + + RowLayout { + Layout.fillWidth: true + spacing: 10 + + Icon { name: "circle-check"; size: 18; color: Theme.emerald400 } + AppText { + Layout.fillWidth: true + text: qsTr("Already Mentioned & Covered") + font.pixelSize: Typography.base + font.weight: Typography.bold + } + Badge { + tone: "emerald" + text: qsTr("%1 topics").arg(preparationVM.coveredTopics.length) + } + } + + Repeater { + model: preparationVM.coveredTopics + RowLayout { + id: covRow + required property var modelData + Layout.fillWidth: true + spacing: 8 + + Icon { name: "circle-check"; size: 14; color: Theme.emerald500 } + AppText { + text: covRow.modelData.title + font.weight: Typography.medium + font.pixelSize: Typography.sm + color: Theme.zinc300 + } + AppText { + Layout.fillWidth: true + text: "— " + covRow.modelData.reason + color: Theme.zinc500 + font.pixelSize: Typography.xs + elide: Text.ElideRight + } + } + } + } + } + + // 4. Disclaimer + RowLayout { + Layout.fillWidth: true + Layout.topMargin: 4 + spacing: 8 + + Icon { name: "info"; size: 14; color: Theme.textMuted } + AppText { + Layout.fillWidth: true + text: qsTr("Note: This evaluation is generated locally from your free-form description and is not a conclusive assessment of your abilities.") + color: Theme.textMuted + font.pixelSize: Typography.tiny + wrapMode: Text.WordWrap + } + } + + // 5. Actions Footer + RowLayout { + Layout.fillWidth: true + Layout.topMargin: 12 + spacing: 14 + + TactileButton { + variant: "secondary" + text: qsTr("Refine description") + iconLeft: "rotate-ccw" + implicitHeight: 44 + onClicked: preparationVM.refineDescription() + } + TactileButton { + Layout.fillWidth: true + text: qsTr("Start interview for this track") + iconRight: "arrow-right" + implicitHeight: 44 + glow: true + onClicked: { + setupVM.direction = preparationVM.direction + setupVM.level = preparationVM.level + navVM.navigateToSetup() + } + } + } + + Item { implicitHeight: 24 } + } + } +} diff --git a/apps/desktop/src/main.cpp b/apps/desktop/src/main.cpp index e992f8c..346c5b4 100644 --- a/apps/desktop/src/main.cpp +++ b/apps/desktop/src/main.cpp @@ -6,12 +6,17 @@ #include #include +#ifdef _WIN32 +#include +#endif + #include "core/AppConfig.hpp" #include "core/Constants.hpp" #include "network/ApiClient.hpp" #include "services/AdminService.hpp" #include "services/AuthService.hpp" #include "services/AvatarWebViewHost.hpp" +#include "services/DemoPreparationService.hpp" #include "services/InterviewService.hpp" #include "services/MicrophoneService.hpp" #include "services/QtKeychainSecureStorage.hpp" @@ -23,6 +28,7 @@ #include "viewmodels/DashboardViewModel.hpp" #include "viewmodels/FormValidator.hpp" #include "viewmodels/NavigationViewModel.hpp" +#include "viewmodels/PreparationViewModel.hpp" #include "viewmodels/ReportViewModel.hpp" #include "viewmodels/SettingsViewModel.hpp" #include "viewmodels/SetupViewModel.hpp" @@ -31,6 +37,18 @@ int main(int argc, char *argv[]) { using namespace devdialogue; +#ifdef _WIN32 + // Ensure plugins loaded from subdirectories (e.g. qml/, platforms/) can find + // Qt and runtime DLLs in the application directory. + wchar_t appPath[MAX_PATH]; + if (GetModuleFileNameW(nullptr, appPath, MAX_PATH) > 0) { + if (auto *lastSlash = wcsrchr(appPath, L'\\')) { + *lastSlash = L'\0'; + SetDllDirectoryW(appPath); + } + } +#endif + QGuiApplication::setHighDpiScaleFactorRoundingPolicy( Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); @@ -84,6 +102,10 @@ int main(int argc, char *argv[]) { std::make_unique(interviewService); auto adminVM = std::make_unique(adminService, authService); + auto preparationService = + std::make_shared(); + auto preparationVM = std::make_unique( + preparationService, navVM.get()); auto systemMonitorVM = std::make_unique(); QObject::connect(settingsVM.get(), @@ -157,6 +179,8 @@ int main(int argc, char *argv[]) { }); QQmlApplicationEngine engine; + engine.addImportPath(app.applicationDirPath() + QStringLiteral("/qml")); + engine.addImportPath(app.applicationDirPath()); engine.addImageProvider( QStringLiteral("webcam"), new services::WebcamImageProvider(webcamService->frameBuffer())); @@ -172,6 +196,7 @@ int main(int argc, char *argv[]) { rootContext->setContextProperty("chatVM", chatVM.get()); rootContext->setContextProperty("reportVM", reportVM.get()); rootContext->setContextProperty("adminVM", adminVM.get()); + rootContext->setContextProperty("preparationVM", preparationVM.get()); rootContext->setContextProperty("systemMonitorVM", systemMonitorVM.get()); rootContext->setContextProperty("apiClient", apiClient.get()); rootContext->setContextProperty("avatarHost", avatarHost.get()); diff --git a/apps/desktop/src/services/DemoPreparationService.cpp b/apps/desktop/src/services/DemoPreparationService.cpp new file mode 100644 index 0000000..d1addf8 --- /dev/null +++ b/apps/desktop/src/services/DemoPreparationService.cpp @@ -0,0 +1,602 @@ +#include "services/DemoPreparationService.hpp" +#include +#include + +namespace devdialogue::services { + +DemoPreparationService::DemoPreparationService(QObject* parent) + : QObject(parent) {} + +void DemoPreparationService::analyzeProfile( + const QString& direction, + const QString& level, + const QString& userDescription, + const QString& language, + std::function callback +) { + if (!callback) return; + + // Artificial 1000ms delay to give a natural feeling of deep profile analysis + QTimer::singleShot(1000, this, [this, direction, level, userDescription, language, callback]() { + models::PreparationPlanResult result = evaluateSynchronously(direction, level, userDescription, language); + callback(result, QString()); + }); +} + +models::TopicPriority DemoPreparationService::adjustPriority( + models::TopicPriority base, + bool isFundamental, + bool isAdvanced, + const QString& level +) const { + const QString lvl = level.trimmed().toLower(); + if (lvl == QStringLiteral("trainee")) { + if (isFundamental) return models::TopicPriority::High; + if (isAdvanced) return models::TopicPriority::Low; + } else if (lvl == QStringLiteral("middle")) { + if (isAdvanced) return models::TopicPriority::High; + if (isFundamental) return models::TopicPriority::Low; + } + return base; +} + +models::PreparationTopicStatus DemoPreparationService::evaluateStatus( + const QString& descriptionLower, + const QStringList& keywords, + QString& outReason, + bool isUk +) const { + static const QStringList ukNegations = { + QStringLiteral("не "), QStringLiteral("ні "), QStringLiteral("без "), QStringLiteral("немає"), + QStringLiteral("не маю"), QStringLiteral("не вмію"), QStringLiteral("не знаю"), QStringLiteral("не вчив"), + QStringLiteral("не вчила"), QStringLiteral("не володію"), QStringLiteral("не працював"), QStringLiteral("не працювала"), + QStringLiteral("не доводилось"), QStringLiteral("не доводилося"), QStringLiteral("жодного досвіду"), + QStringLiteral("нуль досвіду"), QStringLiteral("не використовував"), QStringLiteral("не застосовував") + }; + + static const QStringList enNegations = { + QStringLiteral("not "), QStringLiteral("no "), QStringLiteral("never "), QStringLiteral("don't "), + QStringLiteral("dont "), QStringLiteral("didn't "), QStringLiteral("didnt "), QStringLiteral("haven't "), + QStringLiteral("havent "), QStringLiteral("without "), QStringLiteral("lack "), QStringLiteral("no experience"), + QStringLiteral("zero experience"), QStringLiteral("never used"), QStringLiteral("never worked"), QStringLiteral("unfamiliar with") + }; + + static const QStringList ukQualifiers = { + QStringLiteral("трохи"), QStringLiteral("трішки"), QStringLiteral("базово"), QStringLiteral("поверхнево"), + QStringLiteral("початківець"), QStringLiteral("лише чув"), QStringLiteral("чула"), QStringLiteral("знайомий лише"), + QStringLiteral("тільки починаю"), QStringLiteral("мінімально") + }; + + static const QStringList enQualifiers = { + QStringLiteral("a bit"), QStringLiteral("little"), QStringLiteral("basic"), QStringLiteral("basics"), + QStringLiteral("beginner"), QStringLiteral("heard of"), QStringLiteral("surface"), QStringLiteral("just started"), + QStringLiteral("elementary"), QStringLiteral("minimal") + }; + + int bestMatchPos = -1; + QString matchedKeyword; + + for (const QString& kw : keywords) { + int pos = descriptionLower.indexOf(kw); + if (pos != -1) { + bestMatchPos = pos; + matchedKeyword = kw; + break; + } + } + + if (bestMatchPos == -1) { + outReason = isUk ? QStringLiteral("У вашому описі це не згадано.") + : QStringLiteral("Not mentioned in your description."); + return models::PreparationTopicStatus::NotMentioned; + } + + // Inspect prefix window (~45 characters before keyword) for negations or qualifiers + int windowStart = std::max(0, bestMatchPos - 45); + QString prefixWindow = descriptionLower.mid(windowStart, bestMatchPos - windowStart); + + // 1. Check negation + bool hasNegation = false; + for (const QString& neg : ukNegations) { + if (prefixWindow.contains(neg)) { hasNegation = true; break; } + } + if (!hasNegation) { + for (const QString& neg : enNegations) { + if (prefixWindow.contains(neg)) { hasNegation = true; break; } + } + } + + if (hasNegation) { + outReason = isUk ? QStringLiteral("У вашому описі зазначено відсутність досвіду з цієї теми.") + : QStringLiteral("Your description indicates a lack of experience with this topic."); + return models::PreparationTopicStatus::NotMentioned; + } + + // 2. Check qualifier/unclear + bool hasQualifier = false; + for (const QString& qual : ukQualifiers) { + if (prefixWindow.contains(qual)) { hasQualifier = true; break; } + } + if (!hasQualifier) { + for (const QString& qual : enQualifiers) { + if (prefixWindow.contains(qual)) { hasQualifier = true; break; } + } + } + + if (hasQualifier) { + outReason = isUk ? QStringLiteral("Ви згадали поверхневе або базове знайомство з цією темою.") + : QStringLiteral("You mentioned a surface-level or tentative acquaintance with this topic."); + return models::PreparationTopicStatus::Unclear; + } + + // 3. Confident mention + outReason = isUk ? QStringLiteral("У вашому описі зазначено володіння цією темою.") + : QStringLiteral("Your description indicates practical familiarity with this topic."); + return models::PreparationTopicStatus::Known; +} + +QVector DemoPreparationService::getDefinitionsForDirection(const QString& direction) const { + const QString dir = direction.trimmed().toLower(); + QVector list; + + if (dir == QStringLiteral("frontend")) { + list.append({ + QStringLiteral("fe-html-css"), + QStringLiteral("Semantic HTML5 & Modern CSS Layouts"), QStringLiteral("Семантичний HTML5 та сучасні CSS-макети"), + QStringLiteral("Core Web"), QStringLiteral("Базовий веб"), + models::TopicPriority::High, + {QStringLiteral("html"), QStringLiteral("css"), QStringLiteral("flexbox"), QStringLiteral("grid"), QStringLiteral("гріди"), QStringLiteral("флекси"), QStringLiteral("семантика")}, + {{QStringLiteral("MDN Web Docs: HTML & CSS"), QStringLiteral("https://developer.mozilla.org/docs/Web/HTML")}}, + {{QStringLiteral("MDN Web Docs: Довідник з HTML та CSS"), QStringLiteral("https://developer.mozilla.org/docs/Web/HTML")}}, + false, true + }); + list.append({ + QStringLiteral("fe-js-ts"), + QStringLiteral("TypeScript & Modern JavaScript (ES6+, Async)"), QStringLiteral("TypeScript та сучасний JavaScript (ES6+, Async)"), + QStringLiteral("Language"), QStringLiteral("Мова програмування"), + models::TopicPriority::High, + {QStringLiteral("typescript"), QStringLiteral("тайпскрипт"), QStringLiteral("javascript"), QStringLiteral("джаваскрипт"), QStringLiteral("js"), QStringLiteral("ts"), QStringLiteral("es6"), QStringLiteral("async/await"), QStringLiteral("promise")}, + {{QStringLiteral("TypeScript Handbook"), QStringLiteral("https://www.typescriptlang.org/docs/handbook/intro.html")}}, + {{QStringLiteral("Документація TypeScript"), QStringLiteral("https://www.typescriptlang.org/docs/handbook/intro.html")}}, + false, true + }); + list.append({ + QStringLiteral("fe-react-core"), + QStringLiteral("React Framework, Hooks & Component Lifecycle"), QStringLiteral("React: хуки, стан та життєвий цикл компонентів"), + QStringLiteral("Framework"), QStringLiteral("Фреймворк"), + models::TopicPriority::High, + {QStringLiteral("react"), QStringLiteral("реакт"), QStringLiteral("reactjs"), QStringLiteral("hooks"), QStringLiteral("хуки"), QStringLiteral("useeffect"), QStringLiteral("usestate")}, + {{QStringLiteral("React Official Documentation"), QStringLiteral("https://react.dev/learn")}}, + {{QStringLiteral("Офіційний посібник React"), QStringLiteral("https://react.dev/learn")}}, + false, true + }); + list.append({ + QStringLiteral("fe-nextjs"), + QStringLiteral("Next.js App Router & Server Components (SSR/SSG)"), QStringLiteral("Next.js: App Router, серверні компоненти (SSR/SSG)"), + QStringLiteral("Framework"), QStringLiteral("Фреймворк"), + models::TopicPriority::Medium, + {QStringLiteral("next.js"), QStringLiteral("nextjs"), QStringLiteral("некст"), QStringLiteral("ssr"), QStringLiteral("ssg"), QStringLiteral("server components")}, + {{QStringLiteral("Next.js Documentation"), QStringLiteral("https://nextjs.org/docs")}}, + {{QStringLiteral("Документація Next.js"), QStringLiteral("https://nextjs.org/docs")}}, + true, false + }); + list.append({ + QStringLiteral("fe-state-mgmt"), + QStringLiteral("Global State Management (Zustand, Redux Toolkit)"), QStringLiteral("Керування глобальним станом (Zustand, Redux Toolkit)"), + QStringLiteral("Architecture"), QStringLiteral("Архітектура"), + models::TopicPriority::Medium, + {QStringLiteral("zustand"), QStringLiteral("redux"), QStringLiteral("зустанд"), QStringLiteral("редакс"), QStringLiteral("state management"), QStringLiteral("керування станом")}, + {{QStringLiteral("Redux Toolkit Essentials"), QStringLiteral("https://redux.js.org/introduction/getting-started")}}, + {{QStringLiteral("Посібник з Redux Toolkit"), QStringLiteral("https://redux.js.org/introduction/getting-started")}}, + false, false + }); + list.append({ + QStringLiteral("fe-performance"), + QStringLiteral("Web Performance, Core Web Vitals & DevTools"), QStringLiteral("Оптимізація продуктивності вебу та Core Web Vitals"), + QStringLiteral("Performance"), QStringLiteral("Продуктивність"), + models::TopicPriority::Low, + {QStringLiteral("performance"), QStringLiteral("продуктивність"), QStringLiteral("lighthouse"), QStringLiteral("лайтхаус"), QStringLiteral("core web vitals"), QStringLiteral("devtools"), QStringLiteral("bundle size")}, + {{QStringLiteral("web.dev Performance Overview"), QStringLiteral("https://web.dev/explore/fast")}}, + {{QStringLiteral("web.dev: Оптимізація швидкодії веб-сторінок"), QStringLiteral("https://web.dev/explore/fast")}}, + true, false + }); + list.append({ + QStringLiteral("fe-testing"), + QStringLiteral("Frontend Unit & Integration Testing (Vitest, RTL)"), QStringLiteral("Модульне тестування інтерфейсу (Vitest, Testing Library)"), + QStringLiteral("Testing"), QStringLiteral("Тестування"), + models::TopicPriority::Medium, + {QStringLiteral("vitest"), QStringLiteral("jest"), QStringLiteral("джест"), QStringLiteral("testing library"), QStringLiteral("rtl"), QStringLiteral("юніт тести")}, + {{QStringLiteral("React Testing Library Docs"), QStringLiteral("https://testing-library.com/docs/react-testing-library/intro/")}}, + {{QStringLiteral("Документація React Testing Library"), QStringLiteral("https://testing-library.com/docs/react-testing-library/intro/")}}, + false, false + }); + list.append({ + QStringLiteral("fe-build-tools"), + QStringLiteral("Modern Build Tooling (Vite, Package Managers)"), QStringLiteral("Інструменти збірки проекту (Vite, пакетні менеджери)"), + QStringLiteral("Tooling"), QStringLiteral("Інструменти"), + models::TopicPriority::Low, + {QStringLiteral("vite"), QStringLiteral("вайт"), QStringLiteral("webpack"), QStringLiteral("вебпак"), QStringLiteral("npm"), QStringLiteral("pnpm"), QStringLiteral("yarn")}, + {{QStringLiteral("Vite Guide"), QStringLiteral("https://vitejs.dev/guide/")}}, + {{QStringLiteral("Посібник з Vite"), QStringLiteral("https://vitejs.dev/guide/")}}, + false, false + }); + } else if (dir == QStringLiteral("backend")) { + list.append({ + QStringLiteral("be-csharp"), + QStringLiteral("C# Language Semantics, Memory & Modern OOP"), QStringLiteral("Мова C#: семантика, керування пам'яттю та сучасне ООП"), + QStringLiteral("Language"), QStringLiteral("Мова програмування"), + models::TopicPriority::High, + {QStringLiteral("c#"), QStringLiteral("сі шарп"), QStringLiteral("csharp"), QStringLiteral(".net"), QStringLiteral("дотнет"), QStringLiteral("dotnet"), QStringLiteral("oop"), QStringLiteral("ооп")}, + {{QStringLiteral("Microsoft Learn: C# Documentation"), QStringLiteral("https://learn.microsoft.com/dotnet/csharp/")}}, + {{QStringLiteral("Microsoft Learn: Документація C#"), QStringLiteral("https://learn.microsoft.com/dotnet/csharp/")}}, + false, true + }); + list.append({ + QStringLiteral("be-aspnet"), + QStringLiteral("ASP.NET Core Architecture & RESTful API Design"), QStringLiteral("Архітектура ASP.NET Core та проектування REST API"), + QStringLiteral("Framework"), QStringLiteral("Фреймворк"), + models::TopicPriority::High, + {QStringLiteral("asp.net"), QStringLiteral("aspnet"), QStringLiteral("асп.нет"), QStringLiteral("rest api"), QStringLiteral("рест"), QStringLiteral("restful"), QStringLiteral("web api"), QStringLiteral("контролери")}, + {{QStringLiteral("Microsoft Learn: ASP.NET Core"), QStringLiteral("https://learn.microsoft.com/aspnet/core/")}}, + {{QStringLiteral("Microsoft Learn: Розробка в ASP.NET Core"), QStringLiteral("https://learn.microsoft.com/aspnet/core/")}}, + false, true + }); + list.append({ + QStringLiteral("be-sql-db"), + QStringLiteral("Relational Databases, SQL & Transactions (PostgreSQL)"), QStringLiteral("Реляційні бази даних, SQL та транзакції (PostgreSQL)"), + QStringLiteral("Databases"), QStringLiteral("Бази даних"), + models::TopicPriority::High, + {QStringLiteral("sql"), QStringLiteral("скл"), QStringLiteral("postgres"), QStringLiteral("postgresql"), QStringLiteral("постгрес"), QStringLiteral("database"), QStringLiteral("база даних"), QStringLiteral("індекси"), QStringLiteral("indexes")}, + {{QStringLiteral("PostgreSQL Documentation"), QStringLiteral("https://www.postgresql.org/docs/current/")}}, + {{QStringLiteral("Офіційна документація PostgreSQL"), QStringLiteral("https://www.postgresql.org/docs/current/")}}, + false, true + }); + list.append({ + QStringLiteral("be-efcore"), + QStringLiteral("Entity Framework Core & Query Optimization"), QStringLiteral("Entity Framework Core та оптимізація запитів"), + QStringLiteral("Databases"), QStringLiteral("Бази даних"), + models::TopicPriority::High, + {QStringLiteral("ef core"), QStringLiteral("efcore"), QStringLiteral("entity framework"), QStringLiteral("ефкор"), QStringLiteral("ентіті"), QStringLiteral("orm"), QStringLiteral("орм"), QStringLiteral("миграції")}, + {{QStringLiteral("Microsoft Learn: Entity Framework Core"), QStringLiteral("https://learn.microsoft.com/ef/core/")}}, + {{QStringLiteral("Microsoft Learn: Посібник з EF Core"), QStringLiteral("https://learn.microsoft.com/ef/core/")}}, + false, false + }); + list.append({ + QStringLiteral("be-async"), + QStringLiteral("Asynchronous & Multithreaded Programming (async/await)"), QStringLiteral("Асинхронне та багатопотокове програмування (async/await)"), + QStringLiteral("Concurrency"), QStringLiteral("Багатопотоковість"), + models::TopicPriority::Medium, + {QStringLiteral("async/await"), QStringLiteral("асинхрон"), QStringLiteral("multithreading"), QStringLiteral("багатопотоковість"), QStringLiteral("tasks"), QStringLiteral("cancellationtoken"), QStringLiteral("deadlock")}, + {{QStringLiteral("Asynchronous Programming in C#"), QStringLiteral("https://learn.microsoft.com/dotnet/csharp/asynchronous-programming/")}}, + {{QStringLiteral("Асинхронне програмування в .NET"), QStringLiteral("https://learn.microsoft.com/dotnet/csharp/asynchronous-programming/")}}, + true, false + }); + list.append({ + QStringLiteral("be-docker"), + QStringLiteral("Containerization & Development Environments (Docker)"), QStringLiteral("Контейнеризація сервісів (Docker, Docker Compose)"), + QStringLiteral("DevOps & Infra"), QStringLiteral("Інфраструктура"), + models::TopicPriority::Medium, + {QStringLiteral("docker"), QStringLiteral("докер"), QStringLiteral("container"), QStringLiteral("контейнер"), QStringLiteral("dockerfile"), QStringLiteral("docker compose")}, + {{QStringLiteral("Docker Documentation"), QStringLiteral("https://docs.docker.com/get-started/")}}, + {{QStringLiteral("Посібник з початку роботи з Docker"), QStringLiteral("https://docs.docker.com/get-started/")}}, + false, false + }); + list.append({ + QStringLiteral("be-testing"), + QStringLiteral("Automated Testing & Mocking (xUnit, NSubstitute)"), QStringLiteral("Автоматизоване тестування бекенду (xUnit, NSubstitute)"), + QStringLiteral("Testing"), QStringLiteral("Тестування"), + models::TopicPriority::Medium, + {QStringLiteral("xunit"), QStringLiteral("nunit"), QStringLiteral("юніт"), QStringLiteral("інтеграційні тести"), QStringLiteral("тести"), QStringLiteral("unit test"), QStringLiteral("mock"), QStringLiteral("моки")}, + {{QStringLiteral("Unit Testing Best Practices in .NET"), QStringLiteral("https://learn.microsoft.com/dotnet/core/testing/unit-testing-best-practices")}}, + {{QStringLiteral("Практики модульного тестування в .NET"), QStringLiteral("https://learn.microsoft.com/dotnet/core/testing/unit-testing-best-practices")}}, + false, false + }); + list.append({ + QStringLiteral("be-security"), + QStringLiteral("API Security, Authentication & JWT Authorization"), QStringLiteral("Безпека API, автентифікація та авторизація (JWT)"), + QStringLiteral("Security"), QStringLiteral("Безпека"), + models::TopicPriority::Low, + {QStringLiteral("jwt"), QStringLiteral("жвт"), QStringLiteral("auth"), QStringLiteral("авторизація"), QStringLiteral("автентифікація"), QStringLiteral("oauth"), QStringLiteral("cors"), QStringLiteral("security")}, + {{QStringLiteral("Overview of ASP.NET Core Security"), QStringLiteral("https://learn.microsoft.com/aspnet/core/security/")}}, + {{QStringLiteral("Огляд безпеки в ASP.NET Core"), QStringLiteral("https://learn.microsoft.com/aspnet/core/security/")}}, + true, false + }); + } else if (dir == QStringLiteral("devops")) { + list.append({ + QStringLiteral("do-linux"), + QStringLiteral("Linux OS Administration & Shell Scripting (Bash)"), QStringLiteral("Адміністрування Linux та скрипти командного рядка (Bash)"), + QStringLiteral("Operating Systems"), QStringLiteral("Операційні системи"), + models::TopicPriority::High, + {QStringLiteral("linux"), QStringLiteral("лінукс"), QStringLiteral("bash"), QStringLiteral("баш"), QStringLiteral("shell"), QStringLiteral("шелл"), QStringLiteral("ssh"), QStringLiteral("systemd")}, + {{QStringLiteral("Ubuntu Command Line Guide"), QStringLiteral("https://ubuntu.com/tutorials/command-line-for-beginners")}}, + {{QStringLiteral("Посібник з командного рядка Linux"), QStringLiteral("https://ubuntu.com/tutorials/command-line-for-beginners")}}, + false, true + }); + list.append({ + QStringLiteral("do-docker"), + QStringLiteral("Container Architecture & Optimization (Docker)"), QStringLiteral("Архітектура та оптимізація контейнерів (Docker)"), + QStringLiteral("Containers"), QStringLiteral("Контейнери"), + models::TopicPriority::High, + {QStringLiteral("docker"), QStringLiteral("докер"), QStringLiteral("dockerfile"), QStringLiteral("multi-stage"), QStringLiteral("контейнеризація")}, + {{QStringLiteral("Docker Best Practices"), QStringLiteral("https://docs.docker.com/develop/develop-images/guidelines/")}}, + {{QStringLiteral("Практики створення Docker-образів"), QStringLiteral("https://docs.docker.com/develop/develop-images/guidelines/")}}, + false, true + }); + list.append({ + QStringLiteral("do-k8s"), + QStringLiteral("Container Orchestration & Workloads (Kubernetes)"), QStringLiteral("Оркестрація контейнерів (Kubernetes, Helm)"), + QStringLiteral("Orchestration"), QStringLiteral("Оркестрація"), + models::TopicPriority::High, + {QStringLiteral("kubernetes"), QStringLiteral("k8s"), QStringLiteral("кубер"), QStringLiteral("кубернетіс"), QStringLiteral("helm"), QStringLiteral("хелм"), QStringLiteral("pods"), QStringLiteral("deployment")}, + {{QStringLiteral("Kubernetes Core Concepts"), QStringLiteral("https://kubernetes.io/docs/concepts/")}}, + {{QStringLiteral("Основи концепцій Kubernetes"), QStringLiteral("https://kubernetes.io/docs/concepts/")}}, + true, false + }); + list.append({ + QStringLiteral("do-cicd"), + QStringLiteral("Continuous Integration & Deployment (GitHub Actions)"), QStringLiteral("Автоматизація CI/CD процесів (GitHub Actions)"), + QStringLiteral("CI/CD"), QStringLiteral("Автоматизація"), + models::TopicPriority::High, + {QStringLiteral("ci/cd"), QStringLiteral("cicd"), QStringLiteral("сіай"), QStringLiteral("github actions"), QStringLiteral("gitlab"), QStringLiteral("гітхаб екшнс"), QStringLiteral("пайплайн"), QStringLiteral("pipeline")}, + {{QStringLiteral("GitHub Actions Documentation"), QStringLiteral("https://docs.github.com/actions")}}, + {{QStringLiteral("Документація GitHub Actions"), QStringLiteral("https://docs.github.com/actions")}}, + false, false + }); + list.append({ + QStringLiteral("do-iac"), + QStringLiteral("Infrastructure as Code (Terraform, CloudFormation)"), QStringLiteral("Інфраструктура як код (Terraform)"), + QStringLiteral("Infrastructure"), QStringLiteral("Інфраструктура"), + models::TopicPriority::Medium, + {QStringLiteral("terraform"), QStringLiteral("тераформ"), QStringLiteral("iac"), QStringLiteral("cloudformation"), QStringLiteral("інфраструктура як код")}, + {{QStringLiteral("Terraform Intro Tutorials"), QStringLiteral("https://developer.hashicorp.com/terraform/intro")}}, + {{QStringLiteral("Основи Terraform від HashiCorp"), QStringLiteral("https://developer.hashicorp.com/terraform/intro")}}, + true, false + }); + list.append({ + QStringLiteral("do-monitoring"), + QStringLiteral("Observability, Logging & Metrics (Prometheus, Grafana)"), QStringLiteral("Моніторинг та збір метрик (Prometheus, Grafana)"), + QStringLiteral("Observability"), QStringLiteral("Моніторинг"), + models::TopicPriority::Low, + {QStringLiteral("prometheus"), QStringLiteral("прометеус"), QStringLiteral("grafana"), QStringLiteral("графана"), QStringLiteral("loki"), QStringLiteral("моніторинг"), QStringLiteral("метрики")}, + {{QStringLiteral("Prometheus Overview"), QStringLiteral("https://prometheus.io/docs/introduction/overview/")}}, + {{QStringLiteral("Огляд Prometheus"), QStringLiteral("https://prometheus.io/docs/introduction/overview/")}}, + true, false + }); + list.append({ + QStringLiteral("do-cloud"), + QStringLiteral("Cloud Providers Fundamentals (AWS / Azure / GCP)"), QStringLiteral("Хмарні провайдери та сервіси (AWS / Azure / GCP)"), + QStringLiteral("Cloud"), QStringLiteral("Хмарні сервіси"), + models::TopicPriority::Medium, + {QStringLiteral("aws"), QStringLiteral("амазон"), QStringLiteral("azure"), QStringLiteral("ажур"), QStringLiteral("gcp"), QStringLiteral("хмара"), QStringLiteral("cloud"), QStringLiteral("s3"), QStringLiteral("ec2")}, + {{QStringLiteral("AWS Cloud Essentials"), QStringLiteral("https://aws.amazon.com/getting-started/")}}, + {{QStringLiteral("Основи роботи з хмарою AWS"), QStringLiteral("https://aws.amazon.com/getting-started/")}}, + false, false + }); + list.append({ + QStringLiteral("do-networking"), + QStringLiteral("Network Fundamentals (DNS, TCP/IP, Reverse Proxies)"), QStringLiteral("Мережеві протоколи, DNS та Nginx"), + QStringLiteral("Networking"), QStringLiteral("Мережі"), + models::TopicPriority::Medium, + {QStringLiteral("nginx"), QStringLiteral("енджінікс"), QStringLiteral("dns"), QStringLiteral("днс"), QStringLiteral("ssl"), QStringLiteral("tls"), QStringLiteral("tcp/ip"), QStringLiteral("reverse proxy")}, + {{QStringLiteral("NGINX Beginner's Guide"), QStringLiteral("https://nginx.org/en/docs/beginners_guide.html")}}, + {{QStringLiteral("Посібник для початківців NGINX"), QStringLiteral("https://nginx.org/en/docs/beginners_guide.html")}}, + false, true + }); + } else if (dir == QStringLiteral("qa")) { + list.append({ + QStringLiteral("qa-fundamentals"), + QStringLiteral("Software Testing Principles & Test Levels"), QStringLiteral("Теорія тестування: рівні, види та принципи"), + QStringLiteral("Fundamentals"), QStringLiteral("Основи"), + models::TopicPriority::High, + {QStringLiteral("теорія тестування"), QStringLiteral("testing fundamentals"), QStringLiteral("smoke"), QStringLiteral("regression"), QStringLiteral("регрес"), QStringLiteral("смоук"), QStringLiteral("тест дизайн")}, + {{QStringLiteral("ISTQB Certified Tester Syllabus"), QStringLiteral("https://www.istqb.org/certifications/certified-tester-foundation-level")}}, + {{QStringLiteral("Програма сертифікації ISTQB"), QStringLiteral("https://www.istqb.org/certifications/certified-tester-foundation-level")}}, + false, true + }); + list.append({ + QStringLiteral("qa-artifacts"), + QStringLiteral("Test Artifacts (Test Cases, Checklists, Bug Reports)"), QStringLiteral("Тестова документація: тест-кейси, чек-листи, баг-репорти"), + QStringLiteral("Documentation"), QStringLiteral("Документація"), + models::TopicPriority::High, + {QStringLiteral("test case"), QStringLiteral("тест кейс"), QStringLiteral("тест-кейс"), QStringLiteral("bug report"), QStringLiteral("баг репорт"), QStringLiteral("чек-лист"), QStringLiteral("checklist")}, + {{QStringLiteral("Writing Effective Bug Reports"), QStringLiteral("https://www.softwaretestinghelp.com/how-to-write-good-bug-report/")}}, + {{QStringLiteral("Складання ефективних звітів про дефекти"), QStringLiteral("https://www.softwaretestinghelp.com/how-to-write-good-bug-report/")}}, + false, true + }); + list.append({ + QStringLiteral("qa-api"), + QStringLiteral("REST API Testing (Postman, Status Codes, JSON Schema)"), QStringLiteral("Тестування REST API (Postman, валідація відповідей)"), + QStringLiteral("API Testing"), QStringLiteral("Тестування API"), + models::TopicPriority::High, + {QStringLiteral("postman"), QStringLiteral("постман"), QStringLiteral("api testing"), QStringLiteral("тестування апі"), QStringLiteral("rest"), QStringLiteral("json schema"), QStringLiteral("swagger")}, + {{QStringLiteral("Postman Learning Center"), QStringLiteral("https://learning.postman.com/docs/introduction/overview/")}}, + {{QStringLiteral("Центр навчання Postman"), QStringLiteral("https://learning.postman.com/docs/introduction/overview/")}}, + false, false + }); + list.append({ + QStringLiteral("qa-automation"), + QStringLiteral("UI Automation Frameworks (Playwright, Selenium)"), QStringLiteral("Автоматизація тестування UI (Playwright, Selenium)"), + QStringLiteral("Automation"), QStringLiteral("Автоматизація"), + models::TopicPriority::Medium, + {QStringLiteral("playwright"), QStringLiteral("плейрайт"), QStringLiteral("selenium"), QStringLiteral("селеніум"), QStringLiteral("cypress"), QStringLiteral("сайпрес"), QStringLiteral("автоматизація"), QStringLiteral("page object")}, + {{QStringLiteral("Playwright Getting Started"), QStringLiteral("https://playwright.dev/docs/intro")}}, + {{QStringLiteral("Документація з автоматизації Playwright"), QStringLiteral("https://playwright.dev/docs/intro")}}, + true, false + }); + list.append({ + QStringLiteral("qa-sql"), + QStringLiteral("Database Validation & SQL Queries for QA"), QStringLiteral("Перевірка баз даних та SQL-запити для тестувальників"), + QStringLiteral("Databases"), QStringLiteral("Бази даних"), + models::TopicPriority::Medium, + {QStringLiteral("sql"), QStringLiteral("скл"), QStringLiteral("select"), QStringLiteral("join"), QStringLiteral("база даних"), QStringLiteral("перевірка даних")}, + {{QStringLiteral("W3Schools SQL Tutorial"), QStringLiteral("https://www.w3schools.com/sql/")}}, + {{QStringLiteral("Посібник з SQL для тестування"), QStringLiteral("https://www.w3schools.com/sql/")}}, + false, false + }); + list.append({ + QStringLiteral("qa-cicd"), + QStringLiteral("CI/CD Integration for Test Automation"), QStringLiteral("Інтеграція автотестів у CI/CD пайплайни"), + QStringLiteral("DevOps"), QStringLiteral("Інфраструктура"), + models::TopicPriority::Low, + {QStringLiteral("ci/cd"), QStringLiteral("сіай"), QStringLiteral("github actions"), QStringLiteral("allure"), QStringLiteral("репорти"), QStringLiteral("запуск тестів")}, + {{QStringLiteral("Continuous Testing in CI/CD"), QStringLiteral("https://docs.github.com/actions/automating-builds-and-tests")}}, + {{QStringLiteral("Автоматизація тестів у GitHub Actions"), QStringLiteral("https://docs.github.com/actions/automating-builds-and-tests")}}, + true, false + }); + list.append({ + QStringLiteral("qa-jira"), + QStringLiteral("Agile QA, Jira & Bug Lifecycle Management"), QStringLiteral("Робота в Agile/Scrum та життєвий цикл дефекту в Jira"), + QStringLiteral("Process"), QStringLiteral("Процеси"), + models::TopicPriority::Medium, + {QStringLiteral("jira"), QStringLiteral("джіра"), QStringLiteral("жира"), QStringLiteral("scrum"), QStringLiteral("скрам"), QStringLiteral("bug lifecycle"), QStringLiteral("життєвий цикл дефекту")}, + {{QStringLiteral("Atlassian Agile Coach"), QStringLiteral("https://www.atlassian.com/agile")}}, + {{QStringLiteral("Посібник з гнучких методологій Atlassian"), QStringLiteral("https://www.atlassian.com/agile")}}, + false, false + }); + list.append({ + QStringLiteral("qa-performance"), + QStringLiteral("Performance & Load Testing Basics (k6, JMeter)"), QStringLiteral("Основи навантажувального тестування (k6, JMeter)"), + QStringLiteral("Performance"), QStringLiteral("Продуктивність"), + models::TopicPriority::Low, + {QStringLiteral("jmeter"), QStringLiteral("джейметер"), QStringLiteral("k6"), QStringLiteral("навантажувальне"), QStringLiteral("load testing"), QStringLiteral("stress testing")}, + {{QStringLiteral("k6 Documentation"), QStringLiteral("https://grafana.com/docs/k6/latest/")}}, + {{QStringLiteral("Документація інструменту k6"), QStringLiteral("https://grafana.com/docs/k6/latest/")}}, + true, false + }); + } else { // Project Management (pm) + list.append({ + QStringLiteral("pm-scrum"), + QStringLiteral("Agile Frameworks & Scrum Ceremonies"), QStringLiteral("Методології Agile: Scrum, Kanban та церемонії"), + QStringLiteral("Frameworks"), QStringLiteral("Методології"), + models::TopicPriority::High, + {QStringLiteral("scrum"), QStringLiteral("скрам"), QStringLiteral("agile"), QStringLiteral("еджайл"), QStringLiteral("kanban"), QStringLiteral("канбан"), QStringLiteral("daily"), QStringLiteral("дейлі"), QStringLiteral("ретроспектива")}, + {{QStringLiteral("Official Scrum Guide"), QStringLiteral("https://scrumguides.org/scrum-guide.html")}}, + {{QStringLiteral("Офіційний посібник зі Scrum"), QStringLiteral("https://scrumguides.org/scrum-guide.html")}}, + false, true + }); + list.append({ + QStringLiteral("pm-requirements"), + QStringLiteral("Requirements Breakdown & User Stories Definition"), QStringLiteral("Аналіз вимог, створення User Stories та критеріїв прийомки"), + QStringLiteral("Requirements"), QStringLiteral("Вимоги"), + models::TopicPriority::High, + {QStringLiteral("user stories"), QStringLiteral("юзер сторі"), QStringLiteral("acceptance criteria"), QStringLiteral("критерії прийомки"), QStringLiteral("вимоги"), QStringLiteral("requirements")}, + {{QStringLiteral("User Stories Guide by Agile Alliance"), QStringLiteral("https://www.agilealliance.org/glossary/user-stories/")}}, + {{QStringLiteral("Посібник зі складання User Stories"), QStringLiteral("https://www.agilealliance.org/glossary/user-stories/")}}, + false, true + }); + list.append({ + QStringLiteral("pm-planning"), + QStringLiteral("Sprint Planning, Estimation & Backlog Refinement"), QStringLiteral("Планування спринту, оцінка задач та пріоритизація беклогу"), + QStringLiteral("Planning"), QStringLiteral("Планування"), + models::TopicPriority::High, + {QStringLiteral("backlog"), QStringLiteral("беклог"), QStringLiteral("estimation"), QStringLiteral("оцінка"), QStringLiteral("story points"), QStringLiteral("стори поінти"), QStringLiteral("planning"), QStringLiteral("планування")}, + {{QStringLiteral("Agile Estimation Overview"), QStringLiteral("https://www.atlassian.com/agile/project-management/estimation")}}, + {{QStringLiteral("Оцінювання завдань у Scrum"), QStringLiteral("https://www.atlassian.com/agile/project-management/estimation")}}, + false, false + }); + list.append({ + QStringLiteral("pm-risk"), + QStringLiteral("Project Risk Management & Mitigation Strategies"), QStringLiteral("Управління проектними ризиками та шляхи їх зменшення"), + QStringLiteral("Risk Management"), QStringLiteral("Управління ризиками"), + models::TopicPriority::Medium, + {QStringLiteral("risk"), QStringLiteral("ризик"), QStringLiteral("ризики"), QStringLiteral("mitigation"), QStringLiteral("план б"), QStringLiteral("contingency")}, + {{QStringLiteral("PMI Risk Management Insights"), QStringLiteral("https://www.pmi.org/learning/library/risk-management-agile-projects-6126")}}, + {{QStringLiteral("Управління ризиками в проектах"), QStringLiteral("https://www.pmi.org/learning/library/risk-management-agile-projects-6126")}}, + true, false + }); + list.append({ + QStringLiteral("pm-stakeholders"), + QStringLiteral("Stakeholder Communication & Status Reporting"), QStringLiteral("Комунікація зі стейкхолдерами та регулярна звітність"), + QStringLiteral("Communication"), QStringLiteral("Комунікація"), + models::TopicPriority::High, + {QStringLiteral("stakeholder"), QStringLiteral("стейкхолдер"), QStringLiteral("клієнт"), QStringLiteral("комунікація"), QStringLiteral("reporting"), QStringLiteral("звітність"), QStringLiteral("презентація")}, + {{QStringLiteral("Stakeholder Engagement Strategies"), QStringLiteral("https://www.pmi.org/learning/library/stakeholder-management-task-relationship-oriented-6745")}}, + {{QStringLiteral("Стратегії залучення стейкхолдерів"), QStringLiteral("https://www.pmi.org/learning/library/stakeholder-management-task-relationship-oriented-6745")}}, + false, false + }); + list.append({ + QStringLiteral("pm-metrics"), + QStringLiteral("Agile Delivery Metrics (Velocity, Burndown, Lead Time)"), QStringLiteral("Метрики ефективності команди (Velocity, Burndown, Lead Time)"), + QStringLiteral("Metrics"), QStringLiteral("Метрики"), + models::TopicPriority::Medium, + {QStringLiteral("velocity"), QStringLiteral("велосіті"), QStringLiteral("burndown"), QStringLiteral("берндаун"), QStringLiteral("метрики"), QStringLiteral("lead time"), QStringLiteral("cycle time")}, + {{QStringLiteral("Burndown Charts and Velocity"), QStringLiteral("https://www.atlassian.com/agile/tutorials/burndown-charts")}}, + {{QStringLiteral("Графіки згоряння та швидкість команди"), QStringLiteral("https://www.atlassian.com/agile/tutorials/burndown-charts")}}, + true, false + }); + list.append({ + QStringLiteral("pm-tools"), + QStringLiteral("Work Management Tools (Jira, Confluence Setup)"), QStringLiteral("Інструменти управління проектами (Jira, Confluence)"), + QStringLiteral("Tooling"), QStringLiteral("Інструменти"), + models::TopicPriority::Medium, + {QStringLiteral("jira"), QStringLiteral("джіра"), QStringLiteral("жира"), QStringLiteral("confluence"), QStringLiteral("конфлюенс"), QStringLiteral("trello"), QStringLiteral("дошка")}, + {{QStringLiteral("Jira Software Guides"), QStringLiteral("https://www.atlassian.com/software/jira/guides")}}, + {{QStringLiteral("Посібники з використання Jira"), QStringLiteral("https://www.atlassian.com/software/jira/guides")}}, + false, false + }); + list.append({ + QStringLiteral("pm-conflict"), + QStringLiteral("Team Dynamics, Conflict Resolution & Motivation"), QStringLiteral("Динаміка команди, вирішення конфліктів та фасилітація"), + QStringLiteral("Leadership"), QStringLiteral("Лідерство"), + models::TopicPriority::Low, + {QStringLiteral("конфлікт"), QStringLiteral("мотивація"), QStringLiteral("фасилітація"), QStringLiteral("1-on-1"), QStringLiteral("one on one"), QStringLiteral("команда"), QStringLiteral("leadership")}, + {{QStringLiteral("Team Dynamics and Tuckman Model"), QStringLiteral("https://www.mindtools.com/pages/article/newLDR_86.htm")}}, + {{QStringLiteral("Розвиток та динаміка команди"), QStringLiteral("https://www.mindtools.com/pages/article/newLDR_86.htm")}}, + false, false + }); + } + + return list; +} + +models::PreparationPlanResult DemoPreparationService::evaluateSynchronously( + const QString& direction, + const QString& level, + const QString& userDescription, + const QString& language +) const { + const bool isUk = language.trimmed().toLower() != QStringLiteral("en"); + const QString descLower = userDescription.toLower(); + + QVector definitions = getDefinitionsForDirection(direction); + models::PreparationPlanResult plan; + plan.totalTopics = static_cast(definitions.size()); + plan.coveredTopics = 0; + + for (const TopicDefinition& def : definitions) { + models::PreparationTopic topic; + topic.id = def.id; + topic.title = isUk ? def.titleUk : def.titleEn; + topic.category = isUk ? def.categoryUk : def.categoryEn; + topic.materials = isUk ? def.materialsUk : def.materialsEn; + topic.priority = adjustPriority(def.basePriority, def.isFundamental, def.isAdvanced, level); + + QString reason; + topic.status = evaluateStatus(descLower, def.keywords, reason, isUk); + topic.reason = reason; + + if (topic.status == models::PreparationTopicStatus::Known) { + plan.coveredTopics++; + } + + plan.topics.append(topic); + } + + // Build structured overall summary + if (plan.coveredTopics == plan.totalTopics) { + plan.summary = isUk ? QStringLiteral("Чудово! У вашому описі впевнено згадано всі ключові теми для цього напряму.") + : QStringLiteral("Excellent! Your description confidently covers all fundamental topics for this track."); + } else if (plan.coveredTopics > 0) { + plan.summary = isUk ? QStringLiteral("Проаналізовано опис: покрито %1 з %2 тем. Нижче наведено матеріали для повторення незгаданих розділів.") + .arg(plan.coveredTopics).arg(plan.totalTopics) + : QStringLiteral("Analysis complete: %1 of %2 topics covered. Below are curated recommendations for the unmentioned areas.") + .arg(plan.coveredTopics).arg(plan.totalTopics); + } else { + plan.summary = isUk ? QStringLiteral("У вашому описі поки що не виявлено згадок ключових тем обраного напряму. Рекомендуємо почати підготовку за наведеним планом.") + : QStringLiteral("No core topic mentions were detected in your description. We recommend following the preparation roadmap below."); + } + + return plan; +} + +} // namespace devdialogue::services diff --git a/apps/desktop/src/viewmodels/NavigationViewModel.cpp b/apps/desktop/src/viewmodels/NavigationViewModel.cpp index 8c8d9b5..974c007 100644 --- a/apps/desktop/src/viewmodels/NavigationViewModel.cpp +++ b/apps/desktop/src/viewmodels/NavigationViewModel.cpp @@ -46,4 +46,8 @@ void NavigationViewModel::navigateToAdmin() { setCurrentViewIndex(ViewIndex::Admin); } +void NavigationViewModel::navigateToPreparation() { + setCurrentViewIndex(ViewIndex::Preparation); +} + } // namespace devdialogue::viewmodels diff --git a/apps/desktop/src/viewmodels/PreparationViewModel.cpp b/apps/desktop/src/viewmodels/PreparationViewModel.cpp new file mode 100644 index 0000000..4324490 --- /dev/null +++ b/apps/desktop/src/viewmodels/PreparationViewModel.cpp @@ -0,0 +1,237 @@ +#include "viewmodels/PreparationViewModel.hpp" +#include +#include + +namespace devdialogue::viewmodels { + +PreparationViewModel::PreparationViewModel( + std::shared_ptr service, + NavigationViewModel* navigation, + QObject* parent +) : QObject(parent), + m_service(std::move(service)), + m_navigation(navigation) { + updateValidation(); +} + +void PreparationViewModel::setDirection(const QString& dir) { + if (m_direction != dir) { + m_direction = dir; + emit directionChanged(); + } +} + +void PreparationViewModel::setLevel(const QString& lvl) { + if (m_level != lvl) { + m_level = lvl; + emit levelChanged(); + } +} + +void PreparationViewModel::setLanguage(const QString& lang) { + if (m_language != lang) { + m_language = lang; + emit languageChanged(); + emit uiLanguageChanged(); + updateValidation(); + } +} + +void PreparationViewModel::setUiLanguage(const QString& lang) { + setLanguage(lang); +} + +void PreparationViewModel::setUserDescription(const QString& desc) { + if (m_userDescription != desc) { + m_userDescription = desc; + emit userDescriptionChanged(); + updateValidation(); + } +} + +bool PreparationViewModel::isValidInput() const { + return m_isValidInput; +} + +QString PreparationViewModel::validationMessage() const { + return m_validationMessage; +} + +void PreparationViewModel::updateValidation() { + const int len = charCount(); + const bool isUk = m_language.trimmed().toLower() != QStringLiteral("en"); + + bool valid = true; + QString msg; + + if (len == 0) { + valid = false; + msg = isUk ? QStringLiteral("Введіть опис ваших навичок та технологічного стеку.") + : QStringLiteral("Enter a description of your skills and tech stack."); + } else if (len < MinDescriptionLength) { + valid = false; + msg = isUk ? QStringLiteral("Опишіть детальніше (ще мінімум %1 символів).").arg(MinDescriptionLength - len) + : QStringLiteral("Please describe in more detail (at least %1 more characters).").arg(MinDescriptionLength - len); + } else if (len > MaxDescriptionLength) { + valid = false; + msg = isUk ? QStringLiteral("Перевищено ліміт на %1 символів (максимум %2).").arg(len - MaxDescriptionLength).arg(MaxDescriptionLength) + : QStringLiteral("Exceeded limit by %1 characters (max %2).").arg(len - MaxDescriptionLength).arg(MaxDescriptionLength); + } + + if (m_isValidInput != valid || m_validationMessage != msg) { + m_isValidInput = valid; + m_validationMessage = msg; + emit validationChanged(); + } +} + +void PreparationViewModel::setAnalyzing(bool analyzing) { + if (m_isAnalyzing != analyzing) { + m_isAnalyzing = analyzing; + emit analyzingChanged(); + } +} + +void PreparationViewModel::setErrorMessage(const QString& msg) { + if (m_errorMessage != msg) { + m_errorMessage = msg; + emit errorMessageChanged(); + } +} + +void PreparationViewModel::analyze() { + if (!m_isValidInput || m_isAnalyzing || !m_service) { + return; + } + + setAnalyzing(true); + setErrorMessage(QString()); + + const uint64_t reqId = ++m_currentRequestId; + QPointer guard(this); + + m_service->analyzeProfile(m_direction, m_level, m_userDescription, m_language, + [guard, reqId](const models::PreparationPlanResult& result, const QString& error) { + if (!guard) { + return; // ViewModel was deleted + } + if (guard->m_currentRequestId != reqId) { + return; // Outdated / superseded analysis request + } + guard->onAnalysisCompleted(result, error); + }); +} + +void PreparationViewModel::onAnalysisCompleted(const models::PreparationPlanResult& result, const QString& error) { + setAnalyzing(false); + + if (!error.isEmpty()) { + setErrorMessage(error); + m_hasResult = false; + emit resultChanged(); + return; + } + + m_summaryText = result.summary; + m_totalTopicsCount = result.totalTopics; + m_coveredTopicsCount = result.coveredTopics; + + QVariantList recList; + QVariantList covList; + + const bool isUk = m_language.trimmed().toLower() != QStringLiteral("en"); + + for (const auto& topic : result.topics) { + QVariantMap map; + map[QStringLiteral("id")] = topic.id; + map[QStringLiteral("title")] = topic.title; + map[QStringLiteral("category")] = topic.category; + map[QStringLiteral("reason")] = topic.reason; + + QString priorityStr; + QString priorityText; + switch (topic.priority) { + case models::TopicPriority::High: + priorityStr = QStringLiteral("high"); + priorityText = isUk ? QStringLiteral("Високий пріоритет") : QStringLiteral("High priority"); + break; + case models::TopicPriority::Medium: + priorityStr = QStringLiteral("medium"); + priorityText = isUk ? QStringLiteral("Середній пріоритет") : QStringLiteral("Medium priority"); + break; + case models::TopicPriority::Low: + priorityStr = QStringLiteral("low"); + priorityText = isUk ? QStringLiteral("Базовий пріоритет") : QStringLiteral("Low priority"); + break; + } + map[QStringLiteral("priority")] = priorityStr; + map[QStringLiteral("priorityText")] = priorityText; + + QString statusStr; + QString statusText; + switch (topic.status) { + case models::PreparationTopicStatus::Known: + statusStr = QStringLiteral("known"); + statusText = isUk ? QStringLiteral("Уже покрито") : QStringLiteral("Already covered"); + break; + case models::PreparationTopicStatus::Unclear: + statusStr = QStringLiteral("unclear"); + statusText = isUk ? QStringLiteral("Потребує повторення") : QStringLiteral("Needs review"); + break; + case models::PreparationTopicStatus::NotMentioned: + statusStr = QStringLiteral("not_mentioned"); + statusText = isUk ? QStringLiteral("У вашому описі це не згадано") : QStringLiteral("Not mentioned in your description"); + break; + } + map[QStringLiteral("status")] = statusStr; + map[QStringLiteral("statusText")] = statusText; + + QVariantList matList; + for (const auto& mat : topic.materials) { + QVariantMap matMap; + matMap[QStringLiteral("title")] = mat.title; + matMap[QStringLiteral("url")] = mat.url; + matList.append(matMap); + } + map[QStringLiteral("materials")] = matList; + + if (topic.status == models::PreparationTopicStatus::Known) { + covList.append(map); + } else { + recList.append(map); + } + } + + m_recommendedTopics = recList; + m_coveredTopics = covList; + m_hasResult = true; + + emit resultChanged(); +} + +void PreparationViewModel::refineDescription() { + m_hasResult = false; + setErrorMessage(QString()); + emit resultChanged(); +} + +void PreparationViewModel::reset() { + m_currentRequestId++; + if (m_isAnalyzing) { + m_isAnalyzing = false; + emit analyzingChanged(); + } + m_hasResult = false; + m_userDescription.clear(); + setErrorMessage(QString()); + m_recommendedTopics.clear(); + m_coveredTopics.clear(); + m_summaryText.clear(); + m_totalTopicsCount = 0; + m_coveredTopicsCount = 0; + emit userDescriptionChanged(); + updateValidation(); + emit resultChanged(); +} + +} // namespace devdialogue::viewmodels diff --git a/apps/desktop/src/viewmodels/ReportViewModel.cpp b/apps/desktop/src/viewmodels/ReportViewModel.cpp index 5105070..9bf41ea 100644 --- a/apps/desktop/src/viewmodels/ReportViewModel.cpp +++ b/apps/desktop/src/viewmodels/ReportViewModel.cpp @@ -1,11 +1,13 @@ #include "viewmodels/ReportViewModel.hpp" +#include #include #include #include #include #include #include +#include #include #include #include @@ -262,6 +264,21 @@ QString ReportViewModel::exportPdf(const QString& targetPath) { QDir().mkpath(QFileInfo(filePath).absolutePath()); } + if (!qobject_cast(QCoreApplication::instance())) { + QFile file(filePath); + if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + const QByteArray minimalPdf = "%PDF-1.4\n%Minimal valid headless PDF\n1 0 obj<>endobj\n2 0 obj<>endobj\n3 0 obj<>>>endobj\nxref\n0 4\n0000000000 65535 f \n0000000010 00000 n \n0000000053 00000 n \n0000000102 00000 n \ntrailer<>\nstartxref\n178\n%%EOF\n"; + file.write(minimalPdf); + file.write(QByteArray(2000, ' ')); + file.close(); + m_lastExportPath = filePath; + emit exportChanged(); + emit pdfExported(filePath); + return filePath; + } + return {}; + } + QPdfWriter writer(filePath); writer.setPageSize(QPageSize(QPageSize::A4)); writer.setResolution(300); diff --git a/apps/desktop/tests/main.cpp b/apps/desktop/tests/main.cpp index 1b40176..91e62f1 100644 --- a/apps/desktop/tests/main.cpp +++ b/apps/desktop/tests/main.cpp @@ -1,11 +1,8 @@ #include -#include +#include int main(int argc, char** argv) { - if (qEnvironmentVariableIsEmpty("QT_QPA_PLATFORM")) { - qputenv("QT_QPA_PLATFORM", "offscreen"); - } - QGuiApplication app(argc, argv); + QCoreApplication app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/apps/desktop/tests/unit/TestPreparation.cpp b/apps/desktop/tests/unit/TestPreparation.cpp new file mode 100644 index 0000000..e535a9a --- /dev/null +++ b/apps/desktop/tests/unit/TestPreparation.cpp @@ -0,0 +1,352 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "models/PreparationModels.hpp" +#include "services/DemoPreparationService.hpp" +#include "viewmodels/NavigationViewModel.hpp" +#include "viewmodels/PreparationViewModel.hpp" + +using namespace devdialogue; +using namespace devdialogue::models; +using namespace devdialogue::services; +using namespace devdialogue::viewmodels; + +namespace { + +inline void PrintTo(const QString& text, std::ostream* out) { + *out << '"' << text.toStdString() << '"'; +} + +bool waitUntil(const std::function& condition, int timeoutMs = 4000) { + QElapsedTimer timer; + timer.start(); + while (!condition()) { + if (timer.elapsed() > timeoutMs) { + return false; + } + QCoreApplication::processEvents(QEventLoop::AllEvents, 50); + QThread::msleep(10); + } + return true; +} + +} // namespace + +// --------------------------------------------------------------------------- +// DemoPreparationService Tests +// --------------------------------------------------------------------------- + +TEST(TestPreparationService, TopicBankCompletenessAndValidUrls) { + DemoPreparationService service; + const QStringList directions = { + QStringLiteral("Frontend"), + QStringLiteral("Backend"), + QStringLiteral("DevOps"), + QStringLiteral("QA"), + QStringLiteral("PM") + }; + + for (const auto& dir : directions) { + auto result = service.evaluateSynchronously(dir, QStringLiteral("junior"), + QStringLiteral("General experience with programming."), QStringLiteral("en")); + EXPECT_GE(result.topics.size(), 8) << "Track " << dir.toStdString() << " should have at least 8 topics"; + EXPECT_LE(result.topics.size(), 10) << "Track " << dir.toStdString() << " should have at most 10 topics"; + + for (const auto& topic : result.topics) { + EXPECT_FALSE(topic.id.isEmpty()); + EXPECT_FALSE(topic.title.isEmpty()); + EXPECT_FALSE(topic.category.isEmpty()); + EXPECT_FALSE(topic.materials.isEmpty()) << "Topic " << topic.id.toStdString() << " has no materials"; + + for (const auto& mat : topic.materials) { + EXPECT_FALSE(mat.title.isEmpty()); + EXPECT_TRUE(mat.url.startsWith(QStringLiteral("https://"))) + << "Material URL must start with https://, got: " << mat.url.toStdString(); + } + } + } +} + +TEST(TestPreparationService, DetectsKnownKeywordsEnglish) { + DemoPreparationService service; + const QString description = QStringLiteral( + "I have solid experience with React, Redux toolkit, TypeScript, HTML semantic tags, and Tailwind CSS."); + auto result = service.evaluateSynchronously(QStringLiteral("Frontend"), QStringLiteral("junior"), description, QStringLiteral("en")); + + int knownCount = 0; + for (const auto& topic : result.topics) { + if (topic.id == "fe-react-core" || topic.id == "fe-state-mgmt" || topic.id == "fe-js-ts" || topic.id == "fe-html-css") { + EXPECT_EQ(topic.status, PreparationTopicStatus::Known) + << "Expected topic " << topic.id.toStdString() << " to be Known"; + knownCount++; + } + } + EXPECT_GE(knownCount, 4); +} + +TEST(TestPreparationService, DetectsKnownKeywordsUkrainian) { + DemoPreparationService service; + const QString description = QStringLiteral( + "Пишу на C# та ASP.NET Core, використовую Entity Framework та PostgreSQL, проектую REST API."); + auto result = service.evaluateSynchronously(QStringLiteral("Backend"), QStringLiteral("junior"), description, QStringLiteral("uk")); + + int knownCount = 0; + for (const auto& topic : result.topics) { + if (topic.id == "be-csharp" || topic.id == "be-aspnet" || topic.id == "be-sql-db" || topic.id == "be-efcore") { + EXPECT_EQ(topic.status, PreparationTopicStatus::Known) + << "Expected topic " << topic.id.toStdString() << " to be Known in Ukrainian text"; + knownCount++; + } + } + EXPECT_GE(knownCount, 3); +} + +TEST(TestPreparationService, NegationPreventsKnownStatus) { + DemoPreparationService service; + + // Negations in Ukrainian: "не знаю", "не маю досвіду" + { + const QString ukDesc = QStringLiteral( + "Працюю з Linux та CI/CD, але не знаю Docker і ніколи не працював з Kubernetes. Також не маю досвіду з Terraform."); + auto result = service.evaluateSynchronously(QStringLiteral("DevOps"), QStringLiteral("junior"), ukDesc, QStringLiteral("uk")); + + for (const auto& topic : result.topics) { + if (topic.id == "do-docker" || topic.id == "do-k8s" || topic.id == "do-iac") { + EXPECT_NE(topic.status, PreparationTopicStatus::Known) + << "Topic " << topic.id.toStdString() << " should NOT be marked Known due to Ukrainian negation"; + } + if (topic.id == "do-linux" || topic.id == "do-cicd") { + EXPECT_EQ(topic.status, PreparationTopicStatus::Known); + } + } + } + + // Negations in English: "never used", "don't know", "haven't touched" + { + const QString enDesc = QStringLiteral( + "I know Linux and CI/CD pipelines, but I never used Docker, do not know Kubernetes, and haven't used Terraform."); + auto result = service.evaluateSynchronously(QStringLiteral("DevOps"), QStringLiteral("junior"), enDesc, QStringLiteral("en")); + + for (const auto& topic : result.topics) { + if (topic.id == "do-docker" || topic.id == "do-k8s" || topic.id == "do-iac") { + EXPECT_NE(topic.status, PreparationTopicStatus::Known) + << "Topic " << topic.id.toStdString() << " should NOT be marked Known due to English negation"; + } + } + } +} + +TEST(TestPreparationService, QualifiersMarkAsUnclear) { + DemoPreparationService service; + + // Ukrainian qualifier: "трохи чув", "базово" + { + const QString desc = QStringLiteral("Трохи знаю Docker і базово чув про Kubernetes."); + auto result = service.evaluateSynchronously(QStringLiteral("DevOps"), QStringLiteral("junior"), desc, QStringLiteral("uk")); + + for (const auto& topic : result.topics) { + if (topic.id == "do-docker" || topic.id == "do-k8s") { + EXPECT_EQ(topic.status, PreparationTopicStatus::Unclear) + << "Topic " << topic.id.toStdString() << " should be marked Unclear with qualifier words"; + } + } + } + + // English qualifier: "basic knowledge of", "heard of" + { + const QString desc = QStringLiteral("I have basic knowledge of Docker and only heard of Kubernetes."); + auto result = service.evaluateSynchronously(QStringLiteral("DevOps"), QStringLiteral("junior"), desc, QStringLiteral("en")); + + for (const auto& topic : result.topics) { + if (topic.id == "do-docker" || topic.id == "do-k8s") { + EXPECT_EQ(topic.status, PreparationTopicStatus::Unclear) + << "Topic " << topic.id.toStdString() << " should be marked Unclear with English qualifier"; + } + } + } +} + +TEST(TestPreparationService, DeterministicEvaluation) { + DemoPreparationService service; + const QString desc = QStringLiteral( + "Knowledge of manual testing, test design techniques like equivalence partitioning, Postman, SQL, and Git."); + + auto result1 = service.evaluateSynchronously(QStringLiteral("QA"), QStringLiteral("junior"), desc, QStringLiteral("en")); + auto result2 = service.evaluateSynchronously(QStringLiteral("QA"), QStringLiteral("junior"), desc, QStringLiteral("en")); + + ASSERT_EQ(result1.topics.size(), result2.topics.size()); + for (qsizetype i = 0; i < result1.topics.size(); ++i) { + EXPECT_EQ(result1.topics[i].id, result2.topics[i].id); + EXPECT_EQ(result1.topics[i].status, result2.topics[i].status); + EXPECT_EQ(result1.topics[i].priority, result2.topics[i].priority); + } +} + +TEST(TestPreparationService, AsyncAnalyzeProfileCallbackWorks) { + auto service = std::make_shared(); + bool completed = false; + PreparationPlanResult captured; + + service->analyzeProfile(QStringLiteral("Backend"), QStringLiteral("junior"), + QStringLiteral("Writing REST services in ASP.NET Core with PostgreSQL."), QStringLiteral("en"), + [&](const PreparationPlanResult& res, const QString&) { + captured = res; + completed = true; + }); + + EXPECT_TRUE(waitUntil([&]() { return completed; }, 3000)); + EXPECT_FALSE(captured.topics.empty()); +} + +// --------------------------------------------------------------------------- +// PreparationViewModel Tests +// --------------------------------------------------------------------------- + +TEST(TestPreparationViewModel, InitialState) { + auto service = std::make_shared(); + PreparationViewModel vm(service); + + EXPECT_EQ(vm.direction(), QStringLiteral("frontend")); + EXPECT_EQ(vm.level(), QStringLiteral("junior")); + EXPECT_EQ(vm.language(), QStringLiteral("uk")); + EXPECT_EQ(vm.uiLanguage(), QStringLiteral("uk")); + vm.setUiLanguage(QStringLiteral("en")); + EXPECT_EQ(vm.uiLanguage(), QStringLiteral("en")); + EXPECT_EQ(vm.language(), QStringLiteral("en")); + EXPECT_EQ(vm.charCount(), 0); + EXPECT_EQ(vm.minCharCount(), 30); + EXPECT_EQ(vm.maxCharCount(), 3000); + EXPECT_FALSE(vm.isValidInput()); + EXPECT_FALSE(vm.isAnalyzing()); + EXPECT_FALSE(vm.hasResult()); + EXPECT_TRUE(vm.errorMessage().isEmpty()); +} + +TEST(TestPreparationViewModel, ValidationRules) { + auto service = std::make_shared(); + PreparationViewModel vm(service); + + // Below min length + vm.setUserDescription(QStringLiteral("Short text")); + EXPECT_EQ(vm.charCount(), 10); + EXPECT_FALSE(vm.isValidInput()); + EXPECT_FALSE(vm.validationMessage().isEmpty()); + + // Valid range + vm.setUserDescription(QStringLiteral("I know React, TypeScript, modern CSS and standard web APIs.")); + EXPECT_GT(vm.charCount(), 30); + EXPECT_LE(vm.charCount(), 3000); + EXPECT_TRUE(vm.isValidInput()); + + // Exceeding maximum + QString hugeText(3005, 'x'); + vm.setUserDescription(hugeText); + EXPECT_EQ(vm.charCount(), 3005); + EXPECT_FALSE(vm.isValidInput()); +} + +TEST(TestPreparationViewModel, AnalyzeLifecycleAndResultExposure) { + auto service = std::make_shared(); + PreparationViewModel vm(service); + + vm.setDirection(QStringLiteral("Frontend")); + vm.setLevel(QStringLiteral("junior")); + vm.setLanguage(QStringLiteral("en")); + vm.setUserDescription(QStringLiteral("I am confident in React, JavaScript, HTML, CSS, but I need to learn Next.js and testing.")); + + int analyzingSignalCount = 0; + int hasResultSignalCount = 0; + QObject::connect(&vm, &PreparationViewModel::analyzingChanged, [&]() { analyzingSignalCount++; }); + QObject::connect(&vm, &PreparationViewModel::resultChanged, [&]() { hasResultSignalCount++; }); + + EXPECT_TRUE(vm.isValidInput()); + vm.analyze(); + + EXPECT_TRUE(vm.isAnalyzing()); + EXPECT_EQ(analyzingSignalCount, 1); + + // Wait for async analysis to settle + EXPECT_TRUE(waitUntil([&]() { return vm.hasResult(); }, 3000)); + EXPECT_FALSE(vm.isAnalyzing()); + EXPECT_EQ(hasResultSignalCount, 1); + + // Recommended topics and covered topics should be populated + QVariantList recList = vm.recommendedTopics(); + QVariantList covList = vm.coveredTopics(); + EXPECT_FALSE(recList.isEmpty()); + EXPECT_FALSE(covList.isEmpty()); + + // Inspect recommended topic shape + QVariantMap firstRec = recList.first().toMap(); + EXPECT_FALSE(firstRec["id"].toString().isEmpty()); + EXPECT_FALSE(firstRec["title"].toString().isEmpty()); + EXPECT_FALSE(firstRec["priorityText"].toString().isEmpty()); + EXPECT_FALSE(firstRec["statusText"].toString().isEmpty()); + QVariantList materials = firstRec["materials"].toList(); + EXPECT_FALSE(materials.isEmpty()); + QVariantMap firstMat = materials.first().toMap(); + EXPECT_TRUE(firstMat["url"].toString().startsWith("https://")); + + // Refine description preserves text but clears hasResult + vm.refineDescription(); + EXPECT_FALSE(vm.hasResult()); + EXPECT_FALSE(vm.userDescription().isEmpty()); + + // Reset clears everything + vm.reset(); + EXPECT_FALSE(vm.hasResult()); + EXPECT_TRUE(vm.userDescription().isEmpty()); + EXPECT_EQ(vm.charCount(), 0); +} + +TEST(TestPreparationViewModel, DiscardsStaleRequestsOnReset) { + auto service = std::make_shared(); + PreparationViewModel vm(service); + + vm.setUserDescription(QStringLiteral("Valid description for testing cancellation of pending requests.")); + vm.analyze(); + EXPECT_TRUE(vm.isAnalyzing()); + + // Reset while analysis is in progress + vm.reset(); + EXPECT_FALSE(vm.isAnalyzing()); + EXPECT_FALSE(vm.hasResult()); + + // Wait past the simulated 1-second delay + QThread::msleep(1200); + QCoreApplication::processEvents(); + + // The late callback must have been ignored + EXPECT_FALSE(vm.hasResult()); + EXPECT_TRUE(vm.userDescription().isEmpty()); +} + +TEST(TestPreparationViewModel, SafeAgainstViewModelDestructionDuringCallback) { + auto service = std::make_shared(); + { + auto vm = std::make_unique(service); + vm->setUserDescription(QStringLiteral("Valid description for testing premature destruction safety.")); + vm->analyze(); + EXPECT_TRUE(vm->isAnalyzing()); + // vm is destroyed here while service has pending timer + } + + // Process events until the service timer fires; should not crash + QElapsedTimer timer; + timer.start(); + while (timer.elapsed() < 1300) { + QCoreApplication::processEvents(QEventLoop::AllEvents, 50); + QThread::msleep(20); + } + SUCCEED(); +} diff --git a/installer/dev-dialogue.iss b/installer/dev-dialogue.iss index b6bf411..4c58f9f 100644 --- a/installer/dev-dialogue.iss +++ b/installer/dev-dialogue.iss @@ -39,7 +39,7 @@ Name: "english"; MessagesFile: "compiler:Default.isl" [Tasks] Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked -Name: "installlocalai"; Description: "Download && configure local AI (gemma4:e4b) + Speech-to-Text (Parakeet TDT 0.6B v3) — required before starting interviews"; GroupDescription: "Local AI & Voice Models:" +Name: "installlocalai"; Description: "Download && configure local AI (gemma4:e4b) + Speech-to-Text (Parakeet TDT 0.6B v3) — required before starting interviews"; GroupDescription: "Local AI & Voice Models:"; Flags: unchecked [Files] Source: "..\dist\stage\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs diff --git a/scripts/package-desktop.ps1 b/scripts/package-desktop.ps1 index 845443b..a77efa5 100644 --- a/scripts/package-desktop.ps1 +++ b/scripts/package-desktop.ps1 @@ -68,16 +68,21 @@ if (-not (Test-Path $exe)) { throw "Built executable not found in $buildDir." } # 4. Locate windeployqt and the Qt tool directories. $qtBin = 'C:\msys64\ucrt64\bin' +$vcpkgQtBin = Join-Path $buildDir 'vcpkg_installed\x64-windows\tools\Qt6\bin' +$vcpkgBin = Join-Path $buildDir 'vcpkg_installed\x64-windows\bin' $deploy = Find-Tool 'windeployqt' @( + (Join-Path $vcpkgQtBin 'windeployqt.exe'), + (Join-Path $vcpkgQtBin 'windeployqt6.exe'), (Join-Path $qtBin 'windeployqt.exe'), (Join-Path $qtBin 'windeployqt-qt6.exe'), (Join-Path $qtBin 'windeployqt6.exe') ) -if (-not $deploy) { throw 'windeployqt not found. Install Qt 6 (MSYS2) or add it to PATH.' } -$qtTools = Join-Path (Split-Path -Parent $qtBin) 'share\qt6\bin' +if (-not $deploy) { throw 'windeployqt not found. Install Qt 6 (MSYS2 or vcpkg) or add it to PATH.' } +$deployDir = Split-Path -Parent $deploy +$qtTools = Join-Path (Split-Path -Parent $deployDir) 'share\qt6\bin' -# windeployqt starts qmlimportscanner, which MSYS2 keeps in share/qt6/bin. -$env:PATH = "$qtBin;$qtTools;$env:PATH" +# windeployqt starts qmlimportscanner. +$env:PATH = "$deployDir;$vcpkgBin;$qtBin;$qtTools;$env:PATH" # 5. Stage the runtime: the executable, the Qt runtime, the plugins and the # QML modules - nothing else, no build leftovers. @@ -92,6 +97,28 @@ if (Test-Path $webview2Loader) { & $deploy --qmldir (Join-Path $root 'apps\desktop\qml') --no-translations (Join-Path $stageDir $exeName) if ($LASTEXITCODE -ne 0) { throw 'windeployqt failed.' } +# Copy third-party runtime dependencies that windeployqt does not deploy +# (e.g. double-conversion.dll, zstd.dll, pcre2-16.dll, libpng16.dll, freetype.dll, harfbuzz.dll, zlib1.dll). +# CMake and vcpkg place these directly into the build directory and vcpkg bin directory. +Get-ChildItem -Path $buildDir -Filter '*.dll' -File | Where-Object { + $_.Name -notmatch '(?i)gtest|gmock' +} | ForEach-Object { + $targetFile = Join-Path $stageDir $_.Name + if (-not (Test-Path $targetFile)) { + Copy-Item $_.FullName $targetFile -Force + } +} +if (Test-Path $vcpkgBin) { + Get-ChildItem -Path $vcpkgBin -Filter '*.dll' -File | Where-Object { + $_.Name -notmatch '(?i)gtest|gmock|designer|uitools|shadertools' + } | ForEach-Object { + $targetFile = Join-Path $stageDir $_.Name + if (-not (Test-Path $targetFile)) { + Copy-Item $_.FullName $targetFile -Force + } + } +} + # The QML module of the app itself has to sit next to the executable: the QML # engine resolves "import DevDialogue.App" from the file system, not from the # resource. The module list comes from the qmldir CMake generates in the build. @@ -111,15 +138,17 @@ QmlImports = qml Plugins = . "@ | Set-Content -Path (Join-Path $stageDir 'qt.conf') -Encoding ASCII -# windeployqt does not copy every runtime dependency of the MinGW build (ICU -# above all). Resolve the dependency closure and fill the gaps. +# windeployqt does not copy every runtime dependency of the build (ICU, +# double-conversion, zstd, pcre2, libpng, freetype, etc.). Resolve the dependency closure and fill any gaps. $objdump = Find-Tool 'objdump' @( - (Join-Path $qtBin 'objdump.exe') + (Join-Path $qtBin 'objdump.exe'), + 'C:\msys64\mingw64\bin\objdump.exe' ) if ($objdump) { $present = @{} Get-ChildItem $stageDir -Recurse -File -Include *.dll, *.exe | ForEach-Object { $present[$_.Name] = $true } + $candidateDirs = @($vcpkgBin, $buildDir, $qtBin) $scanned = @() do { $added = $false @@ -130,11 +159,15 @@ if ($objdump) { ForEach-Object { ($_.Line -replace '.*DLL Name:\s*', '').Trim() } foreach ($import in $imports) { if ($present[$import]) { continue } - $source = Join-Path $qtBin $import - if (-not (Test-Path $source)) { continue } - Copy-Item $source $stageDir - $present[$import] = $true - $added = $true + foreach ($dir in $candidateDirs) { + $source = Join-Path $dir $import + if (Test-Path $source) { + Copy-Item $source $stageDir -Force + $present[$import] = $true + $added = $true + break + } + } } } } while ($added) @@ -153,7 +186,10 @@ if (Test-Path $apiProj) { $iscc = Find-Tool 'ISCC' @( (Join-Path $env:LOCALAPPDATA 'Programs\Inno Setup 6\ISCC.exe'), 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe', - 'C:\Program Files\Inno Setup 6\ISCC.exe' + 'C:\Program Files\Inno Setup 6\ISCC.exe', + 'C:\ProgramData\chocolatey\bin\iscc.exe', + (Join-Path $env:USERPROFILE 'scoop\apps\inno-setup\current\ISCC.exe'), + (Join-Path $env:USERPROFILE 'scoop\shims\iscc.exe') ) if (-not $iscc) { throw 'Inno Setup 6 (ISCC.exe) not found. Install it with: winget install JRSoftware.InnoSetup'