All files / src/platform/reports report.service.ts

0% Statements 0/89
0% Branches 0/62
0% Functions 0/13
0% Lines 0/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import {
  Injectable,
  BadRequestException,
  NotFoundException,
  Logger,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import {
  ReportDataSource,
  ReportDefinition,
  ReportSchedule,
  ReportRun,
} from './schemas/report.schema';
import { ReportDataSourceProvider } from './report-data-source-provider.interface';
import { User } from '../user/schemas/user.schema';
import { StorageHubService } from '../storage/storage-hub.service';
 
const ALLOWED_OPERATORS = [
  '==',
  '!=',
  '>',
  '<',
  '>=',
  '<=',
  'contains',
  'startsWith',
  'endsWith',
];
 
@Injectable()
export class ReportService {
  private readonly logger = new Logger(ReportService.name);
  private readonly providers = new Map<string, ReportDataSourceProvider>();
 
  constructor(
    @InjectModel(ReportDataSource.name)
    private readonly sourceModel: Model<ReportDataSource>,
    @InjectModel(ReportDefinition.name)
    private readonly defModel: Model<ReportDefinition>,
    @InjectModel(ReportSchedule.name)
    private readonly scheduleModel: Model<ReportSchedule>,
    @InjectModel(ReportRun.name) private readonly runModel: Model<ReportRun>,
    @InjectModel(User.name) private readonly userModel: Model<User>,
    @InjectQueue('report.generate') private readonly generateQueue: Queue,
    private readonly storageService: StorageHubService,
  ) {
    // Register local default user provider
    this.registerProvider({
      dataSourceKey: 'users',
      executeQuery: async (tenantId, queryConfig, limit) => {
        const where: any = { tenantId };
        if (queryConfig.filters) {
          for (const f of queryConfig.filters) {
            if (!ALLOWED_OPERATORS.includes(f.operator)) continue;
            if (f.field === 'email') {
              where.email =
                f.operator === 'contains'
                  ? { $regex: f.value, $options: 'i' }
                  : f.value;
            }
          }
        }
        return this.userModel.find(where).limit(limit).lean().exec();
      },
    });
  }
 
  registerProvider(provider: ReportDataSourceProvider) {
    this.providers.set(provider.dataSourceKey, provider);
    this.logger.log(
      `Registered report data source provider: ${provider.dataSourceKey}`,
    );
  }
 
  async getSources(): Promise<any[]> {
    return this.sourceModel.find({ isActive: true }).lean().exec();
  }
 
  async createReport(params: {
    tenantId: string;
    name: string;
    description?: string;
    dataSourceKey: string;
    queryConfig: any;
    chartConfig?: any;
    isShared?: boolean;
    createdBy: string;
  }): Promise<any> {
    const source = await this.sourceModel
      .findOne({ key: params.dataSourceKey })
      .lean()
      .exec();
    if (!source && !this.providers.has(params.dataSourceKey)) {
      throw new BadRequestException(
        `Data source not found or registered: ${params.dataSourceKey}`,
      );
    }
 
    const report = await this.defModel.create({
      tenantId: params.tenantId,
      name: params.name,
      description: params.description,
      dataSourceKey: params.dataSourceKey,
      queryConfig: params.queryConfig,
      chartConfig: params.chartConfig || null,
      isShared: params.isShared || false,
      createdBy: params.createdBy,
    });
 
    return { ...report.toObject(), id: (report as any)._id.toString() };
  }
 
  async getReports(tenantId: string, userId: string): Promise<any[]> {
    return this.defModel
      .find({
        tenantId,
        $or: [{ createdBy: userId }, { isShared: true }],
      })
      .lean()
      .exec();
  }
 
  async getReport(id: string, tenantId: string): Promise<any> {
    const report = await this.defModel
      .findOne({ _id: id, tenantId })
      .lean()
      .exec();
    if (!report) throw new NotFoundException('Report not found');
    return { ...report, id: (report as any)._id.toString() };
  }
 
  async executeReport(
    id: string,
    tenantId: string,
    userId: string,
  ): Promise<any> {
    const report = await this.defModel
      .findOne({ _id: id, tenantId })
      .lean()
      .exec();
    if (!report) throw new NotFoundException('Report not found');
 
    const provider = this.providers.get(report.dataSourceKey);
    if (!provider) {
      throw new BadRequestException(
        `No active query handler registered for data source: ${report.dataSourceKey}`,
      );
    }
 
    const startTime = Date.now();
    const data = await provider.executeQuery(
      tenantId,
      report.queryConfig,
      report.maxResultCount,
    );
    const duration = Date.now() - startTime;
 
    // Create background log
    await this.runModel.create({
      reportId: id,
      tenantId,
      status: 'COMPLETED',
      rowCount: data.length,
      executionTimeMs: duration,
      triggeredBy: userId,
    });
 
    return { data, meta: { executionTimeMs: duration, count: data.length } };
  }
 
  async queueReportRun(
    id: string,
    tenantId: string,
    userId: string,
  ): Promise<any> {
    const run = await this.runModel.create({
      reportId: id,
      tenantId,
      status: 'PENDING',
      triggeredBy: userId,
    });
 
    await this.generateQueue.add('generate', {
      runId: (run as any)._id.toString(),
      reportId: id,
      tenantId,
      userId,
    });
 
    return { runId: (run as any)._id.toString(), status: 'PENDING' };
  }
 
  async processGenerateReport(jobData: {
    runId: string;
    reportId: string;
    tenantId: string;
    userId: string;
  }) {
    const startTime = Date.now();
    const run = await this.runModel.findById(jobData.runId).exec();
    if (!run) return;
 
    try {
      run.status = 'RUNNING';
      await run.save();
 
      const result = await this.executeReport(
        jobData.reportId,
        jobData.tenantId,
        jobData.userId,
      );
 
      // Convert to CSV
      const csvBuffer = this.convertToCsv(result.data);
      const filename = `report_${jobData.reportId}_${Date.now()}.csv`;
      const storageKey = `tenants/${jobData.tenantId}/reports/${filename}`;
 
      const uploaded = await this.storageService.uploadFile(jobData.tenantId, {
        key: storageKey,
        filename,
        mimeType: 'text/csv',
        buffer: csvBuffer,
      });
 
      const downloadUrl = await this.storageService.getDownloadUrl(
        jobData.tenantId,
        storageKey,
      );
 
      run.status = 'COMPLETED';
      run.rowCount = result.meta.count;
      run.executionTimeMs = Date.now() - startTime;
      run.generatedFileUrl = downloadUrl;
      await run.save();
    } catch (err: any) {
      run.status = 'FAILED';
      run.error = err.message || 'Unknown error';
      await run.save();
    }
  }
 
  async getRuns(reportId: string, tenantId: string): Promise<any[]> {
    return this.runModel
      .find({ reportId, tenantId })
      .sort({ createdAt: -1 })
      .lean()
      .exec();
  }
 
  private convertToCsv(data: any[]): Buffer {
    if (!data || data.length === 0) return Buffer.from('');
 
    const headers = Object.keys(data[0]);
    const csvRows = [headers.join(',')];
 
    for (const row of data) {
      const values = headers.map((header) => {
        const val =
          row[header] !== null && row[header] !== undefined ? row[header] : '';
        return `"${String(val).replace(/"/g, '""')}"`;
      });
      csvRows.push(values.join(','));
    }
 
    return Buffer.from(csvRows.join('\n'));
  }
}