summaryrefslogtreecommitdiff
path: root/import/load_component_list.php
blob: e3aff8e3dc984b205114fc372197d01d0e0167cb (plain)
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
<?php
/**
 * Load components from storage/stock/Component List.csv.
 * Columns: Title, Description, supplier, supplier PN, Supplier price, Supplier URL.
 * First row is a header and is skipped. Append ?clear=y to wipe and re-import.
 *
 * @package stock
 */

namespace Bitweaver\Stock;

require_once '../../kernel/includes/setup_inc.php';

global $gBitSystem, $gBitSmarty, $gBitDb;

$gBitSystem->verifyPackage( 'stock' );
$gBitSystem->verifyPermission( 'p_stock_admin' );

require_once __DIR__.'/ImportSimpleComponent.php';

$csvFile = STOCK_IMPORT_PATH . 'Component List.csv';
$doClear = ( ( $_REQUEST['clear'] ?? '' ) === 'y' );
$loaded  = 0;
$skipped = 0;
$deleted = 0;
$errors  = [];

if( !file_exists( $csvFile ) ) {
	$errors[] = 'CSV file not found: '.$csvFile;
} else {
	$handle = fopen( $csvFile, 'r' );
	if( $handle === false ) {
		$errors[] = 'Cannot open CSV file.';
	} else {
		$rows   = [];
		$rowNum = 0;
		while( ( $data = fgetcsv( $handle, 0, ',', '"', '' ) ) !== false ) {
			$rowNum++;
			if( $rowNum === 1 ) continue;
			$rows[] = $data;
		}
		fclose( $handle );

		if( $doClear ) {
			foreach( $rows as $data ) {
				$title = trim( $data[0] ?? '' );
				if( !empty( $title ) && stockExpungeComponentByTitle( $title ) ) {
					$deleted++;
				}
			}
		}

		foreach( $rows as $idx => $data ) {
			$result   = stockImportSimpleComponent( $data, $idx + 2 );
			$loaded  += $result['loaded'];
			$skipped += $result['skipped'];
			$errors   = array_merge( $errors, $result['errors'] );
		}
	}
}

$gBitSmarty->assign( 'loaded',  $loaded );
$gBitSmarty->assign( 'skipped', $skipped );
$gBitSmarty->assign( 'deleted', $deleted );
$gBitSmarty->assign( 'errors',  $errors );
$gBitSmarty->assign( 'csvFile', $csvFile );

$gBitSystem->display( 'bitpackage:stock/import_results.tpl', 'Import Component List' );