raps-cli 4.15.0

RAPS (rapeseed) - Rust Autodesk Platform Services CLI
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! CSV-based bulk update and import operations

use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{Context, Result};
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
use serde::Serialize;

use raps_acc::admin::AccountAdminClient;
use raps_acc::users::{ImportUserRequest, ProjectUsersClient};
use raps_admin::{BulkConfig, ProgressUpdate};
use raps_kernel::auth::AuthClient;
use raps_kernel::config::Config;
use raps_kernel::http::HttpClientConfig;

use crate::output::OutputFormat;

use super::{create_bulk_progress_bar, get_account_id, parse_filter_with_ids};

// ============================================================================
// CSV UPDATE
// ============================================================================

/// A single row from the CSV update file
#[derive(Debug, serde::Deserialize)]
pub(crate) struct CsvUpdateRow {
    pub(crate) email: String,
    #[serde(default)]
    pub(crate) role: Option<String>,
    #[serde(default)]
    pub(crate) company: Option<String>,
}

#[derive(Serialize)]
pub(crate) struct CsvUpdateResultOutput {
    pub(crate) total: usize,
    pub(crate) updated: usize,
    pub(crate) skipped: usize,
    pub(crate) failed: usize,
    pub(crate) errors: Vec<CsvUpdateErrorOutput>,
}

#[derive(Serialize)]
pub(crate) struct CsvUpdateErrorOutput {
    pub(crate) email: String,
    pub(crate) error: String,
}

