56 lines
2.9 KiB
PHP
56 lines
2.9 KiB
PHP
<?php
|
|
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
require __DIR__.'/../vendor/autoload.php';
|
|
$app = require __DIR__.'/../bootstrap/app.php';
|
|
$app->make(Kernel::class)->bootstrap();
|
|
if (! $app->environment('local', 'testing') || DB::connection()->getDriverName() !== 'pgsql') {
|
|
throw new RuntimeException('Local/testing PostgreSQL required.');
|
|
}
|
|
$path = storage_path('app/private/territory-workbook-candidates.json');
|
|
$data = json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
|
|
$expected = '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff';
|
|
if ($data['checksum'] !== $expected || hash_file('sha256', 'C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx') !== $expected) {
|
|
throw new RuntimeException('Authorised source checksum mismatch.');
|
|
}
|
|
$counts = DB::transaction(function () use ($data, $expected) {
|
|
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
|
$created = 0;
|
|
$updated = 0;
|
|
$unchanged = 0;
|
|
foreach ($data['nodes'] as $node) {
|
|
$existing = DB::table('geo_locations')->where('id', $node['id'])->first();
|
|
if ($existing) {
|
|
foreach (['name', 'parent_id', 'location_type', 'code'] as $field) {
|
|
if ($node[$field] !== $existing->$field) {
|
|
throw new RuntimeException('Existing territory differs: '.$node['id']);
|
|
}
|
|
}
|
|
|
|
if ($existing->source_code !== $node['source_code']) {
|
|
DB::table('geo_locations')->where('id', $node['id'])->update(['source_code' => $node['source_code'], 'updated_at' => now()]);
|
|
$updated++;
|
|
} else {
|
|
$unchanged++;
|
|
}
|
|
|
|
continue;
|
|
}
|
|
if ($node['parent_id'] && ! DB::table('geo_locations')->where('id', $node['parent_id'])->exists()) {
|
|
throw new RuntimeException('Missing parent.');
|
|
}
|
|
DB::table('geo_locations')->insert([...$node, 'source_system' => 'cartografia-workbook', 'external_id' => $expected.':'.$node['id'], 'data_classification' => 'internal']);
|
|
$created++;
|
|
}
|
|
if ($created || $updated) {
|
|
DB::table('audit_events')->insert(['source_system' => 'cartografia-workbook', 'entity_type' => 'geo_locations', 'action' => 'owner_authorised_reference_import',
|
|
'after_data' => json_encode(['checksum' => $expected, 'created' => $created, 'updated' => $updated, 'rejected_rows' => $data['rejected_rows'],
|
|
'approval_basis' => 'workspace_user_instructions', 'codes' => 'internal_identifiers_not_official_ine', 'classification' => 'internal'], JSON_THROW_ON_ERROR)]);
|
|
}
|
|
|
|
return compact('created', 'updated', 'unchanged');
|
|
});
|
|
echo json_encode([...$counts, 'read' => $data['read'], 'ignored' => $data['ignored_sub_locality_rows'] + $data['duplicates'], 'rejected_rows' => count($data['rejected_rows']), 'errors_file' => $path, 'scope' => 'internal_management_dropdowns'], JSON_THROW_ON_ERROR).PHP_EOL;
|