import apiService, { buildQuery } from "~/lib/api"; import jalaali from "jalaali-js"; export interface MetricResult { value: number | null; percent: number | null; nullReason?: string | null; unit?: string; } export interface PagedResult { items: T[]; totalCount: number; page: number; pageSize: number; } export interface ProjectManagementDistributions { importance: Record; strategicTheme: Record; innovationValue: Record; innovationDegree: Record; executivePhase: Record; averageRemainingDays: number | null; averageRenewedDuration: number | null; averageProgramDeviation: number | null; averageApprovedBudget: number | null; averageBudgetSpent: number | null; averageCostDeviation: number | null; } const innovationLabels: Record = { 1: "نوآوری دیجیتال", 2: "نوآوری در فرآیند", 3: "نوآوری در محصول", 4: "نوآوری سبز", 5: "نوآوری ساخت داخل", 6: "نوآوری در مدل کسب‌وکار", 7: "نوآوری نرم", 8: "نوآوری اجتماعی", }; export const actorTypeLabels: Record = { 1: "دانشگاه و مؤسسه پژوهشی", 2: "مشاور", 3: "شرکت دانش‌بنیان", 4: "استارتاپ", 5: "تأمین‌کننده", 6: "صندوق سرمایه‌گذاری", 7: "شتاب‌دهنده", 8: "مرکز نوآوری و رشد", }; function toApiDate(value?: string): string | undefined { if (!value) return undefined; if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value; const match = /^(\d{4})\/(\d{2})\/(\d{2})$/.exec(value); if (!match) return value; const jy = Number(match[1]); const jm = Number(match[2]); let jd = Number(match[3]); // Older calendar state used day 30 of Esfand for every year. Clamp it // instead of silently rolling the filter into Farvardin of the next year. if (jm === 12 && jd === 30 && !jalaali.isLeapJalaaliYear(jy)) jd = 29; const { gy, gm, gd } = jalaali.toGregorian( jy, jm, jd, ); return `${gy}-${String(gm).padStart(2, "0")}-${String(gd).padStart(2, "0")}`; } function reportQuery(startDate?: string, endDate?: string, extra: Record = {}) { return buildQuery({ startDate: toApiDate(startDate), endDate: toApiDate(endDate), ...extra, }); } function n(value: unknown): number { const number = Number(value ?? 0); return Number.isFinite(number) ? number : 0; } function metricValue(metric?: MetricResult | null) { return metric?.value ?? 0; } function metricPercent(metric?: MetricResult | null) { return metric?.percent ?? 0; } export const reportingApi = { dashboardOverview(startDate?: string, endDate?: string) { return apiService.get(`/dashboard/overview${reportQuery(startDate, endDate)}`); }, dashboardFinancial(startDate?: string, endDate?: string) { return apiService.get(`/dashboard/financial${reportQuery(startDate, endDate)}`); }, projectsByUnit(startDate?: string, endDate?: string) { return apiService.get(`/reports/projects/by-unit${reportQuery(startDate, endDate)}`); }, async projectManagement(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string): Promise> { const result = await apiService.get>(`/reports/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection, })}`); return { ...result, items: result.items.map((x) => ({ project_id: x.id, project_no: x.projectNumber, title: x.title, importance_project: x.importance, strategic_theme: x.strategicTheme, value_technology_and_innovation: x.innovationValue, type_of_innovation: innovationLabels[x.innovationType] ?? "نامشخص", innovation: x.innovationDegree, person_executing: x.executingPerson, excellent_observer: x.excellentObserver, observer: x.observer, moderator: x.executor, executive_phase: x.executivePhase, start_date: x.startDate, end_date: x.endDate, renewed_duration: x.renewedDurationDays, done_date: x.doneDate, deviation_from_program: x.programDeviation, approved_budget: x.approvedBudget, budget_spent: x.budgetSpent, cost_deviation: x.costDeviation, })), }; }, projectManagementDistributions(startDate?: string, endDate?: string) { return apiService.get( `/reports/projects/distributions${reportQuery(startDate, endDate)}`, ); }, async digitalProjects(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string) { const result = await apiService.get>(`/reports/innovation/digital/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection })}`); return { ...result, items: result.items.map((x) => ({ WorkflowID: x.id, project_id: x.id, project_no: x.projectNumber ?? x.projectNo ?? x.project_no ?? "-", title: x.title, project_status: x.businessStatus ?? "-", project_rating: x.rating ?? 0, actual_progress_percent: x.actualProgressPercent ?? x.ActualProgressPercent ?? x.actual_progress_percent ?? null, project_description: x.description ?? "", digital_competence: x.digitalCompetence, originality_digital_solution: x.solutionOriginality, digital_puberty_elements: x.digitalMaturityElement, digital_capability: x.digitalCapability, operational_plan: x.operationalPlan, desired_strategy: x.desiredStrategy, innovation_cost_reduction: n(x.preInnovationCost) - n(x.innovationCost), reduce_costs_percent: n(x.preInnovationCost) === 0 ? 0 : ((n(x.preInnovationCost) - n(x.innovationCost)) * 100) / n(x.preInnovationCost), })) }; }, digitalReport(startDate?: string, endDate?: string, projectIds?: string[]) { return apiService.get(`/reports/innovation/digital${reportQuery(startDate, endDate, { projectIds })}`); }, async greenProjects(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string) { const result = await apiService.get>(`/reports/innovation/green/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection })}`); return { ...result, items: result.items.map((x) => ({ WorkflowID: x.id, project_id: x.id, project_no: x.projectNumber ?? x.projectNo ?? x.project_no ?? "-", title: x.title, project_status: x.businessStatus ?? "-", project_rating: x.rating ?? 0, project_description: x.description ?? "", start_date: x.startDate, done_date: x.doneDate, approved_budget: x.approvedBudget ?? 0, observer: x.observer ?? "-", })) }; }, greenReport(startDate?: string, endDate?: string, projectIds?: string[]) { return apiService.get(`/reports/innovation/green${reportQuery(startDate, endDate, { projectIds })}`); }, async domesticProjects(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string) { const result = await apiService.get>(`/reports/innovation/domestic/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection })}`); return { ...result, items: result.items.map((x) => ({ WorkflowID: x.id, project_id: x.id, project_no: x.projectNumber ?? x.projectNo ?? x.project_no ?? "-", title: x.title, project_status: x.businessStatus ?? "-", project_rating: x.rating ?? 0, project_description: x.description ?? "", approved_budget: 0, done_date: null, observer: "-", start_date: x.startDate, complexity_level: x.complexityLevel ?? "", collaboration_model: x.collaborationModel ?? "", developer_team_role: x.developerTeamRole ?? "", role_company_staff: x.companyStaffRole ?? "", number_employees_involved: x.employeesInvolved ?? null, participants_full_name: x.participantsFullName ?? "", technology_maturity_level: x.technologyMaturityLevel ?? "", })) }; }, domesticReport(startDate?: string, endDate?: string, projectIds?: string[]) { return apiService.get(`/reports/innovation/domestic${reportQuery(startDate, endDate, { projectIds })}`); }, async technologyParameters(projectId: string) { const items = await apiService.get(`/projects/${encodeURIComponent(projectId)}/technology-parameters`); return items.map((x) => ({ WorkflowID: x.id, technology_parameter_title: x.title, domestic_technology_parameter_value: x.domesticValue, foreign_technology_parameter_value: x.foreignValue })); }, async processProjects(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string) { const result = await apiService.get>(`/reports/innovation/process/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection })}`); return { ...result, items: result.items.map((x) => ({ project_id: x.id, project_no: x.projectNumber, title: x.title, project_status: x.businessStatus ?? "-", project_rating: x.rating ?? 0, project_description: x.description ?? "", start_date: x.startDate, done_date: x.doneDate, approved_budget: x.approvedBudget ?? 0, observer: x.observer ?? "-", reduce_prevention_production_stops: n(x.productionStopBefore) - n(x.productionStopAfter), throat_removal: x.removedBottleneck ? "بله" : "خیر", amount_currency_reduction: n(x.foreignCurrencyCostBefore) - n(x.foreignCurrencyCostAfter), Reduce_rate_failure: n(x.breakdownCountBefore) - n(x.breakdownCountAfter), })) }; }, processReport(startDate?: string, endDate?: string, projectIds?: string[]) { return apiService.get(`/reports/innovation/process${reportQuery(startDate, endDate, { projectIds })}`); }, async productProjects(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number, sortBy?: string, sortDirection?: string) { const result = await apiService.get>(`/reports/innovation/product/projects${reportQuery(startDate, endDate, { page, pageSize, sortBy, sortDirection })}`); return { ...result, items: result.items.map((x) => ({ WorkflowID: x.id, project_id: x.id, project_no: x.projectNumber, title: x.title, project_status: x.businessStatus ?? "-", current_status: x.currentStatus, project_rating: x.rating ?? 0, project_description: x.description ?? "", product_title: x.productTitle, developed_technology_type: x.developedTechnologyType, obtained_standard_title: x.obtainedStandardTitle, knowledge_based_certificate_obtained: x.knowledgeBasedCertificateObtained ? "بله" : "خیر", knowledge_based_certificate_number: x.certificateNumber ?? "", certificate_obtain_date: x.certificateDate, issuing_authority: x.issuingAuthority ?? "", })) }; }, productReport(startDate?: string, endDate?: string, projectIds?: string[]) { return apiService.get(`/reports/innovation/product${reportQuery(startDate, endDate, { projectIds })}`); }, productSummary(projectId: string) { return apiService.get(`/projects/${encodeURIComponent(projectId)}/product-summary`); }, async ideas(startDate: string | undefined, endDate: string | undefined, page: number, pageSize: number) { const result = await apiService.get>(`/reports/ideas/items${reportQuery(startDate, endDate, { page, pageSize })}`); return { ...result, items: result.items.map((x) => ({ idea_id: x.id, idea_title: x.title, idea_registration_date: x.registrationDate, idea_status: x.ideaStatus, increased_revenue: x.increasedRevenue ?? 0, full_name: x.innovatorFullName, personnel_number: x.personnelNumber ?? "", management: x.management ?? "", deputy: x.deputy ?? "", innovator_team_members: x.teamMembers ?? "", innovation_type: x.innovationType ?? "", idea_originality: x.originality ?? "", idea_axis: x.axis ?? "", idea_description: x.description ?? "", idea_current_status_description: x.currentStatusDescription ?? "", idea_execution_benefits: x.executionBenefits ?? "", process_improvements: x.processImprovements ?? "", })) }; }, ideaReport(startDate?: string, endDate?: string) { return apiService.get(`/reports/ideas${reportQuery(startDate, endDate)}`); }, ideasByAuthor(startDate?: string, endDate?: string) { return apiService.get(`/reports/ideas/by-author${reportQuery(startDate, endDate)}`); }, ideasByStatus(startDate?: string, endDate?: string) { return apiService.get(`/reports/ideas/by-status${reportQuery(startDate, endDate)}`); }, themes(startDate?: string, endDate?: string) { return apiService.get(`/reports/alignment/themes${reportQuery(startDate, endDate)}`); }, values(startDate?: string, endDate?: string, strategicThemeId?: string) { return apiService.get(`/reports/alignment/values${reportQuery(startDate, endDate, { strategicThemeId })}`); }, ecosystemCounts(startDate?: string, endDate?: string) { return apiService.get(`/ecosystem/counts${reportQuery(startDate, endDate)}`); }, ecosystemActorSummary(startDate?: string, endDate?: string) { return apiService.get(`/ecosystem/actors/summary${reportQuery(startDate, endDate)}`); }, ecosystemGraph(startDate?: string, endDate?: string) { return apiService.get(`/ecosystem/graph${reportQuery(startDate, endDate)}`); }, actor(id: string) { return apiService.get(`/actors/${encodeURIComponent(id)}`); }, legacyDashboardOverview(x: any) { return { registered_innovation_technology_idea: x.registeredIdeaCount, ongoing_innovation_technology_ideas: x.executedIdeaCount, technology_innovation_based_revenue_growth: String(metricValue(x.newProductsRevenueShare)), technology_innovation_based_revenue_growth_percent: metricPercent(x.newProductsRevenueShare), technology_innovation_based_cost_reduction: String(metricValue(x.innovationCostReduction)), technology_innovation_based_cost_reduction_percent: metricPercent(x.innovationCostReduction), innovation_budget_achievement_percent: metricPercent(x.innovationBudgetAchievement), approved_innovation_budget_achievement_ratio: String(x.approvedInnovationBudget ?? 0), allocated_innovation_budget_achievement_ratio: String(x.allocatedInnovationBudget ?? 0), }; }, legacyDashboardFinancial(x: any) { return { technology_intensity: metricPercent(x.researchAndDevelopmentRatio), executed_project: x.projects?.completed ?? 0, in_progress_project: x.projects?.inProgress ?? 0, planned_project: x.projects?.proposal ?? 0, printed_books_count: x.content?.books ?? 0, registered_patents_count: x.content?.patents ?? 0, published_reports_count: x.content?.publications ?? 0, printed_articles_count: x.content?.articles ?? 0, attended_conferences_count: x.content?.conferences ?? 0, attended_events_count: x.content?.eventParticipations ?? 0, attended_exhibitions_count: x.content?.exhibitions ?? 0, organized_events_count: x.content?.hostedEvents ?? 0, }; }, };