/// Execute bulk user updates from a CSV file
///
/// Expected columns: email (required), role (optional), company (optional)
#[allow(clippy::too_many_arguments)]
pub(crate) async fn execute_csv_update(
    config: &Config,
    auth_client: &AuthClient,
    account: Option<String>,
    filter: Option<String>,
    project_ids: Option<PathBuf>,
    csv_path: &PathBuf,
    concurrency: usize,
    dry_run: bool,
    output_format: OutputFormat,
) -> Result<()> {
    let account_id = get_account_id(account)?;

    // Parse CSV file
    let mut reader = csv::Reader::from_path(csv_path)
        .with_context(|| format!("Failed to open CSV file: {}", csv_path.display()))?;

    let mut rows: Vec<CsvUpdateRow> = Vec::new();
    let mut validation_errors: Vec<String> = Vec::new();

    for (i, result) in reader.deserialize().enumerate() {
        match result {
            Ok(row) => {
                let row: CsvUpdateRow = row;
                // Validate email
                if row.email.is_empty() || !row.email.contains('@') {
                    validation_errors.push(format!("Row {}: invalid email '{}'", i + 2, row.email));
                    continue;
                }
                // Validate at least one field to update
                if row.role.is_none() && row.company.is_none() {
                    validation_errors.push(format!(
                        "Row {}: email '{}' has no role or company to update",
                        i + 2,
                        row.email
                    ));
                    continue;
                }
                rows.push(row);
            }
            Err(e) => {
                validation_errors.push(format!("Row {}: parse error: {}", i + 2, e));
            }
        }
    }

    // Report validation errors
    if !validation_errors.is_empty() {
        if output_format.supports_colors() {
            println!("{} CSV validation errors:", "\u{2717}".red().bold());
            for err in &validation_errors {
                println!("  {} {}", "\u{2022}".red(), err);
            }
        }
        anyhow::bail!(
            "CSV validation failed with {} error(s). Fix errors before proceeding.",
            validation_errors.len()
        );
    }

    if rows.is_empty() {
        anyhow::bail!("No valid rows found in CSV file");
    }

    if output_format.supports_colors() {
        println!(
            "\n{} CSV update: {} rows from {}",
            "\u{2192}".cyan(),
            rows.len().to_string().green(),
            csv_path.display().to_string().cyan()
        );
        if dry_run {
            println!("  {} Dry-run mode enabled", "\u{26A0}".yellow());
        }
        println!();
    }

    let http_config = HttpClientConfig::default();
    let admin_client = AccountAdminClient::new_with_http_config(
        config.clone(),
        auth_client.clone(),
        http_config.clone(),
    );

    let project_filter = parse_filter_with_ids(&filter, &project_ids)?;

    let mut updated = 0usize;
    let skipped = 0usize;
    let mut failed = 0usize;
    let mut errors = Vec::new();

    let progress_bar = create_bulk_progress_bar(output_format);
    if let Some(ref pb) = progress_bar {
        pb.set_length(rows.len() as u64);
    }

    for row in &rows {
        if let Some(ref pb) = progress_bar {
            pb.set_message(row.email.to_string());
        }

        if dry_run {
            if output_format.supports_colors() {
                let mut changes = Vec::new();
                if let Some(ref r) = row.role {
                    changes.push(format!("role={}", r));
                }
                if let Some(ref c) = row.company {
                    changes.push(format!("company={}", c));
                }
                if let Some(ref pb) = progress_bar {
                    pb.println(format!(
                        "  {} {} \u{2192} {}",
                        "\u{2192}".dimmed(),
                        row.email,
                        changes.join(", ")
                    ));
                }
            }
            updated += 1;
        } else {
            let mut row_updated = false;

            // Update company at account level if specified
            if let Some(ref company_name) = row.company {
                match admin_client
                    .find_user_by_email(&account_id, &row.email)
                    .await
                {
                    Ok(Some(user)) => {
                        let update_req = raps_acc::admin::UpdateAccountUserRequest {
                            company_id: None,
                            company_name: Some(company_name.clone()),
                        };
                        match admin_client
                            .update_user(&account_id, &user.id, update_req)
                            .await
                        {
                            Ok(_) => {
                                row_updated = true;
                            }
                            Err(e) => {
                                failed += 1;
                                errors.push(CsvUpdateErrorOutput {
                                    email: row.email.clone(),
                                    error: format!("company update failed: {}", e),
                                });
                                if let Some(ref pb) = progress_bar {
                                    pb.inc(1);
                                }
                                continue;
                            }
                        }
                    }
                    Ok(None) => {
                        failed += 1;
                        errors.push(CsvUpdateErrorOutput {
                            email: row.email.clone(),
                            error: "user not found in account".to_string(),
                        });
                        if let Some(ref pb) = progress_bar {
                            pb.inc(1);
                        }
                        continue;
                    }
                    Err(e) => {
                        failed += 1;
                        errors.push(CsvUpdateErrorOutput {
                            email: row.email.clone(),
                            error: format!("user lookup failed: {}", e),
                        });
                        if let Some(ref pb) = progress_bar {
                            pb.inc(1);
                        }
                        continue;
                    }
                }
            }

            // Update role across projects if specified
            if let Some(ref role_value) = row.role {
                let users_client = Arc::new(ProjectUsersClient::new_with_http_config(
                    config.clone(),
                    auth_client.clone(),
                    http_config.clone(),
                ));

                let bulk_config = BulkConfig {
                    concurrency: concurrency.min(50),
                    dry_run: false,
                    ..Default::default()
                };

                let noop_progress = |_: ProgressUpdate| {};

                match raps_admin::bulk_update_role(
                    &admin_client,
                    users_client,
                    &account_id,
                    &row.email,
                    role_value,
                    None,
                    &project_filter,
                    bulk_config,
                    noop_progress,
                )
                .await
                {
                    Ok(result) => {
                        if result.failed > 0 {
                            failed += 1;
                            errors.push(CsvUpdateErrorOutput {
                                email: row.email.clone(),
                                error: format!(
                                    "role update: {}/{} projects failed",
                                    result.failed, result.total
                                ),
                            });
                        } else {
                            row_updated = true;
                        }
                    }
                    Err(e) => {
                        failed += 1;
                        errors.push(CsvUpdateErrorOutput {
                            email: row.email.clone(),
                            error: format!("role update failed: {}", e),
                        });
                    }
                }
            }

            if row_updated {
                updated += 1;
            }
        }

        if let Some(ref pb) = progress_bar {
            pb.inc(1);
        }
    }

    if let Some(pb) = progress_bar {
        pb.finish_and_clear();
    }

    let output = CsvUpdateResultOutput {
        total: rows.len(),
        updated,
        skipped,
        failed,
        errors,
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "CSV Update Results:".bold());
            println!("{}", "\u{2500}".repeat(60));
            println!("{:<15} {}", "Total:".bold(), output.total);
            println!(
                "{:<15} {}",
                "Updated:".bold(),
                output.updated.to_string().green()
            );
            println!(
                "{:<15} {}",
                "Skipped:".bold(),
                output.skipped.to_string().yellow()
            );
            println!(
                "{:<15} {}",
                "Failed:".bold(),
                output.failed.to_string().red()
            );
            println!("{}", "\u{2500}".repeat(60));

            if !output.errors.is_empty() {
                println!("\n{}", "Errors:".red().bold());
                for err in &output.errors {
                    println!(
                        "  {} {} - {}",
                        "\u{2717}".red(),
                        err.email,
                        err.error.dimmed()
                    );
                }
            }

            if output.failed == 0 {
                println!(
                    "\n{} All {} user(s) updated successfully!",
                    "\u{2713}".green().bold(),
                    output.updated
                );
            } else {
                println!(
                    "\n{} Completed with {} failure(s)",
                    "\u{26A0}".yellow().bold(),
                    output.failed
                );
            }
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    if output.failed > 0 {
        anyhow::bail!(
            "Bulk operation partially failed: {} items failed",
            output.failed
        );
    }

    Ok(())
}

// ============================================================================
// CSV IMPORT (new users)
// ============================================================================

/// A single row from the CSV import file
#[derive(Debug, serde::Deserialize)]
struct CsvImportRow {
    email: String,
    #[serde(default)]
    role_id: Option<String>,
}

