Spaces:
Building
Building
File size: 14,198 Bytes
9f79da5 d7629a6 |
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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatDividerModule } from '@angular/material/divider';
import { ApiService, Project } from '../../services/api.service';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { authInterceptor } from '../../interceptors/auth.interceptor';
import { Subject, takeUntil } from 'rxjs';
// Dynamic imports for dialogs
const loadProjectEditDialog = () => import('../../dialogs/project-edit-dialog/project-edit-dialog.component');
const loadVersionEditDialog = () => import('../../dialogs/version-edit-dialog/version-edit-dialog.component');
const loadConfirmDialog = () => import('../../dialogs/confirm-dialog/confirm-dialog.component');
@Component({
selector: 'app-projects',
standalone: true,
imports: [
CommonModule,
FormsModule,
HttpClientModule,
MatTableModule,
MatProgressBarModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatInputModule,
MatButtonToggleModule,
MatCardModule,
MatChipsModule,
MatIconModule,
MatMenuModule,
MatDividerModule,
MatDialogModule,
MatSnackBarModule
],
providers: [
ApiService
],
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit, OnDestroy {
projects: Project[] = [];
filteredProjects: Project[] = [];
searchTerm = '';
showDeleted = false;
viewMode: 'list' | 'card' = 'card';
loading = false;
message = '';
isError = false;
// For table view
displayedColumns: string[] = ['name', 'caption', 'versions', 'status', 'lastUpdate', 'actions'];
// Memory leak prevention
private destroyed$ = new Subject<void>();
constructor(
private apiService: ApiService,
private dialog: MatDialog,
private snackBar: MatSnackBar
) {}
ngOnInit() {
this.loadProjects();
this.loadEnvironment();
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
isSparkTabVisible(): boolean {
// Environment bilgisini cache'ten al (eğer varsa)
const env = localStorage.getItem('flare_environment');
if (env) {
const config = JSON.parse(env);
return !config.work_mode?.startsWith('gpt4o');
}
return true; // Default olarak göster
}
loadProjects() {
this.loading = true;
this.apiService.getProjects(this.showDeleted)
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: (projects) => {
this.projects = projects || [];
this.applyFilter();
this.loading = false;
},
error: (error) => {
this.loading = false;
this.showMessage('Failed to load projects', true);
console.error('Load projects error:', error);
}
});
}
private loadEnvironment() {
this.apiService.getEnvironment()
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: (env) => {
localStorage.setItem('flare_environment', JSON.stringify(env));
},
error: (err) => {
console.error('Failed to load environment:', err);
}
});
}
applyFilter() {
this.filteredProjects = this.projects.filter(project => {
const matchesSearch = !this.searchTerm ||
project.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
(project.caption || '').toLowerCase().includes(this.searchTerm.toLowerCase());
const matchesDeleted = this.showDeleted || !project.deleted;
return matchesSearch && matchesDeleted;
});
}
filterProjects() {
this.applyFilter();
}
onSearchChange() {
this.applyFilter();
}
onShowDeletedChange() {
this.loadProjects();
}
async createProject() {
try {
const { default: ProjectEditDialogComponent } = await loadProjectEditDialog();
const dialogRef = this.dialog.open(ProjectEditDialogComponent, {
width: '500px',
data: { mode: 'create' }
});
dialogRef.afterClosed()
.pipe(takeUntil(this.destroyed$))
.subscribe(result => {
if (result) {
this.loadProjects();
this.showMessage('Project created successfully', false);
}
});
} catch (error) {
console.error('Failed to load dialog:', error);
this.showMessage('Failed to open dialog', true);
}
}
async editProject(project: Project, event?: Event) {
if (event) {
event.stopPropagation();
}
try {
const { default: ProjectEditDialogComponent } = await loadProjectEditDialog();
const dialogRef = this.dialog.open(ProjectEditDialogComponent, {
width: '500px',
data: { mode: 'edit', project: { ...project } }
});
dialogRef.afterClosed()
.pipe(takeUntil(this.destroyed$))
.subscribe(result => {
if (result) {
// Listeyi güncelle
const index = this.projects.findIndex(p => p.id === result.id);
if (index !== -1) {
this.projects[index] = result;
this.applyFilter(); // Filtreyi yeniden uygula
} else {
this.loadProjects(); // Bulunamazsa tüm listeyi yenile
}
this.showMessage('Project updated successfully', false);
}
});
} catch (error) {
console.error('Failed to load dialog:', error);
this.showMessage('Failed to open dialog', true);
}
}
toggleProject(project: Project, event?: Event) {
if (event) {
event.stopPropagation();
}
const action = project.enabled ? 'disable' : 'enable';
const confirmMessage = `Are you sure you want to ${action} "${project.caption}"?`;
this.confirmAction(
`${action.charAt(0).toUpperCase() + action.slice(1)} Project`,
confirmMessage,
action.charAt(0).toUpperCase() + action.slice(1),
!project.enabled
).then(confirmed => {
if (confirmed) {
this.apiService.toggleProject(project.id)
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: (result) => {
project.enabled = result.enabled;
this.showMessage(
`Project ${project.enabled ? 'enabled' : 'disabled'} successfully`,
false
);
},
error: (error) => this.handleUpdateError(error, project.caption)
});
}
});
}
async manageVersions(project: Project, event?: Event) {
if (event) {
event.stopPropagation();
}
try {
const { default: VersionEditDialogComponent } = await loadVersionEditDialog();
const dialogRef = this.dialog.open(VersionEditDialogComponent, {
width: '90vw',
maxWidth: '1200px',
height: '90vh',
data: { project }
});
dialogRef.afterClosed()
.pipe(takeUntil(this.destroyed$))
.subscribe(result => {
if (result) {
this.loadProjects();
}
});
} catch (error) {
console.error('Failed to load dialog:', error);
this.showMessage('Failed to open dialog', true);
}
}
deleteProject(project: Project, event?: Event) {
if (event) {
event.stopPropagation();
}
const hasVersions = project.versions && project.versions.length > 0;
const message = hasVersions ?
`Project "${project.name}" has ${project.versions.length} version(s). Are you sure you want to delete it?` :
`Are you sure you want to delete project "${project.name}"?`;
this.confirmAction('Delete Project', message, 'Delete', true).then(confirmed => {
if (confirmed) {
this.apiService.deleteProject(project.id)
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: () => {
this.showMessage('Project deleted successfully', false);
this.loadProjects();
},
error: (error) => {
const message = error.error?.detail || 'Failed to delete project';
this.showMessage(message, true);
}
});
}
});
}
exportProject(project: Project, event?: Event) {
if (event) {
event.stopPropagation();
}
this.apiService.exportProject(project.id)
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: (data) => {
// Create and download file
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${project.name}_export_${new Date().getTime()}.json`;
link.click();
window.URL.revokeObjectURL(url);
this.showMessage('Project exported successfully', false);
},
error: (error) => {
this.showMessage('Failed to export project', true);
console.error('Export error:', error);
}
});
}
importProject() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (event: any) => {
const file = event.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
this.apiService.importProject(data)
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: () => {
this.showMessage('Project imported successfully', false);
this.loadProjects();
},
error: (error) => {
const message = error.error?.detail || 'Failed to import project';
this.showMessage(message, true);
}
});
} catch (error) {
this.showMessage('Invalid file format', true);
}
};
input.click();
}
getPublishedCount(project: Project): number {
return project.versions?.filter(v => v.published).length || 0;
}
getRelativeTime(timestamp: string | undefined): string {
if (!timestamp) return 'Never';
const date = new Date(timestamp);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 60) return `${diffMins} minutes ago`;
if (diffHours < 24) return `${diffHours} hours ago`;
if (diffDays < 7) return `${diffDays} days ago`;
return date.toLocaleDateString();
}
trackByProjectId(index: number, project: Project): number {
return project.id;
}
handleUpdateError(error: any, projectName?: string): void {
if (error.status === 409 || error.raceCondition) {
const details = error.error?.details || error;
const lastUpdateUser = details.last_update_user || error.lastUpdateUser || 'another user';
const lastUpdateDate = details.last_update_date || error.lastUpdateDate;
const message = projectName
? `Project "${projectName}" was modified by ${lastUpdateUser}. Please reload.`
: `Project was modified by ${lastUpdateUser}. Please reload.`;
this.snackBar.open(
message,
'Reload',
{
duration: 0,
panelClass: ['error-snackbar', 'race-condition-snackbar']
}
).onAction().subscribe(() => {
this.loadProjects();
});
// Log additional info if available
if (lastUpdateDate) {
console.info(`Last updated at: ${lastUpdateDate}`);
}
} else {
// Generic error handling
this.snackBar.open(
error.error?.detail || error.message || 'Operation failed',
'Close',
{
duration: 5000,
panelClass: ['error-snackbar']
}
);
}
}
private async confirmAction(title: string, message: string, confirmText: string, dangerous: boolean): Promise<boolean> {
try {
const { default: ConfirmDialogComponent } = await loadConfirmDialog();
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '400px',
data: {
title,
message,
confirmText,
confirmColor: dangerous ? 'warn' : 'primary'
}
});
return await dialogRef.afterClosed().toPromise() || false;
} catch (error) {
console.error('Failed to load confirm dialog:', error);
return false;
}
}
private showMessage(message: string, isError: boolean) {
this.message = message;
this.isError = isError;
setTimeout(() => {
this.message = '';
}, 5000);
}
} |