mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 09:09:01 +00:00
Client and asset imports read a file by its headings: new functions/import.php reads an import's CSV by heading in any order with any column left out, comma or semicolon separated, without the old 1000 character line limit, and reads files from the old templates by position when no heading matches; clients now take everything their export has plus Lead, Tax Rate by name, Tax Exempt with certificate and expiry, Tags and Notes, keep a phone's country code, and no longer get an empty location or contact; assets now take everything their export has plus Status, Primary IP or DHCP, Primary MAC, Network, Links, Vendor, Order Reference, Install Date, Warranty Expire and Tags, with Assigned To, Location, Vendor and Network found by name and Assigned To by email; rows with no name are skipped, and the import says what it could not use; templates and the import windows list the columns from the same definition; 26.11.9 changelog entries
This commit is contained in:
@@ -17,15 +17,15 @@ ob_start();
|
||||
<input type="hidden" name="client_id" value="<?= $client_id ?>">
|
||||
|
||||
<div class="modal-body">
|
||||
<p><strong>Format csv file with headings & data:</strong><br>Name, Description, Type, Make, Model, Serial, OS, Purchase Date, Assigned To, Location, Physical Location, Notes</p>
|
||||
<p class="small text-body-secondary mb-0">After those, any of an asset's details can follow, headed as the asset export heads them - <span class="font-monospace">Ports</span>, <span class="font-monospace">SFP Ports</span>, <span class="font-monospace">RAM (GB)</span>, <span class="font-monospace">Capacity (VA)</span> and so on. Each is kept where the row's type has it, and Ports and SFP Ports add its interfaces.</p>
|
||||
<p><strong>A CSV file with these headings</strong>, in any order - leave out the ones you don't have. Only Name is needed, and a file exported from the assets list imports as it is:<br><?= escapeHtml(importHeadingsText('assets')) ?></p>
|
||||
<p class="small text-body-secondary mb-0">Assigned To, Location, Vendor and Network are the client's own, by name - Assigned To by email too. Tags are separated by commas. Any of an asset's details can be added too, headed as the asset export heads them - <span class="font-monospace">Ports</span>, <span class="font-monospace">SFP Ports</span>, <span class="font-monospace">RAM (GB)</span>, <span class="font-monospace">Capacity (VA)</span> and so on. Each is kept where the row's type has it, and Ports and SFP Ports add its interfaces.</p>
|
||||
<hr>
|
||||
<div class="mb-3 my-4">
|
||||
<input type="file" class="form-control" name="file" accept=".csv" required>
|
||||
</div>
|
||||
<hr>
|
||||
<div>Download <a href="post.php?download_assets_csv_template=<?= $client_id ?>">sample csv template</a></div>
|
||||
<small class="text-muted">Note: Purchase date must be in the format YYYY-MM-DD. Spreadsheet tools may automatically reformat dates.</small>
|
||||
<small class="text-muted">Note: dates must be in the format YYYY-MM-DD. Spreadsheet tools may automatically reformat dates.</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="import_assets_csv" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Import</button>
|
||||
|
||||
@@ -13,8 +13,8 @@ ob_start();
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<div class="modal-body">
|
||||
<p><strong>Importing Multiple Contacts:</strong><br>When importing a client, only one contact (which will become the primary contact) and one location (which will become the primary location) can be added initially. To add additional contacts, you will need to click into each client, navigate to the Contacts section, and import multiple contacts individually for each client.</p>
|
||||
<p><strong>Format csv file with headings & data:</strong><br>Client Name, Industry, Referral, Website, Primary Location Name, Location Phone, Location Address, City, State, Postal Code, Country, Primary Contact Name, Title, Contact Phone, Extension, Contact Mobile, Contact Email, Hourly Rate, Currency, Payment Terms, Tax ID, Abbreviation</p>
|
||||
<p class="small text-body-secondary mb-0">A client's rates and net terms come from its contract, else the defaults in Admin > Settings > Defaults. An Hourly Rate or Payment Terms (days) other than the defaults gives the client a Standard terms contract carrying them - leave them empty for the defaults.</p>
|
||||
<p><strong>A CSV file with these headings</strong>, in any order - leave out the ones you don't have. Only Client Name is needed, and a file exported from the clients list imports as it is:<br><?= escapeHtml(importHeadingsText('clients')) ?></p>
|
||||
<p class="small text-body-secondary mb-0">Lead and Tax Exempt take Yes. Tax Rate is one of your tax rates, by name. Tags are separated by commas, and dates are YYYY-MM-DD. A client's rates and net terms come from its contract, else the defaults in Admin > Settings > Defaults. An Hourly Rate or Payment Terms (days) other than the defaults gives the client a Standard terms contract carrying them - leave them empty for the defaults.</p>
|
||||
<hr>
|
||||
<div class="mb-3 my-4">
|
||||
<input type="file" class="form-control" name="file" accept=".csv" required>
|
||||
|
||||
@@ -1002,197 +1002,105 @@ if (isset($_POST["import_assets_csv"])) {
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
$file_name = $_FILES["file"]["tmp_name"];
|
||||
|
||||
$error = false;
|
||||
|
||||
if (!empty($_FILES["file"]["tmp_name"])) {
|
||||
$file_name = $_FILES["file"]["tmp_name"];
|
||||
} else {
|
||||
flashAlert("Please select a file to upload.", 'error');
|
||||
// Read by its headings - any order, any left out, and any of an asset's details after (functions/import.php)
|
||||
[$rows, $ignored, $error] = importCsvRows('assets');
|
||||
if ($error !== '') {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
//Check file is CSV
|
||||
$file_extension = strtolower(end(explode('.',$_FILES['file']['name'])));
|
||||
$allowed_file_extensions = array('csv');
|
||||
if (in_array($file_extension,$allowed_file_extensions) === false) {
|
||||
$error = true;
|
||||
flashAlert("Bad file extension", 'error');
|
||||
}
|
||||
|
||||
//Check file isn't empty
|
||||
elseif ($_FILES["file"]["size"] < 1) {
|
||||
$error = true;
|
||||
flashAlert("Bad file size (empty?)", 'error');
|
||||
}
|
||||
|
||||
//(Else)Check column count (name, desc, type, make, model, serial, os, purchase date, assigned to, location, physical location, notes),
|
||||
// then any of the details, headed as the export heads them (functions/asset_type.php)
|
||||
$f = fopen($file_name, "r");
|
||||
$f_columns = fgetcsv($f, 1000, ",");
|
||||
if (!$error & (!is_array($f_columns) || count($f_columns) < 12)) {
|
||||
$error = true;
|
||||
flashAlert("Invalid column count.", 'error');
|
||||
}
|
||||
$spec_columns = [];
|
||||
if (!$error) {
|
||||
foreach (array_slice($f_columns, 12, null, true) as $index => $heading) {
|
||||
$heading = strtolower(trim((string) $heading));
|
||||
foreach (ASSET_SPECS as $spec_key => $spec) {
|
||||
if ($heading === strtolower($spec['label']) || $heading === strtolower($spec['label'] . (isset($spec['unit']) ? ' (' . $spec['unit'] . ')' : '')) || $heading === $spec_key) {
|
||||
$spec_columns[$index] = $spec_key;
|
||||
}
|
||||
}
|
||||
$row_count = $duplicate_count = $no_name_count = 0;
|
||||
$notes = ['dates left empty (use YYYY-MM-DD)' => 0, 'contacts not found' => 0, 'locations not found' => 0, 'vendors not found' => 0, 'networks not found' => 0];
|
||||
$spec_rows = [];
|
||||
foreach ($rows as $row) {
|
||||
$in = function ($key) use ($row) {
|
||||
return (string) ($row[$key] ?? '');
|
||||
};
|
||||
if ($in('asset_name') === '') {
|
||||
$no_name_count++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
//Else, parse the file
|
||||
if (!$error) {
|
||||
$file = fopen($file_name, "r");
|
||||
fgetcsv($file, 1000, ","); // Skip first line
|
||||
$row_count = 0;
|
||||
$duplicate_count = 0;
|
||||
$spec_rows = [];
|
||||
while(($column = fgetcsv($file, 1000, ",")) !== false) {
|
||||
|
||||
// Default variables (if undefined) - each row starts empty, nothing carried from the last
|
||||
$description = $type = $make = $model = $serial = $os = $physical_location = $notes = '';
|
||||
$contact_id = $location_id = 0;
|
||||
$purchase_date = 'NULL';
|
||||
|
||||
$duplicate_detect = 0;
|
||||
|
||||
// Name
|
||||
if (isset($column[0])) {
|
||||
$name = escapeSql($column[0]);
|
||||
if (mysqli_num_rows(mysqli_query($mysqli,"SELECT 1 FROM assets WHERE asset_name = '$name' AND asset_client_id = $client_id")) > 0) {
|
||||
$duplicate_detect = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Desc
|
||||
if (!empty($column[1])) {
|
||||
$description = escapeSql($column[1]);
|
||||
}
|
||||
|
||||
// Type - as the list spells it, when it is one
|
||||
if (!empty($column[2])) {
|
||||
$type = escapeSql(assetTypeName($column[2]) ?: $column[2]);
|
||||
}
|
||||
|
||||
// Make
|
||||
if (!empty($column[3])) {
|
||||
$make = escapeSql($column[3]);
|
||||
}
|
||||
|
||||
// Model
|
||||
if (!empty($column[4])) {
|
||||
$model = escapeSql($column[4]);
|
||||
}
|
||||
|
||||
// Serial
|
||||
if (!empty($column[5])) {
|
||||
$serial = escapeSql($column[5]);
|
||||
}
|
||||
|
||||
// OS
|
||||
if (!empty($column[6])) {
|
||||
$os = escapeSql($column[6]);
|
||||
}
|
||||
|
||||
// Purchase date
|
||||
if (!empty($column[7])) {
|
||||
$purchase_date = escapeSql($column[7]);
|
||||
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $purchase_date) || empty($purchase_date)) {
|
||||
$purchase_date = "NULL";
|
||||
} else {
|
||||
$purchase_date = "'" . $purchase_date . "'";
|
||||
}
|
||||
}
|
||||
|
||||
// Assigned to (contact)
|
||||
if (!empty($column[8])) {
|
||||
$contact = escapeSql($column[8]);
|
||||
if ($contact) {
|
||||
$sql_contact = mysqli_query($mysqli,"SELECT contact_id FROM contacts WHERE contact_name = '$contact' AND contact_client_id = $client_id");
|
||||
$row = mysqli_fetch_assoc($sql_contact);
|
||||
$contact_id = intval($row['contact_id'] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Location (lookup)
|
||||
if (!empty($column[9])) {
|
||||
$location = escapeSql($column[9]);
|
||||
if ($location) {
|
||||
$sql_location = mysqli_query($mysqli,"SELECT location_id FROM locations WHERE location_name = '$location' AND location_client_id = $client_id");
|
||||
$row = mysqli_fetch_assoc($sql_location);
|
||||
$location_id = intval($row['location_id'] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Physical location (varchar)
|
||||
if (!empty($column[10])) {
|
||||
$physical_location = escapeSql($column[10]);
|
||||
}
|
||||
|
||||
// Notes (varchar)
|
||||
if (!empty($column[11])) {
|
||||
$notes = escapeSql($column[11]);
|
||||
}
|
||||
|
||||
// Check if duplicate was detected
|
||||
if ($duplicate_detect == 0) {
|
||||
//Add
|
||||
mysqli_query($mysqli,"INSERT INTO assets SET asset_name = '$name', asset_description = '$description', asset_type = '$type', asset_make = '$make', asset_model = '$model', asset_serial = '$serial', asset_os = '$os', asset_purchase_date = $purchase_date, asset_physical_location = '$physical_location', asset_notes = '$notes', asset_contact_id = $contact_id, asset_location_id = $location_id, asset_client_id = $client_id");
|
||||
|
||||
$asset_id = mysqli_insert_id($mysqli);
|
||||
|
||||
// Add Primary Interface
|
||||
mysqli_query($mysqli,"INSERT INTO asset_interfaces SET interface_name = '1', interface_primary = 1, interface_asset_id = $asset_id");
|
||||
|
||||
// Its details, from the columns after the twelve - kept once every row is in, so a VM's host can come later in the file
|
||||
$spec_input = [];
|
||||
foreach ($spec_columns as $index => $spec_key) {
|
||||
$spec_input[$spec_key] = (string) ($column[$index] ?? '');
|
||||
}
|
||||
if ($spec_input) {
|
||||
$spec_rows[] = [$asset_id, $column[0], $column[2] ?? '', $spec_input];
|
||||
}
|
||||
|
||||
$row_count = $row_count + 1;
|
||||
} else {
|
||||
$duplicate_count = $duplicate_count + 1;
|
||||
}
|
||||
$name = escapeSql(mb_substr($in('asset_name'), 0, 200));
|
||||
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM assets WHERE asset_name = '$name' AND asset_client_id = $client_id")) > 0) {
|
||||
$duplicate_count++;
|
||||
continue;
|
||||
}
|
||||
fclose($file);
|
||||
|
||||
// The details, and the ports they count; what wasn't kept, by asset
|
||||
$spec_problems = [];
|
||||
foreach ($spec_rows as [$spec_asset_id, $spec_asset_name, $spec_type, $spec_input]) {
|
||||
[, $problems] = assetSpecsFromPost($spec_asset_id, $spec_type, $spec_input, $client_id);
|
||||
if ($problems) {
|
||||
$spec_problems[] = $spec_asset_name . ' (' . implode('; ', $problems) . ')';
|
||||
// Its type as the list spells it, when it is one; its status one of the statuses, made when new (functions/categories.php)
|
||||
$type = escapeSql(assetTypeName($in('asset_type')) ?: mb_substr($in('asset_type'), 0, 200));
|
||||
$status = escapeSql(categoryEnsure('asset_status', $in('asset_status')));
|
||||
|
||||
// Dates as YYYY-MM-DD - anything else is left empty, and said
|
||||
$dates = [];
|
||||
foreach (['asset_purchase_date', 'asset_install_date', 'asset_warranty_expire'] as $key) {
|
||||
$date = importDate($in($key));
|
||||
$notes['dates left empty (use YYYY-MM-DD)'] += $date === null ? 1 : 0;
|
||||
$dates[$key] = $date ? "'$date'" : 'NULL';
|
||||
}
|
||||
|
||||
// The client's own records, by name - a contact by its email too
|
||||
$ids = [];
|
||||
foreach (['contact' => 'contact_name', 'location' => 'location_name', 'vendor' => 'vendor_name', 'network' => 'network_name'] as $kind => $key) {
|
||||
$ids[$kind] = importClientRecordId($kind, $in($key), $client_id);
|
||||
if ($in($key) !== '' && !$ids[$kind]) {
|
||||
$notes[$kind . 's not found']++;
|
||||
}
|
||||
}
|
||||
|
||||
logAudit("Asset", "Import", "$session_name imported $row_count asset(s) via CSV file", $client_id);
|
||||
mysqli_query($mysqli, "INSERT INTO assets SET asset_name = '$name', asset_description = '" . escapeSql(mb_substr($in('asset_description'), 0, 255)) . "', asset_type = '$type', asset_status = '$status',
|
||||
asset_make = '" . escapeSql(mb_substr($in('asset_make'), 0, 200)) . "', asset_model = '" . escapeSql(mb_substr($in('asset_model'), 0, 200)) . "', asset_serial = '" . escapeSql(mb_substr($in('asset_serial'), 0, 200)) . "',
|
||||
asset_os = '" . escapeSql(mb_substr($in('asset_os'), 0, 200)) . "', asset_uri = '" . escapeSql(mb_substr($in('asset_uri'), 0, 500)) . "', asset_uri_2 = '" . escapeSql(mb_substr($in('asset_uri_2'), 0, 500)) . "',
|
||||
asset_uri_client = '" . escapeSql(mb_substr($in('asset_uri_client'), 0, 500)) . "', asset_purchase_reference = '" . escapeSql(mb_substr($in('asset_purchase_reference'), 0, 200)) . "',
|
||||
asset_purchase_date = {$dates['asset_purchase_date']}, asset_install_date = {$dates['asset_install_date']}, asset_warranty_expire = {$dates['asset_warranty_expire']},
|
||||
asset_physical_location = '" . escapeSql(mb_substr($in('asset_physical_location'), 0, 200)) . "', asset_notes = '" . escapeSql($in('asset_notes')) . "',
|
||||
asset_contact_id = {$ids['contact']}, asset_location_id = {$ids['location']}, asset_vendor_id = {$ids['vendor']}, asset_client_id = $client_id");
|
||||
$asset_id = mysqli_insert_id($mysqli);
|
||||
|
||||
if ($spec_problems) {
|
||||
flashAlert("$row_count Asset(s) added, $duplicate_count duplicate(s) detected - details not kept: " . escapeHtml(implode(', ', array_slice($spec_problems, 0, 5)) . (count($spec_problems) > 5 ? ' and ' . (count($spec_problems) - 5) . ' more' : '')), 'warning');
|
||||
} else {
|
||||
flashAlert("$row_count Asset(s) added, $duplicate_count duplicate(s) detected");
|
||||
// Its primary interface, with its address, MAC and network - as the asset form makes it
|
||||
$ip = $in('interface_ip');
|
||||
$ip = strcasecmp($ip, 'DHCP') === 0 ? 'DHCP' : (normalizeIpAddress($ip) ?: $ip);
|
||||
$mac = normalizeMacAddress($in('interface_mac')) ?: $in('interface_mac');
|
||||
mysqli_query($mysqli, "INSERT INTO asset_interfaces SET interface_name = '01', interface_ip = '" . escapeSql(mb_substr($ip, 0, 200)) . "', interface_mac = '" . escapeSql(mb_substr($mac, 0, 200)) . "',
|
||||
interface_network_id = {$ids['network']}, interface_primary = 1, interface_asset_id = $asset_id");
|
||||
|
||||
if ($in('asset_tags') !== '') {
|
||||
tagSetForRecord('asset', $asset_id, importTagIds('asset', $in('asset_tags')));
|
||||
}
|
||||
|
||||
redirect();
|
||||
// Its details - kept once every row is in, so a VM's host can come later in the file
|
||||
$spec_input = [];
|
||||
foreach ($row as $key => $value) {
|
||||
if (strpos($key, 'spec_') === 0) {
|
||||
$spec_input[substr($key, 5)] = $value;
|
||||
}
|
||||
}
|
||||
if (array_filter($spec_input, 'strlen')) {
|
||||
$spec_rows[] = [$asset_id, $in('asset_name'), $in('asset_type'), $spec_input];
|
||||
}
|
||||
|
||||
$row_count++;
|
||||
}
|
||||
//Check for any errors, if there are notify user and redirect
|
||||
if ($error) {
|
||||
redirect();
|
||||
|
||||
// The details, and the ports they count; what wasn't kept, by asset
|
||||
$spec_problems = [];
|
||||
foreach ($spec_rows as [$spec_asset_id, $spec_asset_name, $spec_type, $spec_input]) {
|
||||
[, $problems] = assetSpecsFromPost($spec_asset_id, $spec_type, $spec_input, $client_id);
|
||||
if ($problems) {
|
||||
$spec_problems[] = $spec_asset_name . ' (' . implode('; ', $problems) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
$left_out = importNotesText($notes + ['rows with no Name' => $no_name_count]);
|
||||
logAudit("Asset", "Import", "$session_name imported $row_count asset(s) via CSV file, $duplicate_count duplicate(s) found" . ($left_out !== '' ? " - $left_out" : ''), $client_id);
|
||||
|
||||
flashAlert("<strong>$row_count</strong> Asset(s) added, <strong>$duplicate_count</strong> duplicate(s) found"
|
||||
. ($left_out !== '' ? ' - ' . escapeHtml($left_out) : '')
|
||||
. ($spec_problems ? '. Details not kept: ' . escapeHtml(implode(', ', array_slice($spec_problems, 0, 5)) . (count($spec_problems) > 5 ? ' and ' . (count($spec_problems) - 5) . ' more' : '')) : '')
|
||||
. ($ignored ? '. Columns not imported: ' . escapeHtml(implode(', ', array_slice($ignored, 0, 8)) . (count($ignored) > 8 ? ' and ' . (count($ignored) - 8) . ' more' : '')) : ''),
|
||||
$left_out !== '' || $spec_problems || $ignored ? 'warning' : 'success');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_GET['download_assets_csv_template'])) {
|
||||
@@ -1204,28 +1112,7 @@ if (isset($_GET['download_assets_csv_template'])) {
|
||||
// Named for the client only when it's one this agent can reach - any id would otherwise say its client's name back
|
||||
$client_name = $client_id && hasClientAccess($client_id) ? (string) getFieldById('clients', $client_id, 'client_name') : '';
|
||||
|
||||
$delimiter = ",";
|
||||
$enclosure = '"';
|
||||
$escape = '\\';
|
||||
$filename = ($client_name !== '' ? toAlphanumeric($client_name) . '-' : '') . "Assets-Template.csv";
|
||||
|
||||
//create a file pointer
|
||||
$f = fopen('php://memory', 'w');
|
||||
|
||||
//set column headers
|
||||
$fields = array('Name', 'Description', 'Type', 'Make', 'Model', 'Serial', 'OS', 'Purchase Date', 'Assigned To', 'Location', 'Physical Location', 'Notes');
|
||||
fputcsv($f, $fields, $delimiter, $enclosure, $escape);
|
||||
|
||||
//move back to beginning of file
|
||||
fseek($f, 0);
|
||||
|
||||
//set headers to download file rather than displayed
|
||||
header('Content-Type: text/csv');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '";');
|
||||
|
||||
//output all remaining data on a file pointer
|
||||
fpassthru($f);
|
||||
exit;
|
||||
importTemplateDownload('assets', ($client_name !== '' ? toAlphanumeric($client_name) . '-' : '') . 'Assets-Template.csv');
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -497,235 +497,116 @@ if (isset($_POST["import_clients_csv"])) {
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_client', 2);
|
||||
$error = false;
|
||||
|
||||
if (!empty($_FILES["file"]["tmp_name"])) {
|
||||
$file_name = $_FILES["file"]["tmp_name"];
|
||||
} else {
|
||||
flashAlert("Please select a file to upload.", 'error');
|
||||
// Read by its headings - any order, any left out (functions/import.php)
|
||||
[$rows, $ignored, $error] = importCsvRows('clients');
|
||||
if ($error !== '') {
|
||||
flashAlert(escapeHtml($error), 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
//Check file is CSV
|
||||
$file_extension = strtolower(end(explode('.',$_FILES['file']['name'])));
|
||||
$allowed_file_extensions = array('csv');
|
||||
if (in_array($file_extension,$allowed_file_extensions) === false) {
|
||||
$error = true;
|
||||
flashAlert("Bad file extension", 'error');
|
||||
}
|
||||
|
||||
//Check file isn't empty
|
||||
elseif ($_FILES["file"]["size"] < 1) {
|
||||
$error = true;
|
||||
flashAlert("Bad file size (empty?)", 'error');
|
||||
}
|
||||
|
||||
//(Else)Check column count
|
||||
$f = fopen($file_name, "r");
|
||||
$f_columns = fgetcsv($f, 1000, ",");
|
||||
if (!$error & count($f_columns) != 22) {
|
||||
$error = true;
|
||||
flashAlert("Bad column count.", 'error');
|
||||
}
|
||||
|
||||
//Else, parse the file
|
||||
if (!$error) {
|
||||
$file = fopen($file_name, "r");
|
||||
fgetcsv($file, 1000, ","); // Skip first line
|
||||
$row_count = 0;
|
||||
$duplicate_count = 0;
|
||||
while(($column = fgetcsv($file, 1000, ",")) !== false) {
|
||||
$duplicate_detect = 0;
|
||||
if (isset($column[0])) {
|
||||
$name = escapeSql($column[0]);
|
||||
if (mysqli_num_rows(mysqli_query($mysqli,"SELECT 1 FROM clients WHERE client_name = '$name'")) > 0) {
|
||||
$duplicate_detect = 1;
|
||||
}
|
||||
}
|
||||
|
||||
$industry = '';
|
||||
if (isset($column[1])) {
|
||||
$industry = escapeSql($column[1]);
|
||||
}
|
||||
|
||||
$referral = '';
|
||||
if (isset($column[2])) {
|
||||
$referral = (string) $column[2];
|
||||
}
|
||||
|
||||
$website = '';
|
||||
if (isset($column[3])) {
|
||||
$website = escapeSql(preg_replace("(^https?://)", "", $column[3]));
|
||||
}
|
||||
|
||||
$location_name = '';
|
||||
if (isset($column[4])) {
|
||||
$location_name = escapeSql($column[4]);
|
||||
}
|
||||
|
||||
$location_phone = '';
|
||||
if (isset($column[5])) {
|
||||
$location_phone = preg_replace("/[^0-9]/", '', $column[5]);
|
||||
}
|
||||
|
||||
$address = '';
|
||||
if (isset($column[6])) {
|
||||
$address = escapeSql($column[6]);
|
||||
}
|
||||
|
||||
$city = '';
|
||||
if (isset($column[7])) {
|
||||
$city = escapeSql($column[7]);
|
||||
}
|
||||
|
||||
$state = '';
|
||||
if (isset($column[8])) {
|
||||
$state = escapeSql($column[8]);
|
||||
}
|
||||
|
||||
$zip = '';
|
||||
if (isset($column[9])) {
|
||||
$zip = escapeSql($column[9]);
|
||||
}
|
||||
|
||||
$country = '';
|
||||
if (isset($column[10])) {
|
||||
$country = escapeSql($column[10]);
|
||||
}
|
||||
|
||||
$contact_name = '';
|
||||
if (isset($column[11])) {
|
||||
$contact_name = escapeSql($column[11]);
|
||||
}
|
||||
|
||||
$title = '';
|
||||
if (isset($column[12])) {
|
||||
$title = escapeSql($column[12]);
|
||||
}
|
||||
|
||||
$contact_phone = '';
|
||||
if (isset($column[13])) {
|
||||
$contact_phone = preg_replace("/[^0-9]/", '',$column[13]);
|
||||
}
|
||||
|
||||
$contact_extension = '';
|
||||
if (isset($column[14])) {
|
||||
$contact_extension = preg_replace("/[^0-9]/", '',$column[14]);
|
||||
}
|
||||
|
||||
$contact_mobile = '';
|
||||
if (isset($column[15])) {
|
||||
$contact_mobile = preg_replace("/[^0-9]/", '',$column[15]);
|
||||
}
|
||||
|
||||
$contact_email = '';
|
||||
if (isset($column[16])) {
|
||||
$contact_email = escapeSql($column[16]);
|
||||
}
|
||||
|
||||
// An hourly rate or payment terms other than the defaults become the client's Standard terms contract
|
||||
$hourly_rate = null;
|
||||
if (isset($column[17]) && trim($column[17]) !== '') {
|
||||
$hourly_rate = floatval(str_replace([',', '$'], '', $column[17]));
|
||||
}
|
||||
|
||||
$currency_code = escapeSql($session_company_currency);
|
||||
if (isset($column[18])) {
|
||||
$currency_code = escapeSql($column[18]);
|
||||
}
|
||||
|
||||
$payment_terms = null;
|
||||
if (isset($column[19]) && trim($column[19]) !== '' && is_numeric(trim($column[19]))) {
|
||||
$payment_terms = max(0, min(365, intval($column[19])));
|
||||
}
|
||||
|
||||
$tax_id_number = '';
|
||||
if (isset($column[20])) {
|
||||
$tax_id_number = escapeSql($column[20]);
|
||||
}
|
||||
|
||||
$abbreviation = '';
|
||||
if (isset($column[21])) {
|
||||
$abbreviation = escapeSql($column[21]);
|
||||
}
|
||||
|
||||
// Check if duplicate was detected
|
||||
if ($duplicate_detect == 0) {
|
||||
//Add
|
||||
// A referral that isn't one yet is made one; one that is takes its own spelling
|
||||
$referral = escapeSql(categoryEnsure('Referral', $referral));
|
||||
|
||||
// Create client
|
||||
mysqli_query($mysqli, "INSERT INTO clients SET client_name = '$name', client_type = '$industry', client_website = '$website', client_referral = '$referral', client_currency_code = '$currency_code', client_tax_id_number = '$tax_id_number', client_abbreviation = '$abbreviation'" . billingClientLegacySql());
|
||||
|
||||
$client_id = mysqli_insert_id($mysqli);
|
||||
|
||||
if (!file_exists("../uploads/clients/$client_id")) {
|
||||
mkdir("../uploads/clients/$client_id");
|
||||
file_put_contents("../uploads/clients/$client_id/index.php", "");
|
||||
}
|
||||
|
||||
// Create Location
|
||||
mysqli_query($mysqli, "INSERT INTO locations SET location_name = '$location_name', location_address = '$address', location_city = '$city', location_state = '$state', location_zip = '$zip', location_phone = '$location_phone', location_country = '$country', location_primary = 1, location_client_id = $client_id");
|
||||
|
||||
// Create Contact
|
||||
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$contact_name', contact_title = '$title', contact_phone = '$contact_phone', contact_extension = '$contact_extension', contact_mobile = '$contact_mobile', contact_email = '$contact_email', contact_primary = 1, contact_important = 1, contact_client_id = $client_id");
|
||||
|
||||
// Its rate and terms, where they aren't the defaults (functions/contract.php)
|
||||
if (function_exists('contractsReady') && contractsReady() && contractStandardTermsAdd($client_id, $hourly_rate, $payment_terms, [], null, 'Made by the client import from its Hourly Rate and Payment Terms.')) {
|
||||
$terms_count = ($terms_count ?? 0) + 1;
|
||||
}
|
||||
|
||||
$row_count = $row_count + 1;
|
||||
|
||||
} else {
|
||||
|
||||
$duplicate_count = $duplicate_count + 1;
|
||||
|
||||
}
|
||||
|
||||
$row_count = $duplicate_count = $no_name_count = $terms_count = 0;
|
||||
$notes = ['dates left empty (use YYYY-MM-DD)' => 0, 'tax rates not found' => 0, 'currencies not a 3-letter code' => 0];
|
||||
// A phone's dial code and number - "+1 (412) 555-0100" as the exports write it (functions/import.php)
|
||||
$phone = function ($value, $column) {
|
||||
[$code, $number] = importPhone($value);
|
||||
return "{$column}_country_code = '" . escapeSql($code) . "', $column = '" . escapeSql(mb_substr($number, 0, 200)) . "'";
|
||||
};
|
||||
foreach ($rows as $row) {
|
||||
$in = function ($key) use ($row) {
|
||||
return (string) ($row[$key] ?? '');
|
||||
};
|
||||
if ($in('client_name') === '') {
|
||||
$no_name_count++;
|
||||
continue;
|
||||
}
|
||||
$name = escapeSql(mb_substr($in('client_name'), 0, 200));
|
||||
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_name = '$name'")) > 0) {
|
||||
$duplicate_count++;
|
||||
continue;
|
||||
}
|
||||
fclose($file);
|
||||
|
||||
logAudit("Client", "Import", "$session_name imported $row_count client(s) via CSV file, $duplicate_count duplicate(s) found");
|
||||
$industry = escapeSql(mb_substr($in('client_type'), 0, 200));
|
||||
// A referral that isn't one yet is made one; one that is takes its own spelling
|
||||
$referral = escapeSql(categoryEnsure('Referral', $in('client_referral')));
|
||||
$website = escapeSql(mb_substr(preg_replace("(^https?://)", "", $in('client_website')), 0, 200));
|
||||
$lead = importYes($in('client_lead')) ? 1 : 0;
|
||||
$abbreviation = escapeSql(mb_substr($in('client_abbreviation') !== '' ? $in('client_abbreviation') : shortenClientName($in('client_name')), 0, 6));
|
||||
$currency = strtoupper($in('client_currency_code'));
|
||||
if ($currency !== '' && !preg_match('/^[A-Z]{3}$/', $currency)) {
|
||||
$notes['currencies not a 3-letter code']++;
|
||||
$currency = '';
|
||||
}
|
||||
$currency = escapeSql($currency !== '' ? $currency : $session_company_currency);
|
||||
$tax_id_number = escapeSql(mb_substr($in('client_tax_id_number'), 0, 255));
|
||||
$client_notes = escapeSql($in('client_notes'));
|
||||
|
||||
flashAlert("<strong>$row_count</strong> Client(s) added, <strong>$duplicate_count</strong> duplicate(s) found" . (!empty($terms_count) ? ", <strong>$terms_count</strong> with a Standard terms contract for their own rate or payment terms" : ''));
|
||||
// Its tax rate and exemption, as the Billing tab sets them (functions/tax.php)
|
||||
$tax_input = [];
|
||||
if ($in('client_tax_rate') !== '') {
|
||||
$tax_input['default_tax_id'] = importTaxId($in('client_tax_rate'));
|
||||
$notes['tax rates not found'] += $tax_input['default_tax_id'] ? 0 : 1;
|
||||
}
|
||||
if (importYes($in('client_tax_exempt'))) {
|
||||
$expires = importDate($in('client_tax_exempt_expires'));
|
||||
$notes['dates left empty (use YYYY-MM-DD)'] += $expires === null ? 1 : 0;
|
||||
$tax_input += ['tax_exempt' => true, 'tax_exempt_number' => $in('client_tax_exempt_number'), 'tax_exempt_expires' => (string) $expires];
|
||||
}
|
||||
|
||||
redirect();
|
||||
mysqli_query($mysqli, "INSERT INTO clients SET client_name = '$name', client_type = '$industry', client_website = '$website', client_referral = '$referral', client_lead = $lead, client_currency_code = '$currency', client_tax_id_number = '$tax_id_number', client_abbreviation = '$abbreviation', client_notes = '$client_notes'"
|
||||
. ($tax_input ? ', ' . taxClientSetSql($tax_input) : '') . billingClientLegacySql());
|
||||
$client_id = mysqli_insert_id($mysqli);
|
||||
|
||||
if (!file_exists("../uploads/clients/$client_id")) {
|
||||
mkdir("../uploads/clients/$client_id");
|
||||
file_put_contents("../uploads/clients/$client_id/index.php", "");
|
||||
}
|
||||
|
||||
// Its primary location and contact - when the row has them
|
||||
if ($in('location_name') . $in('location_phone') . $in('location_address') . $in('location_city') . $in('location_state') . $in('location_zip') . $in('location_country') !== '') {
|
||||
$location_name = escapeSql(mb_substr($in('location_name') !== '' ? $in('location_name') : 'Primary', 0, 200));
|
||||
mysqli_query($mysqli, "INSERT INTO locations SET location_name = '$location_name', location_address = '" . escapeSql($in('location_address')) . "', location_city = '" . escapeSql($in('location_city')) . "',
|
||||
location_state = '" . escapeSql($in('location_state')) . "', location_zip = '" . escapeSql($in('location_zip')) . "', location_country = '" . escapeSql($in('location_country')) . "',
|
||||
" . $phone($in('location_phone'), 'location_phone') . ", location_primary = 1, location_client_id = $client_id");
|
||||
}
|
||||
if ($in('contact_name') . $in('contact_email') . $in('contact_phone') . $in('contact_mobile') !== '') {
|
||||
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '" . escapeSql($in('contact_name') !== '' ? $in('contact_name') : $in('contact_email')) . "', contact_title = '" . escapeSql($in('contact_title')) . "',
|
||||
" . $phone($in('contact_phone'), 'contact_phone') . ", contact_extension = '" . preg_replace('/\D/', '', $in('contact_extension')) . "', " . $phone($in('contact_mobile'), 'contact_mobile') . ",
|
||||
contact_email = '" . escapeSql($in('contact_email')) . "', contact_primary = 1, contact_important = 1, contact_client_id = $client_id");
|
||||
}
|
||||
|
||||
if ($in('client_tags') !== '') {
|
||||
tagSetForRecord('client', $client_id, importTagIds('client', $in('client_tags')));
|
||||
}
|
||||
|
||||
// An hourly rate or payment terms other than the defaults become the client's Standard terms contract (functions/contract.php)
|
||||
$hourly_rate = $in('hourly_rate') !== '' ? floatval(str_replace([',', '$'], '', $in('hourly_rate'))) : null;
|
||||
$payment_terms = is_numeric($in('payment_terms')) ? max(0, min(365, intval($in('payment_terms')))) : null;
|
||||
if (function_exists('contractsReady') && contractsReady() && contractStandardTermsAdd($client_id, $hourly_rate, $payment_terms, [], null, 'Made by the client import from its Hourly Rate and Payment Terms.')) {
|
||||
$terms_count++;
|
||||
}
|
||||
|
||||
$row_count++;
|
||||
}
|
||||
|
||||
//Check for any errors, if there are notify user and redirect
|
||||
if ($error) {
|
||||
redirect();
|
||||
}
|
||||
$left_out = importNotesText($notes + ['rows with no Client Name' => $no_name_count]);
|
||||
logAudit("Client", "Import", "$session_name imported $row_count client(s) via CSV file, $duplicate_count duplicate(s) found" . ($left_out !== '' ? " - $left_out" : ''));
|
||||
|
||||
flashAlert("<strong>$row_count</strong> Client(s) added, <strong>$duplicate_count</strong> duplicate(s) found"
|
||||
. ($terms_count ? ", <strong>$terms_count</strong> with a Standard terms contract for their own rate or payment terms" : '')
|
||||
. ($left_out !== '' ? ' - ' . escapeHtml($left_out) : '')
|
||||
. ($ignored ? '. Columns not imported: ' . escapeHtml(implode(', ', array_slice($ignored, 0, 8)) . (count($ignored) > 8 ? ' and ' . (count($ignored) - 8) . ' more' : '')) : ''),
|
||||
$left_out !== '' || $ignored ? 'warning' : 'success');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_GET['download_clients_csv_template'])) {
|
||||
|
||||
$delimiter = ",";
|
||||
$enclosure = '"';
|
||||
$escape = '\\'; // backsla
|
||||
$filename = "Clients-Template.csv";
|
||||
enforceUserPermission('module_client');
|
||||
|
||||
//create a file pointer
|
||||
$f = fopen('php://memory', 'w');
|
||||
|
||||
//set column headers
|
||||
$fields = array('Client Name', 'Industry', 'Referral', 'Website', 'Primary Location Name', 'Location Phone', 'Location Address', 'City', 'State', 'Postal Code', 'Country', 'Primary Contact Name', 'Title', 'Contact Phone', 'Extension', 'Contact Mobile', 'Contact Email', 'Hourly Rate', 'Currency', 'Payment Terms', 'Tax ID', 'Abbreviation');
|
||||
fputcsv($f, $fields, $delimiter, $enclosure, $escape);
|
||||
|
||||
//move back to beginning of file
|
||||
fseek($f, 0);
|
||||
|
||||
//set headers to download file rather than displayed
|
||||
header('Content-Type: text/csv');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '";');
|
||||
|
||||
//output all remaining data on a file pointer
|
||||
fpassthru($f);
|
||||
|
||||
exit;
|
||||
importTemplateDownload('clients', 'Clients-Template.csv');
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user