#[derive(Serialize)]
struct CsvImportResultOutput {
    total: usize,
    imported: usize,
    failed: usize,
    errors: Vec<CsvImportErrorOutput>,
}

#[derive(Serialize)]
struct CsvImportErrorOutput {
    email: String,
    error: String,
}

/// Execute import of new users into a project from a CSV file
///
/// Expected columns: email (required), role_id (optional)
pub(crate) async fn execute_csv_import(
    config: &Config,
    auth_client: &AuthClient,
    project_id: &str,
    csv_path: &PathBuf,
    output_format: OutputFormat,
) -> Result<()> {
    // Parse CSV file
    let mut reader = csv::Reader::from_path(csv_path)
        .with_context(|| format!("Failed to open CSV file: {}", csv_path.display()))?;

    let mut rows: Vec<CsvImportRow> = Vec::new();
    let mut validation_errors: Vec<String> = Vec::new();

    for (i, result) in reader.deserialize().enumerate() {
        match result {
            Ok(row) => {
                let row: CsvImportRow = row;
                // Validate email
                if row.email.is_empty() || !row.email.contains('@') {
                    validation_errors.push(format!("Row {}: invalid email '{}'", i + 2, row.email));
                    continue;
                }
                rows.push(row);
            }
            Err(e) => {
                validation_errors.push(format!("Row {}: parse error: {}", i + 2, e));
            }
        }
    }

    // Report validation errors
    if !validation_errors.is_empty() {
        if output_format.supports_colors() {
            println!("{} CSV validation errors:", "\u{2717}".red().bold());
            for err in &validation_errors {
                println!("  {} {}", "\u{2022}".red(), err);
            }
        }
        anyhow::bail!(
            "CSV validation failed with {} error(s). Fix errors before proceeding.",
            validation_errors.len()
        );
    }

    if rows.is_empty() {
        anyhow::bail!("No valid rows found in CSV file");
    }

    if output_format.supports_colors() {
        println!(
            "\n{} Import users: {} rows from {} into project {}",
            "\u{2192}".cyan(),
            rows.len().to_string().green(),
            csv_path.display().to_string().cyan(),
            project_id.cyan()
        );
        println!();
    }

    // Build import requests
    let users: Vec<ImportUserRequest> = rows
        .iter()
        .map(|row| ImportUserRequest {
            email: row.email.clone(),
            role_id: row.role_id.clone(),
            products: None,
        })
        .collect();

    let total = users.len();

    // Show spinner during concurrent import (up to 10 parallel requests)
    let spinner = if output_format.supports_colors() {
        let sp = ProgressBar::new_spinner();
        sp.set_style(
            ProgressStyle::with_template("{spinner:.cyan} {msg}")
                .expect("hardcoded progress template is valid")
                .tick_strings(&[
                    "\u{280B}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283C}", "\u{2834}",
                    "\u{2826}", "\u{2827}", "\u{2807}", "\u{280F}",
                ]),
        );
        sp.set_message(format!("Importing {} users concurrently...", total));
        sp.enable_steady_tick(std::time::Duration::from_millis(100));
        Some(sp)
    } else {
        None
    };

    // Create users client and call import_users (concurrent with semaphore)
    let http_config = HttpClientConfig::default();
    let users_client =
        ProjectUsersClient::new_with_http_config(config.clone(), auth_client.clone(), http_config);

    let result = users_client.import_users(project_id, users).await?;

    // Finish spinner
    if let Some(sp) = spinner {
        sp.finish_and_clear();
    }

    let errors: Vec<CsvImportErrorOutput> = result
        .errors
        .iter()
        .map(|e| CsvImportErrorOutput {
            email: e.email.clone(),
            error: e.error.clone(),
        })
        .collect();

    let output = CsvImportResultOutput {
        total: result.total,
        imported: result.imported,
        failed: result.failed,
        errors,
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Import Results:".bold());
            println!("{}", "\u{2500}".repeat(60));
            println!("{:<15} {}", "Total:".bold(), output.total);
            println!(
                "{:<15} {}",
                "Imported:".bold(),
                output.imported.to_string().green()
            );
            println!(
                "{:<15} {}",
                "Failed:".bold(),
                output.failed.to_string().red()
            );
            println!("{}", "\u{2500}".repeat(60));

            if !output.errors.is_empty() {
                println!("\n{}", "Errors:".red().bold());
                for err in &output.errors {
                    println!(
                        "  {} {} - {}",
                        "\u{2717}".red(),
                        err.email,
                        err.error.dimmed()
                    );
                }
            }

            if output.failed == 0 {
                println!(
                    "\n{} All {} user(s) imported successfully!",
                    "\u{2713}".green().bold(),
                    output.imported
                );
            } else {
                println!(
                    "\n{} Completed with {} failure(s)",
                    "\u{26A0}".yellow().bold(),
                    output.failed
                );
            }
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    if output.failed > 0 {
        anyhow::bail!(
            "Bulk operation partially failed: {} items failed",
            output.failed
        );
    }

    Ok(())
}