Hooked various the contents of the components together

This commit is contained in:
Brady Wetherington 2023-03-21 22:26:32 -07:00
parent 704a2ad858
commit 6fe520a55d
4 changed files with 140 additions and 204 deletions

View file

@ -17,10 +17,9 @@ class Importer extends Component
use AuthorizesRequests;
public $files;
public $processDetails;
public $progress; //upload progress - '-1' means don't show
public $progress_message; //progress message
public $progress_message;
public $progress_bar_class;
public $message; //status/error message?
@ -28,7 +27,7 @@ class Importer extends Component
//originally from ImporterFile
public $import_errors; //
public $activeFile; //this gets automatically populated on instantiation (no, it doesn't)
public ?Import $activeFile = null;
public $importTypes;
public $columnOptions;
public $statusType;
@ -37,32 +36,29 @@ class Importer extends Component
public $send_welcome;
public $run_backup;
public $field_map; // we need a separate variable for the field-mapping, because the keys in the normal array are too complicated for Livewire to understand
public $file_id; // TODO: I can't figure out *why* we need this, but it really seems like we do. I can't seem to pull the id from the activeFile for some reason?
protected $rules = [
'files.*.file_path' => 'required|string',
'files.*.created_at' => 'required|string',
'files.*.filesize' => 'required|integer',
'activeFile' => 'Import',
'activeFile.import_type' => 'string',
'activeFile.field_map' => 'array',
'activeFile.header_row' => 'array',
'field_map' => 'array'
];
protected $listeners = [
'hideDetails' => 'hideDetails',
'importError' => 'importError',
'alert' => 'alert',
'refreshMe' => '$refresh'
]; // TODO - try using the 'short' form of this?
public function generate_field_map()
{
\Log::debug("header row is: ".print_r($this->activeFile->header_row,true));
\Log::debug("Field map is: ".print_r($this->field_map,true));
$tmp = array_combine($this->activeFile->header_row, $this->field_map);
return json_encode(array_filter($tmp));
}
// all of these 'statics', alas, may have to change to something else to handle translations?
// I'm not sure. Maybe I use them to 'populate' the translations? TBH, I don't know yet.
static $general = [
'category' => 'Category',
'company' => 'Company',
@ -169,7 +165,7 @@ class Importer extends Component
private function getColumns($type)
{
switch($type) {
switch ($type) {
case 'asset':
$results = self::$general + self::$assets;
break;
@ -188,11 +184,11 @@ class Importer extends Component
default:
$results = self::$general;
}
asort($results, SORT_FLAG_CASE|SORT_STRING);
if($type == "asset") {
asort($results, SORT_FLAG_CASE | SORT_STRING);
if ($type == "asset") {
// add Custom Fields after a horizontal line
$results['-'] = "———".trans('admin/custom_fields/general.custom_fields')."———’";
foreach(CustomField::orderBy('name')->get() AS $field) {
$results['-'] = "———" . trans('admin/custom_fields/general.custom_fields') . "———’";
foreach (CustomField::orderBy('name')->get() as $field) {
$results[$field->db_column_name()] = $field->name;
}
}
@ -202,9 +198,10 @@ class Importer extends Component
public function updating($name, $new_import_type)
{
if ($name == "activeFile.import_type") {
\Log::info("WE ARE CHANGING THE import_type!!!!! TO: ".$new_import_type);
\Log::info("WE ARE CHANGING THE import_type!!!!! TO: " . $new_import_type);
\Log::info("so, what's \$this->>field_map at?: " . print_r($this->field_map, true));
// go through each header, find a matching field to try and map it to.
foreach($this->activeFile->header_row as $i => $header) {
foreach ($this->activeFile->header_row as $i => $header) {
// do we have something mapped already?
if (array_key_exists($i, $this->field_map)) {
// yes, we do. Is it valid for this type of import?
@ -219,16 +216,16 @@ class Importer extends Component
} // TODO - strictly speaking, this isn't necessary here I don't think.
}
// first, check for exact matches
foreach ($this->columnOptions[$new_import_type] AS $value => $text) {
foreach ($this->columnOptions[$new_import_type] as $value => $text) {
if (strcasecmp($text, $header) === 0) { // case-INSENSITIVe on purpose!
$this->field_map[$i] = $value;
continue 2; //don't bother with the alias check, go to the next header
}
}
// if you got here, we didn't find a match. Try the aliases
foreach(self::$aliases as $key => $alias_values) {
foreach($alias_values as $alias_value) {
if (strcasecmp($alias_value,$header) === 0) { // aLsO CaSe-INSENSitiVE!
foreach (self::$aliases as $key => $alias_values) {
foreach ($alias_values as $alias_value) {
if (strcasecmp($alias_value, $header) === 0) { // aLsO CaSe-INSENSitiVE!
// Make *absolutely* sure that this key actually _exists_ in this import type -
// you can trigger this by importing accessories with a 'Warranty' column (which don't exist
// in "Accessories"!)
@ -245,6 +242,10 @@ class Importer extends Component
}
}
public function boot() { // FIXME - delete or undelete.
///////$this->activeFile = null; // I do *not* understand why I have to do this, but, well, whatever.
}
public function mount()
{
@ -270,56 +271,30 @@ class Importer extends Component
}
}
public function hideMessages()
public function selectFile($id)
{
$this->message='';
}
public function importError($errors)
{
\Log::debug("Errors fired!!!!");
\Log::debug(" Here they are...".print_r($errors,true));
$this->import_errors = $errors;
}
public function alert($obj)
{
\Log::debug("Alert object received: ".print_r($obj,true));
$this->message = $obj;
$this->message_type = "danger";
}
public function boot() // well, fuck.
{
\Log::error("HEY WE ARE DOING FOR THE BOOOTTS!!!!");
$this->processDetails = null;
}
public function toggleEvent($id)
{
// do something here?
// I mean, I kinda don't get it?
$gonna_refresh = !!$this->processDetails;
if($this->processDetails) {
$this->processDetails = null;
}
\Log::info("TOGGLE EVENT FIRED!");
\Log::error("The ID we are trying to find is AS FOLLOWS: ".$id);
$this->processDetails = Import::find($id);
// $this->emit('refreshFile'); ///FUUUUUUUUUUUUUU
///
// }
/// Just literally none of this fucking shit works.
\Log::error("The import type we are about to try and load up is gonna be this: ".$this->processDetails->import_type);
$this->activeFile = Import::find($id);
$this->field_map = null;
foreach($this->activeFile->header_row as $element) {
if(isset($this->activeFile->field_map[$element])) {
$this->field_map[] = $this->activeFile->field_map[$element];
} else {
$this->field_map[] = null; // re-inject the 'nulls' if a file was imported with some 'Do Not Import' settings
}
}
//$this->field_map = $this->activeFile->field_map ? array_values($this->activeFile->field_map) : []; // this is wrong
$this->file_id = $id;
$this->import_errors = null;
$this->statusText = null;
\Log::error("The import type we are about to try and load up is gonna be this: ".$this->activeFile->import_type);
}
public function hideDetails()
{
$this->processDetails = null;
}
public function destroy($id)
{
// TODO: why don't we just do File::find($id)? This seems dumb.
foreach($this->files as $file) {
\Log::debug("File id is: ".$file->id);
if($id == $file->id) {

View file

@ -1,54 +0,0 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\CustomField;
use Log;
class ImporterFile extends Component
{
protected $listeners = [
'refreshFile' => '$refresh'
];
public function updatedActiveFile()
{
\Log::error("We have updated the active file! WHOOOO!!");
// unset all of the input doodads,
// maybe unset or reset some properties up in here.
}
public function mount()
{
}
public function postSave()
{
//does this, like, do anything, or get used by anything?
if (!$this->activeFile->import_type) {
Log::error("didn't find an import type :(");
$this->statusType ='error';
$this->statusText = "An import type is required... "; // TODO - translate me!
return false;
}
$this->statusType = 'pending';
$this->statusText = trans('admin/hardware/form.processing_spinner');
}
public function render()
{
return view('livewire.importer-file');
}
}

View file

@ -10,7 +10,7 @@
@if($message != '')
<div class="col-md-12" class="{{ $message_type }}">
<div class="alert alert-{{ $this->message_type }} ">
<button type="button" class="close" wire:click="hideMessages">&times;</button>
<button type="button" class="close" wire:click="$set('message','')">&times;</button>
@if($message_type == 'success')
<i class="fas fa-check faa-pulse animated" aria-hidden="true"></i>
@endif
@ -34,15 +34,23 @@
<th>{{ trans('general.error') }}</th>
</thead>
<tbody>
@foreach($import_errors as $field => $error_list)
<tr>
<td>{{ $processDetails->file_path ?? "Unknown File" }}</td>
<td>
<b>{{ $field }}:</b>
<span>{{ implode(", ",$error_list) }}</span>
<br />
</td>
</tr>
@php \Log::error("import errors are: ".print_r($import_errors,true)); @endphp
@foreach($import_errors AS $key => $actual_import_errors)
@php \Log::error("Key is: $key"); @endphp
@foreach($actual_import_errors AS $table => $error_bag)
@php \Log::error("Table is: $table"); @endphp
@foreach($error_bag as $field => $error_list)
@php \Log::error("Field is: $field"); @endphp
<tr>
<td>{{ $activeFile->file_path ?? "Unknown File" }}</td>
<td>
<b>{{ $field }}:</b>
<span>{{ implode(", ",$error_list) }}</span>
<br />
</td>
</tr>
@endforeach
@endforeach
@endforeach
</tbody>
</table>
@ -112,12 +120,12 @@
@foreach($files as $currentFile)
<tr wire:key="current-file-selection-{{ $currentFile->id }}" style="{{ ($processDetails && ($currentFile->id == $processDetails->id)) ? 'font-weight: bold' : '' }}" class="{{ ($processDetails && ($currentFile->id == $processDetails->id)) ? 'warning' : '' }}">
<tr style="{{ ($activeFile && ($currentFile->id == $activeFile->id)) ? 'font-weight: bold' : '' }}" class="{{ ($activeFile && ($currentFile->id == $activeFile->id)) ? 'warning' : '' }}">
<td class="col-md-6">{{ $currentFile->file_path }}</td>
<td class="col-md-3">{{ Helper::getFormattedDateObject($currentFile->created_at, 'datetime', false) }}</td>
<td class="col-md-1">{{ Helper::formatFilesizeUnits($currentFile->filesize) }}</td>
<td class="col-md-1 text-right">
<button class="btn btn-sm btn-info" wire:click="$set('activeFile',{{ $currentFile->id }})">
<button class="btn btn-sm btn-info" wire:click="selectFile({{ $currentFile->id }})">
<i class="fas fa-retweet fa-fw" aria-hidden="true"></i>
<span class="sr-only">{{ trans('general.import') }}</span>
</button>
@ -125,12 +133,10 @@
<i class="fas fa-trash icon-white" aria-hidden="true"></i><span class="sr-only"></span></button>
</td>
</tr>
<?php
\Log::error("Current file is: ".$currentFile->id);
?>
@if( $currentFile && $processDetails && ($currentFile->id == $processDetails->id))
@if( $currentFile && $activeFile && ($currentFile->id == $activeFile->id))
<tr class="warning">
<td colspan="4" >
<td colspan="4">
<div class="col-md-12">
@ -148,8 +154,7 @@
'data-placeholder' => trans('general.select_var', ['thing' => trans('general.import_type')]), /* TODO: translate me */
'placeholder' => '', //needed so that the form-helper will put an empty option first
'data-minimum-results-for-search' => '-1', // Remove this if the list gets long enough that we need to search
'data-livewire-component' => $_instance->id,
'onchange' => "console.log('FAAAAAAAARTs');return true"
'data-livewire-component' => $_instance->id
]) }}
</div>
</div>
@ -234,7 +239,7 @@
<div class="form-group col-md-12">
<div class="col-md-3 text-left">
<a href="#" wire:click="$emit('hideDetails')">{{ trans('general.cancel') }}</a>
<a href="#" wire:click="$set('activeFile',null)">{{ trans('general.cancel') }}</a>
</div>
<div class="col-md-9">
<button type="submit" class="btn btn-primary col-md-5" id="import">Import</button>
@ -247,73 +252,18 @@
{{ $statusText }}
</div>
@endif
@else
<div class="form-group col-md-12">
<div class="col-md-3 text-left">
<a href="#" wire:click="$set('activeFile',null)"><?php echo e(trans('general.cancel')); ?></a>
</div>
</div>
@endif {{-- end of if ... activeFile->import_type --}}
<script>
$(function () {
// initialize iCheck for use with livewire
$('.minimal.livewire-icheck').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
})
// we have to hook up to the `<tr id='importer-file'>` at the root of this display,
// because the #import button isn't visible until you click an import_type
$('#importer-file').on('click', '#import', function () {
console.warn("You clicked it!!!!")
if(!@this.activeFile.import_type) {
@this.statusType='error';
@this.statusText= "An import type is required... "; //TODO: translate?
return;
}
@this.statusType ='pending';
@this.statusText = "{{ trans('admin/hardware/form.processing_spinner') }}";
@this.generate_field_map().then(function (mappings_raw) {
var mappings = JSON.parse(mappings_raw)
// console.warn("Here is the mappings:")
// console.dir(mappings)
$.post({
url: "{{ route('api.imports.importFile', $activeFile->id) }}",
contentType: 'application/json',
data: JSON.stringify({
'import-update': !!@this.update,
'send-welcome': !!@this.send_welcome,
'import-type': @this.activeFile.import_type,
'run-backup': !!@this.run_backup,
'column-mappings': mappings
}),
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content')
}
}).done( function (body) {
// Success
@this.statusType="success";
@this.statusText = "Success... Redirecting.";
console.dir(body)
window.location.href = body.messages.redirect_url;
}).fail( function (jqXHR, textStatus, error) {
// Failure
var body = jqXHR.responseJSON
if(body.status == 'import-errors') {
@this.emit('importError', body.messages);
@this.statusType='error';
@this.statusText = "Error";
} else {
console.warn("Not import-errors, just regular errors")
console.dir(body)
@this.emit('alert', body.error)
}
@this.emit('hideDetails')
});
})
return false;
});})
</script>
</div><!-- /div v-show -->
</td>
</div><!-- /div v-show --> </td>
</tr>
@endif
</tr>
@endforeach
</table>
</div>
@ -328,7 +278,6 @@
</div>
</div>
</div> {{-- DID I HAVE A MISSING CLOSING DIV HERE? PROBABLY!!!! --}}
@push('js')
<script>
@ -363,5 +312,71 @@
@this.progress_message = error_message;
}
})
// For the importFile part:
$(function () {
// initialize iCheck for use with livewire
$('.minimal.livewire-icheck').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
})
// we have to hook up to the `<tr id='importer-file'>` at the root of this display,
// because the #import button isn't visible until you click an import_type
$('#upload-table').on('click', '#import', function () {
if(!@this.activeFile.import_type) {
@this.statusType='error';
@this.statusText= "An import type is required... "; //TODO: translate?
return;
}
@this.statusType ='pending';
@this.statusText = "{{ trans('admin/hardware/form.processing_spinner') }}";
@this.generate_field_map().then(function (mappings_raw) {
var mappings = JSON.parse(mappings_raw)
// console.warn("Here is the mappings:")
// console.dir(mappings)
// console.warn("Uh, active file id is, I guess: "+@this.activeFile.id)
var this_file = @this.file_id; // okay, I actually don't know what I'm doing here.
$.post({
{{-- I want to do something like: route('api.imports.importFile', $activeFile->id) }} --}}
url: "api/v1/imports/process/"+this_file, // maybe? Good a guess as any..FIXME. HARDCODED DUMB FILE
contentType: 'application/json',
data: JSON.stringify({
'import-update': !!@this.update,
'send-welcome': !!@this.send_welcome,
'import-type': @this.activeFile.import_type,
'run-backup': !!@this.run_backup,
'column-mappings': mappings
}),
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content')
}
}).done( function (body) {
// Success
@this.statusType="success";
@this.statusText = "Success... Redirecting.";
// console.dir(body)
window.location.href = body.messages.redirect_url;
}).fail( function (jqXHR, textStatus, error) {
// Failure
var body = jqXHR.responseJSON
if(body.status == 'import-errors') {
@this.emit('importError', body.messages);
@this.import_errors = body.messages
@this.statusType='error';
@this.statusText = "Error";
} else {
console.warn("Not import-errors, just regular errors")
console.dir(body)
{{-- @this.emit('alert', body.error)--}}
@this.message_type="danger"
@this.message = body.error
}
@this.activeFile = null; //@this.set('hideDetails')
});
})
return false;
});})
</script>
@endpush