diff --git a/extensions/igniter/automation/.editorconfig b/extensions/igniter/automation/.editorconfig deleted file mode 100644 index 1173f22..0000000 --- a/extensions/igniter/automation/.editorconfig +++ /dev/null @@ -1,15 +0,0 @@ -root = true - -[*] -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -indent_style = space -indent_size = 4 - -[*.md] -trim_trailing_whitespace = false - -[*.{yml, yaml, json, scss, css}] -indent_size = 2 diff --git a/extensions/igniter/automation/.gitignore b/extensions/igniter/automation/.gitignore deleted file mode 100644 index fc647ca..0000000 --- a/extensions/igniter/automation/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -.DS_Store -.idea -.php_cs -.php_cs.cache -.phpunit.result.cache -build -composer.lock -coverage -docs -phpunit.xml -psalm.xml -vendor -.php-cs-fixer.cache diff --git a/extensions/igniter/automation/Extension.php b/extensions/igniter/automation/Extension.php deleted file mode 100755 index a16a899..0000000 --- a/extensions/igniter/automation/Extension.php +++ /dev/null @@ -1,102 +0,0 @@ -registerConsoleCommand('automation.cleanup', Console\Cleanup::class); - } - - public function boot() - { - EventManager::bindRules(); - - $this->extendActionFormFields(); - } - - public function registerPermissions() - { - return [ - 'Igniter.Automation.Manage' => [ - 'description' => 'Create, modify and delete automations', - 'group' => 'module', - ], - ]; - } - - public function registerNavigation() - { - return [ - 'tools' => [ - 'child' => [ - 'automation' => [ - 'priority' => 5, - 'class' => 'automation', - 'href' => admin_url('igniter/automation/automations'), - 'title' => lang('igniter.automation::default.text_title'), - 'permission' => 'Igniter.Automation.*', - ], - ], - ], - ]; - } - - public function registerAutomationRules() - { - return [ - 'events' => [ - 'automation.order.schedule.hourly' => \Igniter\Automation\AutomationRules\Events\OrderSchedule::class, - 'automation.reservation.schedule.hourly' => \Igniter\Automation\AutomationRules\Events\ReservationSchedule::class, - ], - 'actions' => [ - \Igniter\Automation\AutomationRules\Actions\AssignToGroup::class, - \Igniter\Automation\AutomationRules\Actions\SendMailTemplate::class, - ], - 'conditions' => [], - ]; - } - - /** - * Registers scheduled tasks that are executed on a regular basis. - * - * @param \Illuminate\Console\Scheduling\Schedule $schedule - * @return void - */ - public function registerSchedule($schedule) - { - $schedule->call(function () { - // Pull orders created within the last 30days - EventManager::fireOrderScheduleEvents(); - })->name('automation-order-schedule')->withoutOverlapping(5)->runInBackground()->hourly(); - - $schedule->call(function () { - // Pull reservations booked within the last 30days - EventManager::fireReservationScheduleEvents(); - })->name('automation-reservation-schedule')->withoutOverlapping(5)->runInBackground()->hourly(); - - $schedule->command('automation:cleanup')->name('Automation Log Cleanup')->daily(); - } - - protected function extendActionFormFields() - { - Event::listen('admin.form.extendFieldsBefore', function (Form $form) { - if (!$form->getController() instanceof \Igniter\Automation\Controllers\Automations) { - return; - } - if ($form->model instanceof \Igniter\Automation\Models\RuleAction) { - $form->arrayName .= '[options]'; - $form->fields = array_get($form->model->getFieldConfig(null), 'fields', []); - } - }); - } -} diff --git a/extensions/igniter/automation/LICENSE.md b/extensions/igniter/automation/LICENSE.md deleted file mode 100644 index a666e59..0000000 --- a/extensions/igniter/automation/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Samuel Adepoyigi - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/extensions/igniter/automation/README.md b/extensions/igniter/automation/README.md deleted file mode 100644 index d92b7b5..0000000 --- a/extensions/igniter/automation/README.md +++ /dev/null @@ -1,31 +0,0 @@ -### Introduction - -Automation within TastyIgniter fire when other specific actions have taken place. Rules are run through every time an -order state is changed and triggered if the changes match the conditions defined in the rule. - -An action is attached to the automation, such as send mail to customer or send print jobs to printer. - -### Documentation - -Documentation for TastyIgniter Automation extension can be found on -the [TastyIgniter website](https://tastyigniter.com/docs/extensions/automation). - -### Contributing - -Thank you for considering contributing! The contribution guide can be found in -the [TastyIgniter documentation](https://tastyigniter.com/docs/contribution-guide). - -### Code of Conduct - -In order to ensure that the [TastyIgniter community](https://forum.tastyigniter.com) is welcoming to all, please review -and abide by the [Code of Conduct](https://tastyigniter.com/docs/code-of-conduct). - -### Security Vulnerabilities - -Please review [our security policy](https://github.com/tastyigniter/ti-ext-automation/security/policy) on how to report -security vulnerabilities. - -### License - -TastyIgniter Automation extension is open-sourced software licensed under -the [MIT license](https://github.com/tastyigniter/ti-ext-automation/LICENSE.md). diff --git a/extensions/igniter/automation/automationrules/actions/AssignToGroup.php b/extensions/igniter/automation/automationrules/actions/AssignToGroup.php deleted file mode 100644 index e9327f9..0000000 --- a/extensions/igniter/automation/automationrules/actions/AssignToGroup.php +++ /dev/null @@ -1,53 +0,0 @@ - 'Assign to staff group', - 'description' => 'Automatically assign an order/reservation to a staff group', - ]; - } - - public function defineFormFields() - { - return [ - 'fields' => [ - 'staff_group_id' => [ - 'label' => 'lang:igniter.automation::default.label_assign_to_staff_group', - 'type' => 'select', - 'options' => [\Admin\Models\Staff_groups_model::class, 'getDropdownOptions'], - ], - ], - ]; - } - - public function triggerAction($params) - { - if (!$groupId = $this->model->staff_group_id) { - throw new ApplicationException('Missing valid staff group to assign to.'); - } - - if (!$assigneeGroup = Staff_groups_model::find($groupId)) { - throw new ApplicationException('Invalid staff group to assign to.'); - } - - $assignable = array_get($params, 'order', array_get($params, 'reservation')); - if (!in_array(Assignable::class, class_uses_recursive(get_class($assignable)))) { - throw new ApplicationException('Missing assignable model.'); - } - - $log = $assignable->assignToGroup($assigneeGroup); - - AssigneeUpdated::log($log); - } -} diff --git a/extensions/igniter/automation/automationrules/actions/SendMailTemplate.php b/extensions/igniter/automation/automationrules/actions/SendMailTemplate.php deleted file mode 100644 index b403c96..0000000 --- a/extensions/igniter/automation/automationrules/actions/SendMailTemplate.php +++ /dev/null @@ -1,166 +0,0 @@ - 'Compose a mail template', - 'description' => 'Send a message to a recipient', - ]; - } - - public function defineFormFields() - { - return [ - 'fields' => [ - 'template' => [ - 'label' => 'lang:igniter.user::default.label_template', - 'type' => 'select', - ], - 'send_to' => [ - 'label' => 'lang:igniter.user::default.label_send_to', - 'type' => 'select', - ], - 'staff_group' => [ - 'label' => 'lang:igniter.user::default.label_send_to_staff_group', - 'type' => 'select', - 'options' => [\Admin\Models\Staff_groups_model::class, 'getDropdownOptions'], - 'trigger' => [ - 'action' => 'show', - 'field' => 'send_to', - 'condition' => 'value[staff_group]', - ], - ], - 'customer_group' => [ - 'label' => 'lang:igniter.automation::default.label_send_to_customer_group', - 'type' => 'select', - 'options' => [\Admin\Models\Customer_groups_model::class, 'getDropdownOptions'], - 'trigger' => [ - 'action' => 'show', - 'field' => 'send_to', - 'condition' => 'value[customer_group]', - ], - ], - 'custom' => [ - 'label' => 'lang:igniter.user::default.label_send_to_custom', - 'type' => 'text', - 'trigger' => [ - 'action' => 'show', - 'field' => 'send_to', - 'condition' => 'value[custom]', - ], - ], - ], - ]; - } - - public function triggerAction($params) - { - if (!$templateCode = $this->model->template) { - throw new ApplicationException('SendMailTemplate: Missing a valid mail template'); - } - - if (!$recipient = $this->getRecipientAddress($params)) { - throw new ApplicationException('SendMailTemplate: Missing a valid recipient from the event payload'); - } - - Mail::sendToMany($recipient, $templateCode, $params); - } - - public function getTemplateOptions() - { - return Mail_templates_model::dropdown('label', 'code'); - } - - public function getSendToOptions() - { - return [ - 'restaurant' => 'lang:igniter.user::default.text_send_to_restaurant', - 'location' => 'lang:igniter.user::default.text_send_to_location', - 'staff' => 'lang:igniter.user::default.text_send_to_staff_email', - 'staff_group' => 'lang:igniter.user::default.text_send_to_staff_group', - 'customer' => 'lang:igniter.user::default.text_send_to_customer_email', - 'customer_group' => 'lang:igniter.user::default.text_send_to_customer_group', - 'custom' => 'lang:igniter.user::default.text_send_to_custom', - ]; - } - - protected function getRecipientAddress($params) - { - $mode = $this->model->send_to; - - switch ($mode) { - case 'custom': - return $this->model->custom; - case 'system': - $name = config('mail.from.name', 'Your Site'); - $address = config('mail.from.address', 'admin@domain.tld'); - - return [$address => $name]; - case 'restaurant': - $name = setting('site_name', config('app.name')); - $address = setting('site_email', config('mail.from.address')); - - return [$address => $name]; - case 'location': - $location = array_get($params, 'location'); - if (empty($location->location_email) && empty($location->location_name)) { - return null; - } - - return [$location->location_email => $location->location_name]; - case 'staff_group': - if ($groupId = $this->model->staff_group) { - if (!$staffGroup = Staff_groups_model::find($groupId)) { - throw new ApplicationException('Unable to find staff group with ID: '.$groupId); - } - - return $staffGroup->staffs()->isEnabled()->pluck('staff_name', 'staff_email'); - } - - return null; - case 'customer_group': - if ($groupId = $this->model->customer_group) { - if (!$customerGroup = Customer_groups_model::find($groupId)) { - throw new ApplicationException('Unable to find customer group with ID: '.$groupId); - } - - return $customerGroup->customers()->isEnabled()->pluck('full_name', 'email'); - } - - return null; - case 'customer': - $customer = array_get($params, 'customer'); - if (!empty($customer->email) && !empty($customer->full_name)) { - return [$customer->email => $customer->full_name]; - } - - $fullName = array_get($params, 'first_name').' '.array_get($params, 'last_name'); - if (array_key_exists('email', $params)) { - return [$params['email'] => $fullName]; - } - - return null; - case 'staff': - $staff = array_get($params, 'staff'); - if (!empty($staff->staff_email) && !empty($staff->staff_name)) { - return [$staff->staff_email => $staff->staff_name]; - } - - $orderOrReservation = array_get($params, 'order', array_get($params, 'reservation')); - if ($orderOrReservation && $staff = $orderOrReservation->assignee) { - return [$staff->staff_email => $staff->staff_name]; - } - } - } -} diff --git a/extensions/igniter/automation/automationrules/events/OrderSchedule.php b/extensions/igniter/automation/automationrules/events/OrderSchedule.php deleted file mode 100644 index 9cedc06..0000000 --- a/extensions/igniter/automation/automationrules/events/OrderSchedule.php +++ /dev/null @@ -1,29 +0,0 @@ - 'Order Hourly Schedule', - 'description' => 'Performed on all recent orders once every hour', - 'group' => 'order', - ]; - } - - public static function makeParamsFromEvent(array $args, $eventName = null) - { - $params = []; - $order = array_get($args, 0); - if ($order instanceof Orders_model) { - $params = $order->mailGetData(); - } - - return $params; - } -} diff --git a/extensions/igniter/automation/automationrules/events/ReservationSchedule.php b/extensions/igniter/automation/automationrules/events/ReservationSchedule.php deleted file mode 100644 index 2b5f77b..0000000 --- a/extensions/igniter/automation/automationrules/events/ReservationSchedule.php +++ /dev/null @@ -1,29 +0,0 @@ - 'Reservation Hourly Schedule', - 'description' => 'Performed on all recent reservations once every hour', - 'group' => 'order', - ]; - } - - public static function makeParamsFromEvent(array $args, $eventName = null) - { - $params = []; - $reservation = array_get($args, 0); - if ($reservation instanceof Reservations_model) { - $params = $reservation->mailGetData(); - } - - return $params; - } -} diff --git a/extensions/igniter/automation/classes/AbstractBase.php b/extensions/igniter/automation/classes/AbstractBase.php deleted file mode 100644 index 7479432..0000000 --- a/extensions/igniter/automation/classes/AbstractBase.php +++ /dev/null @@ -1,13 +0,0 @@ -model = $model; - - $this->fieldConfig = $this->defineFormFields(); - - $this->initialize($model); - } - - /** - * Initialize method called when the action class is first loaded - * with an existing model. - * @return void - */ - public function initialize($model) - { - if (!$model) { - return; - } - - if (!$model->exists) { - $this->initConfigData($model); - } - - // Apply validation rules - $model->rules = array_merge($model->rules, $this->defineValidationRules()); - } - - /** - * Initializes configuration data when the action is first created. - * @param \Igniter\Flame\Database\Model $model - */ - public function initConfigData($model) - { - } - - /** - * Returns information about this action, including name and description. - */ - public function actionDetails() - { - return [ - 'name' => 'Action', - 'description' => 'Action description', - ]; - } - - /** - * Extra field configuration for the action. - */ - public function defineFormFields() - { - return []; - } - - /** - * Defines validation rules for the custom fields. - * @return array - */ - public function defineValidationRules() - { - return []; - } - - public function hasFieldConfig() - { - return (bool)$this->fieldConfig; - } - - public function getFieldConfig() - { - return $this->fieldConfig; - } - - public function triggerAction($params) - { - } - - public function getActionName() - { - return array_get($this->actionDetails(), 'name', 'Action'); - } - - public function getActionDescription() - { - return array_get($this->actionDetails(), 'description'); - } - - public static function findActions() - { - $results = []; - $ruleActions = (array)BaseEvent::findRulesValues('actions'); - foreach ($ruleActions as $actionClass) { - if (!class_exists($actionClass)) { - continue; - } - - $actionObj = new $actionClass; - $results[$actionClass] = $actionObj; - } - - return $results; - } -} diff --git a/extensions/igniter/automation/classes/BaseCondition.php b/extensions/igniter/automation/classes/BaseCondition.php deleted file mode 100644 index 0a63440..0000000 --- a/extensions/igniter/automation/classes/BaseCondition.php +++ /dev/null @@ -1,89 +0,0 @@ -model = $model; - - $this->initialize($model); - } - - /** - * Initialize method called when the action class is first loaded - * with an existing model. - * @return void - */ - public function initialize($model) - { - if (!$model) { - return; - } - - if (!$model->exists) { - $this->initConfigData($model); - } - } - - /** - * Initializes configuration data when the action is first created. - * @param \Igniter\Flame\Database\Model $model - */ - public function initConfigData($model) - { - } - - /** - * Returns information about this condition, including name and description. - */ - public function conditionDetails() - { - return [ - 'name' => 'Condition', - 'description' => 'Condition description', - ]; - } - - public function getConditionName() - { - return array_get($this->conditionDetails(), 'name', 'Condition'); - } - - public function getConditionDescription() - { - return array_get($this->conditionDetails(), 'Condition description'); - } - - /** - * Checks whether the condition is TRUE for specified parameters - * @param array $params - * @return bool - */ - public function isTrue(&$params) - { - return false; - } - - public static function findConditions() - { - $results = []; - $ruleConditions = (array)BaseEvent::findRulesValues('conditions'); - foreach ($ruleConditions as $conditionClass) { - if (!class_exists($conditionClass)) { - continue; - } - - $conditionObj = new $conditionClass; - $results[$conditionClass] = $conditionObj; - } - - return $results; - } -} diff --git a/extensions/igniter/automation/classes/BaseEvent.php b/extensions/igniter/automation/classes/BaseEvent.php deleted file mode 100644 index d60cb68..0000000 --- a/extensions/igniter/automation/classes/BaseEvent.php +++ /dev/null @@ -1,170 +0,0 @@ -model = $model; - } - - /** - * Returns information about this event, including name and description. - */ - public function eventDetails() - { - return [ - 'name' => 'Event', - 'description' => 'Event description', - 'group' => 'groupcode', - ]; - } - - /** - * Generates event parameters based on arguments from the triggering system event. - * @param string $eventName - * @return array - */ - public static function makeParamsFromEvent(array $args, $eventName = null) - { - return []; - } - - /** - * Sets multiple params. - * @param array $params - * @return void - */ - public function setEventParams($params) - { - $this->params = $params; - } - - /** - * Returns all params. - * @return array - */ - public function getEventParams() - { - return $this->params; - } - - /** - * Returns the event name. - * @return array - */ - public function getEventName() - { - return array_get($this->eventDetails(), 'name', 'Event'); - } - - /** - * Returns the event description. - * @return array - */ - public function getEventDescription() - { - return array_get($this->eventDetails(), 'description'); - } - - /** - * Returns the event group. - * @return array - */ - public function getEventGroup() - { - return array_get($this->eventDetails(), 'group'); - } - - /** - * Resolves an event or action identifier from the called class name or object. - * @param mixed Class name or object - * @return string Identifier in format of vendor-extension-class - */ - public function getEventIdentifier() - { - $namespace = normalize_class_name(get_called_class()); - if (strpos($namespace, '\\') === null) { - return $namespace; - } - - $parts = explode('\\', $namespace); - $class = array_pop($parts); - $slice = array_slice($parts, 1, 2); - $code = strtolower(implode('-', $slice).'-'.$class); - - return $code; - } - - public static function findRulesValues($key = null) - { - $results = []; - $automationRules = ExtensionManager::instance()->getRegistrationMethodValues('registerAutomationRules'); - if (is_null($key)) { - return $automationRules; - } - - foreach ($automationRules as $extension => $automationRule) { - if (!$values = array_get($automationRule, $key)) { - continue; - } - - if (!is_array($values)) { - $values = [$values]; - } - - foreach ($values as $index => $value) { - if (is_string($index)) { - $results[$index] = $value; - } else { - $results[] = $value; - } - } - } - - return $results; - } - - public static function findEvents() - { - $results = []; - foreach (self::findRulesValues('events') as $eventCode => $eventClass) { - if (!class_exists($eventClass)) { - continue; - } - - $eventObj = new $eventClass; - $results[$eventClass] = [$eventCode, $eventObj]; - } - - return $results; - } - - public static function findEventObjects() - { - $results = []; - foreach (self::findEvents() as $eventClass => [$eventCode, $eventObj]) { - $results[$eventClass] = $eventObj; - } - - return $results; - } - - public static function findEventPresets() - { - return self::findRulesValues('presets'); - } -} diff --git a/extensions/igniter/automation/classes/BaseModelAttributesCondition.php b/extensions/igniter/automation/classes/BaseModelAttributesCondition.php deleted file mode 100644 index ee684c0..0000000 --- a/extensions/igniter/automation/classes/BaseModelAttributesCondition.php +++ /dev/null @@ -1,216 +0,0 @@ - 'is', - 'is_not' => 'is not', - 'contains' => 'contains', - 'does_not_contain' => 'does not contain', - 'equals_or_greater' => 'equals or greater than', - 'equals_or_less' => 'equals or less than', - 'greater' => 'greater than', - 'less' => 'less than', - ]; - - public function initConfigData($model) - { - $model->operator = 'is'; - } - - public function defineModelAttributes() - { - return []; - } - - public function getConditionDescription() - { - $model = $this->model; - $attributes = $this->listModelAttributes(); - $subConditions = $model->options ?? []; - - $result = collect($subConditions)->sortBy('priority')->map(function ($subCondition) use ($attributes) { - $attribute = array_get($subCondition, 'attribute'); - $operator = array_get($subCondition, 'operator'); - $value = array_get($subCondition, 'value'); - - $result = $this->getConditionAttributePrefix($attribute, $attributes); - $result .= ' '.array_get($this->operators, $operator, $operator).' '; - $result .= $value; - - return $result; - })->toArray(); - - return implode(' AND ', $result); - } - - protected function getConditionAttributePrefix($attribute, $attributes) - { - $result = []; - if (isset($attributes[$attribute])) { - $result = $attributes[$attribute]; - } - - return array_get($result, 'label', 'Unknown attribute'); - } - - public function getAttributeOptions() - { - return array_map(function ($attribute) { - return array_get($attribute, 'label'); - }, $this->listModelAttributes()); - } - - public function getOperatorOptions() - { - return $this->operators; - } - - /** - * Checks whether the condition is TRUE for a specified model - * @return bool - */ - public function evalIsTrue($modelToEval) - { - $attributes = $this->listModelAttributes(); - $subConditions = $this->model->options ?? []; - - collect($subConditions)->sortBy('priority')->each(function ($subCondition) use (&$success, $modelToEval, $attributes) { - $attribute = array_get($subCondition, 'attribute'); - $attributeType = array_get($attributes, $attribute.'.type'); - - if ($attributeType == 'string') { - $success = $this->evalAttributeStringType($modelToEval, $subCondition); - } - - if ($attributeType == 'custom') { - $success = $this->evalAttributeCustomType($modelToEval, $subCondition); - } - - return $success; - }); - - return $success; - } - - protected function listModelAttributes() - { - if ($this->modelAttributes) { - return $this->modelAttributes; - } - - $attributes = array_map(function ($info) { - if (is_string($info)) { - $info = ['label' => $info]; - } - - isset($info['type']) || $info['type'] = 'string'; - - return $info; - }, $this->defineModelAttributes()); - - return $this->modelAttributes = $attributes; - } - - protected function evalAttributeStringType($model, $subCondition) - { - $attribute = array_get($subCondition, 'attribute'); - $operator = array_get($subCondition, 'operator'); - $conditionValue = array_get($subCondition, 'value'); - $conditionValue = is_array($conditionValue) ? $conditionValue : mb_strtolower(trim($conditionValue)); - $modelValue = $this->getModelEvalAttribute($model, $attribute, $subCondition); - - if ($operator === 'is') { - return $modelValue == $conditionValue; - } - - if ($operator === 'is_not') { - return $modelValue != $conditionValue; - } - - if ($operator === 'contains') { - return is_array($conditionValue) - ? in_array($modelValue, $conditionValue) !== false - : mb_strpos($modelValue, $conditionValue) !== false; - } - - if ($operator === 'does_not_contain') { - return is_array($conditionValue) - ? in_array($modelValue, $conditionValue) === false - : mb_strpos($modelValue, $conditionValue) === false; - } - - if ($operator === 'equals_or_greater') { - return $modelValue >= $conditionValue; - } - - if ($operator === 'equals_or_less') { - return $modelValue <= $conditionValue; - } - - if ($operator === 'greater') { - return $modelValue > $conditionValue; - } - - if ($operator === 'less') { - return $modelValue < $conditionValue; - } - - return false; - } - - protected function getModelEvalAttribute($model, $attribute, $condition = []) - { - $value = $model->{$attribute}; - - if (method_exists($this, 'get'.Str::studly($attribute).'Attribute')) { - $value = $this->{'get'.Str::studly($attribute).'Attribute'}($value, $model, $condition); - } - - return mb_strtolower(trim($value)); - } - - protected function applyDateRange($query, $attribute, $options) - { - $from = $this->getDateRangeFrom($options); - $to = $this->getDateRangeTo($options); - if ($from && $to) { - $query->whereBetween($attribute, [$from, $to]); - } - - return $query; - } - - protected function getDateRangeFrom(array $options) - { - if (array_get($options, 'when') === 'is_current') { - return now()->startOf(array_get($options, 'current', 'day'))->toDateTimeString(); - } - - if (array_get($options, 'when') === 'is_past') { - return now() - ->parse('- '.str_replace('_', ' ', array_get($options, 'range', '1_day'))) - ->startOfDay() - ->toDateTimeString(); - } - - return null; - } - - protected function getDateRangeTo(array $options) - { - if (array_get($options, 'when') === 'is_current') { - return now()->endOf(array_get($options, 'current', 'day'))->toDateTimeString(); - } - - if (array_get($options, 'when') === 'is_past') { - return now()->endOfDay()->toDateTimeString(); - } - - return null; - } -} diff --git a/extensions/igniter/automation/classes/EventManager.php b/extensions/igniter/automation/classes/EventManager.php deleted file mode 100644 index 5279260..0000000 --- a/extensions/igniter/automation/classes/EventManager.php +++ /dev/null @@ -1,150 +0,0 @@ - [$eventCode, $eventObj]) { - self::bindEvent($eventCode, $eventClass); - } - } - - public static function bindEvents(array $events) - { - foreach ($events as $event => $class) { - self::bindEvent($event, $class); - } - } - - public static function bindEvent($eventCode, $eventClass) - { - Event::listen($eventCode, function () use ($eventCode, $eventClass) { - if (!method_exists($eventClass, 'makeParamsFromEvent')) { - return; - } - - $params = $eventClass::makeParamsFromEvent(func_get_args(), $eventCode); - self::instance()->queueEvent($eventClass, $params); - }); - } - - public static function fireOrderScheduleEvents() - { - Orders_model::whereDate('order_date', '>=', now()->subDays(30)) - ->lazy() - ->each(function ($order) { - Event::fire('automation.order.schedule.hourly', [$order]); - }); - } - - public static function fireReservationScheduleEvents() - { - Reservations_model::whereDate('reserve_date', '>=', now()->subDays(30)) - ->lazy() - ->each(function ($reservation) { - Event::fire('automation.reservation.schedule.hourly', [$reservation]); - }); - } - - public function queueEvent($eventClass, array $params) - { - $params += $this->getContextParams(); - - // If available, push to queue - Queue::push(new EventParams($eventClass, $params)); - } - - public function fireEvent($eventClass, array $params) - { - $models = AutomationRule::listRulesForEvent($eventClass); - - $models->each(function ($model) use ($params) { - $model->setEventParams($params); - $model->triggerRule(); - }); - } - - /** - * Registers a callback function that defines context variables. - * The callback function should register context variables by calling the manager's - * `registerGlobalParams` method. The manager instance is passed to the callback - * function as an argument. Usage: - * - * Notifier::registerCallback(function($manager){ - * $manager->registerGlobalParams([...]); - * }); - * - * @param callable $callback A callable function. - */ - public function registerCallback(callable $callback) - { - $this->callbacks[] = $callback; - } - - public function registerGlobalParams(array $params) - { - if (!$this->registeredGlobalParams) { - $this->registeredGlobalParams = []; - } - - $this->registeredGlobalParams = $params + $this->registeredGlobalParams; - } - - public function getContextParams() - { - $this->processCallbacks(); - - $globals = $this->registeredGlobalParams ?: []; - - return [ - 'isAdmin' => App::runningInAdmin() ? 1 : 0, - 'isConsole' => App::runningInConsole() ? 1 : 0, - 'appLocale' => App::getLocale(), - ] + $globals; - } - - /** - * Helper to process callbacks once and once only. - * @return void - */ - protected function processCallbacks() - { - if ($this->registered) { - return; - } - - foreach ($this->callbacks as $callback) { - $callback($this); - } - - $this->registered = true; - } -} diff --git a/extensions/igniter/automation/composer.json b/extensions/igniter/automation/composer.json deleted file mode 100644 index 9ee42cb..0000000 --- a/extensions/igniter/automation/composer.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "tastyigniter/ti-ext-automation", - "type": "tastyigniter-extension", - "description": "Configure automation rules to be triggered when other specific actions have taken place.", - "license": "MIT", - "authors": [ - { - "name": "Sam Poyigi", - "email": "sam@sampoyigi.com" - } - ], - "extra": { - "tastyigniter-extension": { - "code": "igniter.automation", - "name": "Automation", - "icon": { - "class": "fa fa-tasks", - "backgroundColor": "#25C7EE", - "color": "#FFF" - }, - "homepage": "https://tastyigniter.com/marketplace/item/igniter-automation" - } - } -} diff --git a/extensions/igniter/automation/console/Cleanup.php b/extensions/igniter/automation/console/Cleanup.php deleted file mode 100644 index 27a29db..0000000 --- a/extensions/igniter/automation/console/Cleanup.php +++ /dev/null @@ -1,36 +0,0 @@ -comment('Cleaning old automation log...'); - $logTTL = now()->subDays(config('system.deleteOldRecordsDays', static::$logTTL))->format('Y-m-d H:i:s'); - - $amountDeleted = AutomationLog::query()->where('created_at', '<', $logTTL)->delete(); - - $this->info("Deleted {$amountDeleted} record(s) from the automation log."); - $this->comment('All done!'); - } -} diff --git a/extensions/igniter/automation/controllers/Automations.php b/extensions/igniter/automation/controllers/Automations.php deleted file mode 100755 index 6810281..0000000 --- a/extensions/igniter/automation/controllers/Automations.php +++ /dev/null @@ -1,127 +0,0 @@ - [ - 'model' => \Igniter\Automation\Models\AutomationRule::class, - 'title' => 'lang:igniter.automation::default.text_title', - 'emptyMessage' => 'lang:igniter.automation::default.text_empty', - 'defaultSort' => ['id', 'DESC'], - 'configFile' => 'automationrule', - ], - ]; - - public $formConfig = [ - 'name' => 'lang:igniter.automation::default.text_form_name', - 'model' => \Igniter\Automation\Models\AutomationRule::class, - 'create' => [ - 'title' => 'lang:admin::lang.form.create_title', - 'redirect' => 'igniter/automation/automations/edit/{id}', - 'redirectClose' => 'igniter/automation/automations', - ], - 'edit' => [ - 'title' => 'lang:admin::lang.form.edit_title', - 'redirect' => 'igniter/automation/automations/edit/{id}', - 'redirectClose' => 'igniter/automation/automations', - ], - 'preview' => [ - 'title' => 'lang:admin::lang.form.preview_title', - 'redirect' => 'igniter/automation/automations', - ], - 'delete' => [ - 'redirect' => 'igniter/automation/automations', - ], - 'configFile' => 'automationrule', - ]; - - protected $requiredPermissions = 'Igniter.Automation.*'; - - public function __construct() - { - parent::__construct(); - - AdminMenu::setContext('tools', 'automation'); - } - - public function index() - { - if ($this->getUser()->hasPermission('Igniter.Automation.Manage')) { - AutomationRule::syncAll(); - } - - $this->asExtension('ListController')->index(); - } - - public function edit_onLoadCreateActionForm($context, $recordId) - { - return $this->loadConnectorFormField('actions', $context, $recordId); - } - - public function edit_onLoadCreateConditionForm($context, $recordId) - { - return $this->loadConnectorFormField('conditions', $context, $recordId); - } - - public function formExtendFields($form) - { - if ($form->context != 'create') { - $form->getField('event_class')->disabled = true; - } - } - - public function formBeforeCreate($model) - { - $model->is_custom = true; - $model->status = true; - } - - public function formValidate($model, $form) - { - $rules = [ - ['event_class', 'lang:igniter.automation::default.label_event_class', 'sometimes|required'], - ]; - - return $this->validatePasses(post($form->arrayName), $rules); - } - - protected function loadConnectorFormField($method, $context, $recordId): array - { - $actionClass = post('AutomationRule._'.str_singular($method)); - if (!strlen($actionClass)) { - throw new ApplicationException(sprintf('Please select an %s to attach', str_singular($method))); - } - - $formController = $this->asExtension('FormController'); - $model = $formController->formFindModelObject($recordId); - - $model->$method()->create([ - 'class_name' => $actionClass, - 'automation_rule_id' => $recordId, - ]); - - $formController->initForm($model, $context); - $formField = $this->widgets['form']->getField($method); - - return [ - '#notification' => $this->makePartial('flash'), - '#'.$formField->getId('group') => $this->widgets['form']->renderField($formField, [ - 'useContainer' => false, - ]), - ]; - } -} diff --git a/extensions/igniter/automation/database/migrations/2018_10_01_000100_create_all_tables.php b/extensions/igniter/automation/database/migrations/2018_10_01_000100_create_all_tables.php deleted file mode 100644 index 53d521d..0000000 --- a/extensions/igniter/automation/database/migrations/2018_10_01_000100_create_all_tables.php +++ /dev/null @@ -1,61 +0,0 @@ -engine = 'InnoDB'; - $table->increments('id'); - $table->string('name'); - $table->string('code'); - $table->string('description'); - $table->text('event_class')->nullable(); - $table->text('config_data')->nullable(); - $table->boolean('is_custom')->default(0); - $table->boolean('status')->default(0); - $table->timestamps(); - }); - - Schema::create('igniter_automation_rule_actions', function (Blueprint $table) { - $table->engine = 'InnoDB'; - $table->increments('id'); - $table->integer('automation_rule_id'); - $table->string('class_name'); - $table->text('options'); - $table->timestamps(); - }); - - Schema::create('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->engine = 'InnoDB'; - $table->increments('id'); - $table->integer('automation_rule_id'); - $table->string('class_name'); - $table->text('options'); - $table->timestamps(); - }); - - Schema::create('igniter_automation_jobs', function (Blueprint $table) { - $table->engine = 'InnoDB'; - $table->increments('id'); - $table->string('event_class'); - $table->morphs('eventible', 'automation_jobs_eventible'); - $table->mediumText('payload'); - $table->timestamps(); - }); - } - - public function down() - { - Schema::dropIfExists('igniter_automation_rules'); - Schema::dropIfExists('igniter_automation_rule_actions'); - Schema::dropIfExists('igniter_automation_rule_conditions'); - Schema::dropIfExists('igniter_automation_jobs'); - } -} diff --git a/extensions/igniter/automation/database/migrations/2020_11_08_000300_create_task_log_table.php b/extensions/igniter/automation/database/migrations/2020_11_08_000300_create_task_log_table.php deleted file mode 100644 index 0adb09b..0000000 --- a/extensions/igniter/automation/database/migrations/2020_11_08_000300_create_task_log_table.php +++ /dev/null @@ -1,38 +0,0 @@ -engine = 'InnoDB'; - $table->increments('id'); - $table->integer('automation_rule_id')->unsigned(); - $table->integer('rule_action_id')->unsigned(); - $table->boolean('is_success'); - $table->text('message'); - $table->text('params')->nullable(); - $table->text('exception')->nullable(); - $table->timestamps(); - }); - } - - public function down() - { - Schema::dropIfExists('igniter_automation_logs'); - } -} diff --git a/extensions/igniter/automation/database/migrations/2021_11_18_010000_make_primary_key_bigint_all_tables.php b/extensions/igniter/automation/database/migrations/2021_11_18_010000_make_primary_key_bigint_all_tables.php deleted file mode 100644 index 3256eca..0000000 --- a/extensions/igniter/automation/database/migrations/2021_11_18_010000_make_primary_key_bigint_all_tables.php +++ /dev/null @@ -1,33 +0,0 @@ -unsignedBigInteger('id', true)->change(); - }); - - Schema::table('igniter_automation_rule_actions', function (Blueprint $table) { - $table->unsignedBigInteger('id', true)->change(); - }); - - Schema::table('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->unsignedBigInteger('id', true)->change(); - }); - - Schema::table('igniter_automation_logs', function (Blueprint $table) { - $table->unsignedBigInteger('id', true)->change(); - }); - } - - public function down() - { - } -} diff --git a/extensions/igniter/automation/database/migrations/2021_11_18_010300_add_foreign_key_constraints_to_tables.php b/extensions/igniter/automation/database/migrations/2021_11_18_010300_add_foreign_key_constraints_to_tables.php deleted file mode 100644 index ffadbe9..0000000 --- a/extensions/igniter/automation/database/migrations/2021_11_18_010300_add_foreign_key_constraints_to_tables.php +++ /dev/null @@ -1,81 +0,0 @@ -foreignId('automation_rule_id')->nullable()->change(); - $table->foreign('automation_rule_id', DB::getTablePrefix().'igniter_actions_automation_rule_id_foreign') - ->references('id') - ->on('igniter_automation_rules') - ->cascadeOnDelete() - ->cascadeOnUpdate(); - }); - - Schema::table('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->foreignId('automation_rule_id')->nullable()->change(); - $table->foreign('automation_rule_id', DB::getTablePrefix().'igniter_conditions_automation_rule_id_foreign') - ->references('id') - ->on('igniter_automation_rules') - ->cascadeOnDelete() - ->cascadeOnUpdate(); - }); - - Schema::table('igniter_automation_logs', function (Blueprint $table) { - $table->foreignId('automation_rule_id')->nullable()->change(); - $table->foreign('automation_rule_id') - ->references('id') - ->on('igniter_automation_rules') - ->cascadeOnDelete() - ->cascadeOnUpdate(); - - $table->foreignId('rule_action_id')->nullable()->change(); - $table->foreign('rule_action_id') - ->references('id') - ->on('igniter_automation_rule_actions') - ->nullOnDelete() - ->cascadeOnUpdate(); - }); - - Schema::enableForeignKeyConstraints(); - } - - public function down() - { - try { - Schema::table('igniter_automation_rule_actions', function (Blueprint $table) { - $table->dropForeign('igniter_actions_automation_rule_id_foreign'); - }); - - Schema::table('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->dropForeign('igniter_conditions_automation_rule_id_foreign'); - }); - } catch (Exception $ex) { - } - - try { - Schema::table('igniter_automation_rule_actions', function (Blueprint $table) { - $table->dropForeign(DB::getTablePrefix().'igniter_actions_automation_rule_id_foreign'); - }); - - Schema::table('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->dropForeign(DB::getTablePrefix().'igniter_conditions_automation_rule_id_foreign'); - }); - } catch (Exception $ex) { - } - } -} diff --git a/extensions/igniter/automation/database/migrations/2022_06_30_010000_drop_foreign_key_constraints.php b/extensions/igniter/automation/database/migrations/2022_06_30_010000_drop_foreign_key_constraints.php deleted file mode 100644 index 702750e..0000000 --- a/extensions/igniter/automation/database/migrations/2022_06_30_010000_drop_foreign_key_constraints.php +++ /dev/null @@ -1,40 +0,0 @@ -dropForeignKeyIfExists(DB::getTablePrefix().'igniter_actions_automation_rule_id_foreign'); - $table->dropIndexIfExists(DB::getTablePrefix().'igniter_actions_automation_rule_id_foreign'); - }); - - Schema::table('igniter_automation_rule_conditions', function (Blueprint $table) { - $table->dropForeignKeyIfExists(DB::getTablePrefix().'igniter_conditions_automation_rule_id_foreign'); - $table->dropIndexIfExists(DB::getTablePrefix().'igniter_conditions_automation_rule_id_foreign'); - }); - - Schema::table('igniter_automation_logs', function (Blueprint $table) { - $table->dropForeignKeyIfExists('automation_rule_id'); - $table->dropForeignKeyIfExists('rule_action_id'); - - $table->dropIndexIfExists(DB::getTablePrefix().'igniter_automation_logs_automation_rule_id_foreign'); - $table->dropIndexIfExists(DB::getTablePrefix().'igniter_automation_logs_rule_action_id_foreign'); - }); - - Schema::enableForeignKeyConstraints(); - } - - public function down() - { - } -} diff --git a/extensions/igniter/automation/jobs/EventParams.php b/extensions/igniter/automation/jobs/EventParams.php deleted file mode 100644 index 1f71072..0000000 --- a/extensions/igniter/automation/jobs/EventParams.php +++ /dev/null @@ -1,62 +0,0 @@ -eventClass = $eventClass; - - $this->params = $this->serializeParams($params); - } - - /** - * Execute the job. - * - * @return void - */ - public function handle() - { - EventManager::instance()->fireEvent( - $this->eventClass, - $this->unserializeParams() - ); - - $this->delete(); - } - - protected function serializeParams($params) - { - $result = []; - - foreach ($params as $param => $value) { - $result[$param] = $this->getSerializedPropertyValue($value); - } - - return $result; - } - - protected function unserializeParams() - { - $result = []; - - foreach ($this->params as $param => $value) { - $result[$param] = $this->getRestoredPropertyValue($value); - } - - return $result; - } -} diff --git a/extensions/igniter/automation/language/en/default.php b/extensions/igniter/automation/language/en/default.php deleted file mode 100644 index f496e17..0000000 --- a/extensions/igniter/automation/language/en/default.php +++ /dev/null @@ -1,40 +0,0 @@ - 'Automations', - 'text_form_name' => 'Automation', - 'text_action_form_name' => 'Automation Rule Action', - 'text_condition_form_name' => 'Automation Rule Condition', - 'text_tab_general' => 'General', - 'text_tab_logs' => 'Recent Failures', - 'text_empty' => 'No added automations', - 'text_condition_match_any' => 'Match ANY of the below', - 'text_condition_match_all' => 'Match ALL of the below', - 'text_success' => 'Success', - 'text_failed' => 'Failed', - - 'column_event' => 'Event', - 'column_code' => 'Code', - 'column_status' => 'Status', - 'column_time_date' => 'Date', - 'column_message' => 'Message', - 'column_action_name' => 'Action', - 'column_condition_priority' => 'Priority', - 'column_condition_attribute' => 'Attribute', - 'column_condition_operator' => 'Operator', - 'column_condition_value' => 'Value', - - 'label_code' => 'Code', - 'label_event' => 'Event', - 'label_actions' => 'Actions', - 'label_conditions' => 'Conditions', - 'label_status' => 'Status', - - 'label_assign_to_staff' => 'Assign To Staff', - 'label_assign_to_staff_group' => 'Assign To Staff Group', - 'label_send_to_customer_group' => 'Send To Customer Group', - - 'help_event' => 'This rule is triggered by the selected system event', - 'help_actions' => 'Choose one or more actions to perform when this automation is triggered', - 'help_conditions' => 'Choose one or more conditions that must be met for this automation to be triggered. Leave blank to always trigger this automation.', -]; diff --git a/extensions/igniter/automation/models/AutomationLog.php b/extensions/igniter/automation/models/AutomationLog.php deleted file mode 100644 index 791f393..0000000 --- a/extensions/igniter/automation/models/AutomationLog.php +++ /dev/null @@ -1,90 +0,0 @@ - [ - 'rule' => [AutomationRule::class, 'key' => 'automation_rule_id'], - 'action' => [RuleAction::class, 'foreignKey' => 'rule_action_id'], - ], - ]; - - public $rules = [ - 'automation_rule_id' => 'integer', - 'rule_action_id' => 'nullable|integer', - 'is_success' => 'boolean', - 'message' => 'string', - 'params' => 'array', - 'exception' => 'array', - ]; - - protected $casts = [ - 'automation_rule_id' => 'integer', - 'rule_action_id' => 'integer', - 'is_success' => 'boolean', - 'params' => 'array', - 'exception' => 'array', - ]; - - protected $appends = ['action_name', 'status_name', 'created_since']; - - public static function createLog($rule, string $message, bool $isSuccess, array $params = [], ?Throwable $exception = null) - { - $record = new static; - if ($rule instanceof RuleAction) { - $record->automation_rule_id = $rule->automation_rule_id; - $record->rule_action_id = $rule->getKey(); - } else { - $record->automation_rule_id = $rule->getKey(); - $record->rule_action_id = null; - } - - $record->is_success = $isSuccess; - $record->message = $message; - $record->params = $params; - $record->exception = $exception ? [ - 'message' => $exception->getMessage(), - 'code' => $exception->getCode(), - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - 'trace' => $exception->getTraceAsString(), - ] : null; - - $record->save(); - - return $record; - } - - public function getStatusNameAttribute($value) - { - return lang($this->is_success - ? 'igniter.automation::default.text_success' - : 'igniter.automation::default.text_failed' - ); - } - - public function getActionNameAttribute($value) - { - return optional($this->action)->name ?? '--'; - } - - public function getCreatedSinceAttribute($value) - { - return $this->created_at ? time_elapsed($this->created_at) : null; - } -} diff --git a/extensions/igniter/automation/models/AutomationRule.php b/extensions/igniter/automation/models/AutomationRule.php deleted file mode 100644 index 90da02a..0000000 --- a/extensions/igniter/automation/models/AutomationRule.php +++ /dev/null @@ -1,267 +0,0 @@ - [ - 'conditions' => [RuleCondition::class, 'delete' => true], - 'actions' => [RuleAction::class, 'delete' => true], - 'logs' => [AutomationLog::class, 'delete' => true], - ], - ]; - - protected $casts = [ - 'config_data' => 'array', - ]; - - protected $purgeable = ['actions', 'conditions']; - - public $rules = [ - 'name' => ['sometimes', 'required', 'string'], - 'code' => ['sometimes', 'required', 'alpha_dash', 'unique:igniter_automation_rules,code'], - 'event_class' => ['required'], - ]; - - /** - * Kicks off this notification rule, fires the event to obtain its parameters, - * checks the rule conditions evaluate as true, then spins over each action. - */ - public function triggerRule() - { - try { - if (!$this->actions) { - return false; - } - - $params = $this->getEventObject()->getEventParams(); - - if ($this->conditions && !$this->checkConditions($params)) { - return false; - } - - $this->actions->each(function ($action) use ($params) { - $action->triggerAction($params); - }); - } catch (Throwable|Exception $ex) { - AutomationLog::createLog($this, $ex->getMessage(), false, $params ?? [], $ex); - } - } - - public function getEventClassOptions() - { - return array_map(function (BaseEvent $eventObj) { - return $eventObj->getEventName().' - '.$eventObj->getEventDescription(); - }, BaseEvent::findEventObjects()); - } - - public function getActionOptions() - { - return array_map(function (BaseAction $actionObj) { - return $actionObj->getActionName(); - }, BaseAction::findActions()); - } - - public function getConditionOptions() - { - return array_map(function (BaseCondition $conditionObj) { - return $conditionObj->getConditionName(); - }, BaseCondition::findConditions()); - } - - // - // Attributes - // - - public function getEventNameAttribute() - { - return $this->getEventObject()->getEventName(); - } - - public function getEventDescriptionAttribute() - { - return $this->getEventObject()->getEventDescription(); - } - - // - // Events - // - - protected function afterFetch() - { - $this->applyEventClass(); - } - - // - // Scope - // - - public function scopeApplyStatus($query, $status = true) - { - return $query->where('status', $status); - } - - public function scopeApplyClass($query, $class) - { - if (!is_string($class)) { - $class = get_class($class); - } - - return $query->where('event_class', $class); - } - - // - // Manager - // - - /** - * Extends this class with the event class - * @param string $class Class name - * @return bool - */ - public function applyEventClass($class = null) - { - if (!$class) { - $class = $this->event_class; - } - - if (!$class) { - return false; - } - - if (!$this->isClassExtendedWith($class)) { - $this->extendClassWith($class); - } - - $this->event_class = $class; - - return true; - } - - /** - * Returns the event class extension object. - * @return \Igniter\Automation\Classes\BaseEvent - */ - public function getEventObject() - { - $this->applyEventClass(); - - return $this->asExtension($this->getEventClass()); - } - - public function getEventClass() - { - return $this->event_class; - } - - /** - * Returns an array of rule codes and descriptions. - * @return \Illuminate\Support\Collection - */ - public static function listRulesForEvent($eventClass) - { - return self::applyStatus()->applyClass($eventClass)->get(); - } - - /** - * Synchronise all file-based rules to the database. - * @return void - */ - public static function syncAll() - { - $presets = BaseEvent::findEventPresets(); - $dbRules = self::pluck('is_custom', 'code')->toArray(); - $newRules = array_diff_key($presets, $dbRules); - - // Clean up non-customized rules - foreach ($dbRules as $code => $isCustom) { - if ($isCustom || !$code) { - continue; - } - - if (!array_key_exists($code, $presets)) { - self::whereName($code)->delete(); - } - } - - // Create new rules - foreach ($newRules as $code => $preset) { - self::createFromPreset($code, $preset); - } - } - - public static function createFromPreset($code, $preset) - { - $actions = array_get($preset, 'actions'); - if (!$actions || !is_array($actions)) { - return; - } - - $automation = new self; - $automation->status = 0; - $automation->is_custom = 0; - $automation->code = $code; - $automation->name = array_get($preset, 'name'); - $automation->event_class = array_get($preset, 'event'); - $automation->save(); - - foreach ($actions as $actionClass => $config) { - $ruleAction = new RuleAction; - $ruleAction->fill($config); - $ruleAction->class_name = $actionClass; - $ruleAction->automation_rule_id = $automation->getKey(); - $ruleAction->save(); - } - - $conditions = array_get($preset, 'conditions', []); - foreach ($conditions as $conditionClass => $config) { - $ruleCondition = new RuleCondition; - $ruleCondition->options = $config; - $ruleCondition->class_name = $conditionClass; - $ruleCondition->automation_rule_id = $automation->getKey(); - $ruleCondition->save(); - } - - return $automation; - } - - protected function checkConditions($params) - { - $conditions = $this->conditions; - if ($conditions->isEmpty()) { - return true; - } - - $validConditions = $conditions->sortBy('priority')->filter(function (RuleCondition $condition) use ($params) { - return $condition->getConditionObject()->isTrue($params); - })->values(); - - $matchType = $this->config_data['condition_match_type'] ?? 'all'; - - if ($matchType == 'all') { - return $conditions->count() === $validConditions->count(); - } - - return $validConditions->isNotEmpty(); - } -} diff --git a/extensions/igniter/automation/models/RuleAction.php b/extensions/igniter/automation/models/RuleAction.php deleted file mode 100644 index 1dd0f8b..0000000 --- a/extensions/igniter/automation/models/RuleAction.php +++ /dev/null @@ -1,130 +0,0 @@ - [ - 'automation_rule' => [AutomationRule::class, 'key' => 'automation_rule_id'], - ], - ]; - - protected $casts = [ - 'options' => 'array', - ]; - - public $rules = [ - 'class_name' => 'required', - ]; - - // - // Attributes - // - - public function getNameAttribute() - { - return $this->getActionObject()->getActionName(); - } - - public function getDescriptionAttribute() - { - return $this->getActionObject()->getActionDescription(); - } - - // - // Events - // - - protected function afterFetch() - { - $this->applyActionClass(); - $this->loadCustomData(); - } - - protected function beforeSave() - { - $this->setCustomData(); - } - - public function applyCustomData() - { - $this->setCustomData(); - $this->loadCustomData(); - } - - /** - * Extends this model with the action class - * @param string $class Class name - * @return bool - */ - public function applyActionClass($class = null) - { - if (!$class) { - $class = $this->class_name; - } - - if (!$class) { - return false; - } - - if (!$this->isClassExtendedWith($class)) { - $this->extendClassWith($class); - } - - $this->class_name = $class; - - return true; - } - - /** - * @return \Igniter\Automation\Classes\BaseAction - */ - public function getActionObject() - { - $this->applyActionClass(); - - return $this->asExtension($this->getActionClass()); - } - - public function getActionClass() - { - return $this->class_name; - } - - protected function loadCustomData() - { - $this->setRawAttributes((array)$this->getAttributes() + (array)$this->options, true); - } - - protected function setCustomData() - { - if (!$actionObj = $this->getActionObject()) { - throw new SystemException(sprintf('Unable to find action object [%s]', $this->getActionClass())); - } - - $config = $actionObj->getFieldConfig(); - if (!$fields = array_get($config, 'fields')) { - return; - } - - $fieldAttributes = array_keys($fields); - $this->options = array_only($this->getAttributes(), $fieldAttributes); - $this->setRawAttributes(array_except($this->getAttributes(), $fieldAttributes)); - } -} diff --git a/extensions/igniter/automation/models/RuleCondition.php b/extensions/igniter/automation/models/RuleCondition.php deleted file mode 100644 index ecf738a..0000000 --- a/extensions/igniter/automation/models/RuleCondition.php +++ /dev/null @@ -1,93 +0,0 @@ - [ - 'automation_rule' => [AutomationRule::class, 'key' => 'automation_rule_id'], - ], - ]; - - protected $casts = [ - 'options' => 'array', - ]; - - public $rules = [ - 'class_name' => 'required', - ]; - - // - // Attributes - // - - public function getNameAttribute() - { - return $this->getConditionObject()->getConditionName(); - } - - public function getDescriptionAttribute() - { - return $this->getConditionObject()->getConditionDescription(); - } - - // - // Events - // - - protected function afterFetch() - { - $this->applyConditionClass(); - } - - /** - * Extends this model with the condition class - * @param string $class Class name - * @return bool - */ - public function applyConditionClass($class = null) - { - if (!$class) { - $class = $this->class_name; - } - - if (!$class) { - return false; - } - - if (!$this->isClassExtendedWith($class)) { - $this->extendClassWith($class); - } - - $this->class_name = $class; - - return true; - } - - /** - * @return \Igniter\Automation\Classes\BaseCondition - */ - public function getConditionObject() - { - $this->applyConditionClass(); - - return $this->asExtension($this->getConditionClass()); - } - - public function getConditionClass() - { - return $this->class_name; - } -} diff --git a/extensions/igniter/automation/models/config/automationrule.php b/extensions/igniter/automation/models/config/automationrule.php deleted file mode 100644 index 02aa551..0000000 --- a/extensions/igniter/automation/models/config/automationrule.php +++ /dev/null @@ -1,231 +0,0 @@ - [ - 'toolbar' => [ - 'buttons' => [ - 'create' => ['label' => 'lang:admin::lang.button_new', 'class' => 'btn btn-primary', 'href' => 'igniter/automation/automations/create'], - ], - ], - 'bulkActions' => [ - 'status' => [ - 'label' => 'lang:admin::lang.list.actions.label_status', - 'type' => 'dropdown', - 'class' => 'btn btn-light', - 'statusColumn' => 'status', - 'menuItems' => [ - 'enable' => [ - 'label' => 'lang:admin::lang.list.actions.label_enable', - 'type' => 'button', - 'class' => 'dropdown-item', - ], - 'disable' => [ - 'label' => 'lang:admin::lang.list.actions.label_disable', - 'type' => 'button', - 'class' => 'dropdown-item text-danger', - ], - ], - ], - 'delete' => [ - 'label' => 'lang:admin::lang.button_delete', - 'class' => 'btn btn-light text-danger', - 'data-request-confirm' => 'lang:admin::lang.alert_warning_confirm', - ], - ], - 'columns' => [ - 'edit' => [ - 'type' => 'button', - 'iconCssClass' => 'fa fa-pencil', - 'attributes' => [ - 'class' => 'btn btn-edit', - 'href' => 'igniter/automation/automations/edit/{id}', - ], - ], - 'name' => [ - 'label' => 'lang:admin::lang.label_name', - 'type' => 'text', - 'searchable' => true, - ], - 'code' => [ - 'label' => 'lang:igniter.automation::default.column_code', - 'type' => 'text', - 'searchable' => true, - ], - 'event_name' => [ - 'label' => 'lang:igniter.automation::default.column_event', - 'type' => 'text', - 'sortable' => false, - ], - 'status' => [ - 'label' => 'lang:admin::lang.label_status', - 'type' => 'switch', - 'searchable' => true, - ], - 'id' => [ - 'label' => 'lang:admin::lang.column_id', - 'invisible' => true, - ], - ], - ], - - 'form' => [ - 'toolbar' => [ - 'buttons' => [ - 'back' => ['label' => 'lang:admin::lang.button_icon_back', 'class' => 'btn btn-outline-secondary', 'href' => 'igniter/automation/automations'], - 'save' => [ - 'label' => 'lang:admin::lang.button_save', - 'class' => 'btn btn-primary', - 'data-request' => 'onSave', - ], - 'saveClose' => [ - 'label' => 'lang:admin::lang.button_save_close', - 'class' => 'btn btn-default', - 'data-request' => 'onSave', - 'data-request-data' => 'close:1', - ], - ], - ], - 'fields' => [ - 'event_class' => [ - 'label' => 'lang:igniter.automation::default.label_event', - 'type' => 'select', - 'comment' => 'lang:igniter.automation::default.help_event', - ], - 'name' => [ - 'label' => 'lang:admin::lang.label_name', - 'type' => 'text', - 'context' => ['edit', 'preview'], - 'span' => 'left', - ], - 'code' => [ - 'label' => 'lang:igniter.automation::default.label_code', - 'type' => 'text', - 'context' => ['edit', 'preview'], - 'span' => 'right', - 'cssClass' => 'flex-width', - ], - 'status' => [ - 'label' => 'lang:admin::lang.label_status', - 'type' => 'switch', - 'default' => true, - 'context' => ['edit', 'preview'], - 'span' => 'right', - 'cssClass' => 'flex-width', - ], - 'description' => [ - 'context' => ['edit', 'preview'], - 'type' => 'hidden', - ], - ], - 'tabs' => [ - 'fields' => [ - 'config_data[condition_match_type]' => [ - 'tab' => 'lang:igniter.automation::default.label_conditions', - 'type' => 'radiolist', - 'context' => ['edit', 'preview'], - 'inlineMode' => true, - 'default' => 'all', - 'options' => [ - 'all' => 'lang:igniter.automation::default.text_condition_match_all', - 'any' => 'lang:igniter.automation::default.text_condition_match_any', - ], - ], - '_condition' => [ - 'tab' => 'lang:igniter.automation::default.label_conditions', - 'type' => 'select', - 'context' => ['edit', 'preview'], - 'placeholder' => 'lang:admin::lang.text_select', - 'comment' => 'lang:igniter.automation::default.help_conditions', - 'attributes' => [ - 'data-request' => 'onLoadCreateConditionForm', - 'data-request-success' => '$(\'[data-control="connector"]\').connector();', - ], - ], - 'conditions' => [ - 'tab' => 'lang:igniter.automation::default.label_conditions', - 'type' => 'connector', - 'context' => ['edit', 'preview'], - 'formName' => 'lang:igniter.automation::default.text_condition_form_name', - 'popupSize' => 'modal-lg', - 'sortable' => true, - 'form' => [ - 'fields' => [ - 'options' => [ - 'label' => 'lang:igniter.automation::default.label_conditions', - 'type' => 'repeater', - 'commentAbove' => 'lang:igniter.automation::default.help_conditions', - 'sortable' => true, - 'form' => [ - 'fields' => [ - 'priority' => [ - 'label' => 'lang:igniter.automation::default.column_condition_priority', - 'type' => 'hidden', - ], - 'attribute' => [ - 'label' => 'lang:igniter.automation::default.column_condition_attribute', - 'type' => 'select', - 'options' => 'getAttributeOptions', - ], - 'operator' => [ - 'label' => 'lang:igniter.automation::default.column_condition_operator', - 'type' => 'select', - 'options' => 'getOperatorOptions', - ], - 'value' => [ - 'label' => 'lang:igniter.automation::default.column_condition_value', - 'type' => 'text', - ], - ], - ], - ], - ], - ], - ], - - '_action' => [ - 'tab' => 'lang:igniter.automation::default.label_actions', - 'type' => 'select', - 'context' => ['edit', 'preview'], - 'placeholder' => 'lang:admin::lang.text_select', - 'comment' => 'lang:igniter.automation::default.help_actions', - 'attributes' => [ - 'data-request' => 'onLoadCreateActionForm', - 'data-request-success' => '$(\'[data-control="connector"]\').connector();', - ], - ], - 'actions' => [ - 'tab' => 'lang:igniter.automation::default.label_actions', - 'type' => 'connector', - 'context' => ['edit', 'preview'], - 'formName' => 'lang:igniter.automation::default.text_action_form_name', - 'popupSize' => 'modal-lg', - 'sortable' => true, - 'form' => [], - ], - - 'logs' => [ - 'tab' => 'lang:igniter.automation::default.text_tab_logs', - 'type' => 'datatable', - 'context' => ['edit', 'preview'], - 'defaultSort' => ['created_at', 'desc'], - 'searchableFields' => ['message'], - 'useAjax' => true, - 'columns' => [ - 'created_since' => [ - 'title' => 'lang:igniter.automation::default.column_time_date', - ], - 'status_name' => [ - 'title' => 'lang:igniter.automation::default.column_status', - ], - 'action_name' => [ - 'title' => 'lang:igniter.automation::default.column_action_name', - ], - 'message' => [ - 'title' => 'lang:igniter.automation::default.column_message', - ], - ], - ], - ], - ], - ], -]; diff --git a/extensions/igniter/automation/views/automations/create.blade.php b/extensions/igniter/automation/views/automations/create.blade.php deleted file mode 100644 index 81b6bb4..0000000 --- a/extensions/igniter/automation/views/automations/create.blade.php +++ /dev/null @@ -1,11 +0,0 @@ -
- {!! form_open([ - 'id' => 'form-widget', - 'role' => 'form', - 'method' => 'POST', - ]) !!} - - {!! $this->renderForm() !!} - - {!! form_close() !!} -
diff --git a/extensions/igniter/automation/views/automations/edit.blade.php b/extensions/igniter/automation/views/automations/edit.blade.php deleted file mode 100644 index 2f7385d..0000000 --- a/extensions/igniter/automation/views/automations/edit.blade.php +++ /dev/null @@ -1,11 +0,0 @@ -
- {!! form_open([ - 'id' => 'form-widget', - 'role' => 'form', - 'method' => 'PATCH', - ]) !!} - - {!! $this->renderForm() !!} - - {!! form_close() !!} -
diff --git a/extensions/igniter/automation/views/automations/index.blade.php b/extensions/igniter/automation/views/automations/index.blade.php deleted file mode 100644 index 5dbd03b..0000000 --- a/extensions/igniter/automation/views/automations/index.blade.php +++ /dev/null @@ -1,3 +0,0 @@ -
- {!! $this->renderList() !!} -
diff --git a/extensions/igniter/automation/views/automations/preview.blade.php b/extensions/igniter/automation/views/automations/preview.blade.php deleted file mode 100644 index a501e83..0000000 --- a/extensions/igniter/automation/views/automations/preview.blade.php +++ /dev/null @@ -1,10 +0,0 @@ -
- {!! form_open([ - 'id' => 'preview-form', - 'role' => 'form', - ]) !!} - - {!! $this->renderForm(['preview' => TRUE]) !!} - - {!! form_close() !!} -
diff --git a/extensions/igniterlabs/importexport/.editorconfig b/extensions/igniterlabs/importexport/.editorconfig deleted file mode 100644 index 1173f22..0000000 --- a/extensions/igniterlabs/importexport/.editorconfig +++ /dev/null @@ -1,15 +0,0 @@ -root = true - -[*] -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -indent_style = space -indent_size = 4 - -[*.md] -trim_trailing_whitespace = false - -[*.{yml, yaml, json, scss, css}] -indent_size = 2 diff --git a/extensions/igniterlabs/importexport/.gitignore b/extensions/igniterlabs/importexport/.gitignore deleted file mode 100644 index fc647ca..0000000 --- a/extensions/igniterlabs/importexport/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -.DS_Store -.idea -.php_cs -.php_cs.cache -.phpunit.result.cache -build -composer.lock -coverage -docs -phpunit.xml -psalm.xml -vendor -.php-cs-fixer.cache diff --git a/extensions/igniterlabs/importexport/Extension.php b/extensions/igniterlabs/importexport/Extension.php deleted file mode 100644 index 8dcba6b..0000000 --- a/extensions/igniterlabs/importexport/Extension.php +++ /dev/null @@ -1,38 +0,0 @@ - [ - 'description' => 'Access import/export tool', - 'group' => 'module', - ], - ]; - } - - public function registerNavigation() - { - return [ - 'tools' => [ - 'child' => [ - 'importexport' => [ - 'priority' => 200, - 'class' => 'importexport', - 'href' => admin_url('igniterlabs/importexport/importexport'), - 'title' => 'Import/Export', - 'permission' => 'IgniterLabs.ImportExport.Manage', - ], - ], - ], - ]; - } -} diff --git a/extensions/igniterlabs/importexport/LICENSE.md b/extensions/igniterlabs/importexport/LICENSE.md deleted file mode 100644 index f2a82b9..0000000 --- a/extensions/igniterlabs/importexport/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Igniter Labs Team - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/extensions/igniterlabs/importexport/README.md b/extensions/igniterlabs/importexport/README.md deleted file mode 100644 index 215a064..0000000 --- a/extensions/igniterlabs/importexport/README.md +++ /dev/null @@ -1,20 +0,0 @@ -This extension allows you to import or export TastyIgniter menu items with images, orders and customers. It is super -simple! - -### Features - -- Export Menu Items into a CSV file. -- Import Menu Items in CSV format into TastyIgniter. - -### TODO - -- Implement import/export history -- Import/Export customers, reservations and orders - -### Admin Panel - -In the admin user interface you can import/export menu items, orders or customers. - -### License - -[The MIT License (MIT)](https://tastyigniter.com/license/) diff --git a/extensions/igniterlabs/importexport/actions/ExportController.php b/extensions/igniterlabs/importexport/actions/ExportController.php deleted file mode 100644 index b9f77af..0000000 --- a/extensions/igniterlabs/importexport/actions/ExportController.php +++ /dev/null @@ -1,228 +0,0 @@ -partialPath[] = '$/'.$classPath; - - parent::__construct($controller); - - // Build configuration - $this->setConfig($controller->exportConfig, $this->requiredConfig); - - // Override config - if ($exportFileName = $this->getConfig('fileName')) { - $this->exportFileName = $exportFileName; - } - } - - public function export($context, $recordName = null) - { - if ($redirect = $this->checkPermissions()) { - return $redirect; - } - - $this->loadRecordConfig($context, $recordName); - - $pageTitle = lang($this->getConfig('record[title]', 'igniterlabs.importexport::default.text_export_title')); - Template::setTitle($pageTitle); - Template::setHeading($pageTitle); - - $this->initExportForms(); - } - - public function download($context, $recordName = null, $exportName = null, $outputName = null) - { - $this->loadRecordConfig('export', $recordName); - - return $this->getExportModel()->download($exportName, $outputName); - } - - public function renderExport() - { - if (!is_null($this->exportToolbarWidget)) { - $import[] = $this->exportToolbarWidget->render(); - } - - $import[] = $this->importExportMakePartial('export_container'); - - return implode(PHP_EOL, $import); - } - - public function export_onExport($context, $recordName) - { - $partials = []; - - try { - $this->loadRecordConfig($context, $recordName); - - $model = $this->getExportModel(); - - if ($secondaryData = post('ExportSecondary')) { - $model->fill($secondaryData); - } - - $columns = $this->processExportColumnsFromPost(); - $options = $this->getFormatOptionsFromPost(); - - $reference = $model->export($columns, $options); - $fileUrl = admin_url('igniterlabs/importexport/importexport/download/'. - $recordName.'/'.$reference.'/'.$this->exportFileName - ); - - $this->vars['fileUrl'] = $fileUrl; - $this->vars['returnUrl'] = $this->getRedirectUrl(); - - flash()->success( - 'File export process completed! The browser will now redirect to the file download.' - )->important(); - - $partials['@#exportContainer'] = $this->importExportMakePartial('export_result'); - } catch (MassAssignmentException $ex) { - $this->controller->handleError(new ApplicationException(lang( - 'igniterlabs.importexport::default.error_mass_assignment', $ex->getMessage() - ))); - } catch (Exception $ex) { - $this->controller->handleError($ex); - } - - $partials['#notification'] = $this->makePartial('flash'); - - return $partials; - } - - /** - * @return \IgniterLabs\ImportExport\Models\ExportModel - */ - public function getExportModel() - { - return $this->getModelForType('export'); - } - - protected function initExportForms() - { - $model = $this->getExportModel(); - - $this->exportPrimaryFormWidget = $this->makePrimaryFormWidgetForType($model, 'export'); - - $this->exportSecondaryFormWidget = $this->makeSecondaryFormWidgetForType($model, 'export'); - - if (!$this->exportSecondaryFormWidget && $this->exportPrimaryFormWidget) { - $stepSection = $this->exportPrimaryFormWidget->getField('step_secondary'); - $stepSection->hidden = true; - } - - $this->prepareExportVars(); - } - - protected function prepareExportVars() - { - $this->vars['recordTitle'] = $this->getConfig('record[title]', 'Unknown Title'); - $this->vars['recordDescription'] = $this->getConfig('record[description]', 'Unknown description'); - $this->vars['exportPrimaryFormWidget'] = $this->exportPrimaryFormWidget; - $this->vars['exportSecondaryFormWidget'] = $this->exportSecondaryFormWidget; - $this->vars['exportColumns'] = $this->getExportColumns(); - - // Make these variables available to widgets - $this->controller->vars += $this->vars; - } - - protected function getExportColumns() - { - if (!is_null($this->exportColumns)) { - return $this->exportColumns; - } - - $configFile = $this->getConfig('record[configFile]'); - $columns = $this->makeListColumns($configFile); - - if (empty($columns)) { - throw new ApplicationException(lang('igniterlabs.importexport::default.error_empty_export_columns')); - } - - return $this->exportColumns = $columns; - } - - // - // - // - - /** - * Called before the form fields are defined. - * - * @param \Admin\Widgets\Form $host The hosting form widget - * - * @return void - */ - public function exportFormExtendFieldsBefore($host) - { - } - - /** - * Called after the form fields are defined. - * - * @param \Admin\Widgets\Form $host The hosting form widget - * - * @return void - */ - public function exportFormExtendFields($host, $fields) - { - } -} diff --git a/extensions/igniterlabs/importexport/actions/ImportController.php b/extensions/igniterlabs/importexport/actions/ImportController.php deleted file mode 100644 index b4a3f20..0000000 --- a/extensions/igniterlabs/importexport/actions/ImportController.php +++ /dev/null @@ -1,264 +0,0 @@ -partialPath[] = '$/'.$classPath; - - parent::__construct($controller); - - // Build configuration - $this->setConfig($controller->importConfig, $this->requiredConfig); - } - - public function import($context, $recordName = null) - { - if ($redirect = $this->checkPermissions()) { - return $redirect; - } - - $this->loadRecordConfig($context, $recordName); - - $pageTitle = lang($this->getConfig('record[title]', 'igniterlabs.importexport::default.text_import_title')); - Template::setTitle($pageTitle); - Template::setHeading($pageTitle); - - $this->initImportForms(); - } - - public function renderImport() - { - if (!is_null($this->importToolbarWidget)) { - $import[] = $this->importToolbarWidget->render(); - } - - $import[] = $this->importExportMakePartial('import_container'); - - return implode(PHP_EOL, $import); - } - - public function import_onImport($context, $recordName) - { - $partials = []; - - try { - $this->loadRecordConfig($context, $recordName); - $model = $this->getImportModel(); - - $matches = $this->getImportMatchColumns(); - - if ($optionData = post('ImportSecondary')) { - $model->fill($optionData); - } - - $importOptions = $this->getFormatOptionsFromPost(); - - $model->import($matches, $importOptions); - - File::delete($this->getImportFilePath()); - - $this->vars['importResults'] = $model->getResultStats(); - $this->vars['returnUrl'] = $this->getRedirectUrl(); - - $partials['#importContainer'] = $this->importExportMakePartial('import_result'); - } catch (MassAssignmentException $ex) { - $this->controller->handleError(new ApplicationException(lang( - 'admin::lang.form.mass_assignment_failed', - ['attribute' => $ex->getMessage()] - ))); - } catch (Exception $ex) { - $this->controller->handleError($ex); - } - - return $partials; - } - - public function import_onImportUploadFile($context, $recordName) - { - try { - if (!request()->hasFile('import_file')) { - throw new ApplicationException('You must upload a file to import'); - } - - $uploadedFile = request()->file('import_file'); - if (!$uploadedFile->isValid()) { - throw new ApplicationException($uploadedFile->getErrorMessage()); - } - - if (!in_array($uploadedFile->getMimeType(), ['csv', 'text/csv', 'text/plain'])) { - throw new ApplicationException('you must upload a valida csv file'); - } - - $this->loadRecordConfig($context, $recordName); - - File::put( - $this->getImportFilePath(), - File::get($uploadedFile->getRealPath()) - ); - } catch (Exception $ex) { - flash()->error($ex->getMessage()); - } - - return $this->controller->redirectBack(); - } - - /** - * @return \IgniterLabs\ImportExport\Models\ImportModel - */ - public function getImportModel() - { - return $this->getModelForType('import'); - } - - protected function initImportForms() - { - $model = $this->getImportModel(); - - $this->importPrimaryFormWidget = $this->makePrimaryFormWidgetForType($model, 'import'); - - $this->importSecondaryFormWidget = $this->makeSecondaryFormWidgetForType($model, 'import'); - - if (!$this->importSecondaryFormWidget && $this->importPrimaryFormWidget) { - $stepSection = $this->importPrimaryFormWidget->getField('step_secondary'); - $stepSection->hidden = true; - } - - $this->prepareImportVars(); - } - - protected function prepareImportVars() - { - $this->vars['recordTitle'] = $this->getConfig('record[title]', 'Unknown Title'); - $this->vars['recordDescription'] = $this->getConfig('record[description]', 'Unknown description'); - $this->vars['importPrimaryFormWidget'] = $this->importPrimaryFormWidget; - $this->vars['importSecondaryFormWidget'] = $this->importSecondaryFormWidget; - $this->vars['importColumns'] = $this->getImportColumns(); - $this->vars['importFileColumns'] = $this->getImportFileColumns(); - - // Make these variables available to widgets - $this->controller->vars += $this->vars; - } - - protected function getImportColumns() - { - if (!is_null($this->importColumns)) { - return $this->importColumns; - } - - $configFile = $this->getConfig('record[configFile]'); - $columns = $this->makeListColumns($configFile); - - if (empty($columns)) { - throw new ApplicationException(lang('igniterlabs.importexport::default.error_empty_import_columns')); - } - - return $this->importColumns = $columns; - } - - protected function getImportFileColumns() - { - if (!$this->importFilePathExists()) { - return; - } - - $path = $this->getImportFilePath(); - $reader = $this->createCsvReader($path); - $firstRow = $reader->fetchOne(0); - - if (json_encode($firstRow) === false) { - throw new ApplicationException(lang('igniterlabs.importexport::default.encoding_not_supported')); - } - - return $firstRow; - } - - protected function getImportFilePath() - { - return $this->getImportModel()->getImportFilePath(); - } - - protected function importFilePathExists() - { - return File::exists($path = $this->getImportFilePath()) - ? $path : null; - } - - // - // - // - - /** - * Called before the form fields are defined. - * - * @param \Admin\Widgets\Form $host The hosting form widget - * - * @return void - */ - public function importFormExtendFieldsBefore($host) - { - } - - /** - * Called after the form fields are defined. - * - * @param \Admin\Widgets\Form $host The hosting form widget - * - * @return void - */ - public function importFormExtendFields($host, $fields) - { - } -} diff --git a/extensions/igniterlabs/importexport/actions/exportcontroller/export_columns.blade.php b/extensions/igniterlabs/importexport/actions/exportcontroller/export_columns.blade.php deleted file mode 100644 index cb318f4..0000000 --- a/extensions/igniterlabs/importexport/actions/exportcontroller/export_columns.blade.php +++ /dev/null @@ -1,46 +0,0 @@ -@php - $fieldOptions = []; //$field->options(); - $checkedValues = (array)$field->value; - $isScrollable = count($exportColumns) > 10; -@endphp - -
- @if ($isScrollable) - - @lang('admin::lang.text_select'): - @lang('admin::lang.text_select_all'), - @lang('admin::lang.text_select_none') - - -
-
- @endif - - @foreach ($exportColumns as $key => $column) - @php $checkboxId = 'checkbox_'.$field->getId().'_'.$loop->index; @endphp -
- - - -
- @endforeach - - @if ($isScrollable) -
-
- @endif - -
diff --git a/extensions/igniterlabs/importexport/actions/exportcontroller/export_container.blade.php b/extensions/igniterlabs/importexport/actions/exportcontroller/export_container.blade.php deleted file mode 100644 index 078f2ea..0000000 --- a/extensions/igniterlabs/importexport/actions/exportcontroller/export_container.blade.php +++ /dev/null @@ -1,6 +0,0 @@ -
- {!! $exportPrimaryFormWidget->render() !!} - @if ($exportSecondaryFormWidget) - {!! $exportSecondaryFormWidget->render() !!} - @endif -
diff --git a/extensions/igniterlabs/importexport/actions/exportcontroller/export_result.blade.php b/extensions/igniterlabs/importexport/actions/exportcontroller/export_result.blade.php deleted file mode 100644 index 7d2443a..0000000 --- a/extensions/igniterlabs/importexport/actions/exportcontroller/export_result.blade.php +++ /dev/null @@ -1 +0,0 @@ - diff --git a/extensions/igniterlabs/importexport/actions/importcontroller/import_columns.blade.php b/extensions/igniterlabs/importexport/actions/importcontroller/import_columns.blade.php deleted file mode 100644 index df8b0a3..0000000 --- a/extensions/igniterlabs/importexport/actions/importcontroller/import_columns.blade.php +++ /dev/null @@ -1,50 +0,0 @@ -
-
- - - - - - - - - - @if ($importFileColumns) - @foreach ($importFileColumns as $index => $fileColumn) - - - - - - @endforeach - @else - - - - @endif - -
@lang('igniterlabs.importexport::default.label_file_columns')@lang('igniterlabs.importexport::default.label_db_columns')
-
- - -
-
{{ $fileColumn }} - -
@lang('igniterlabs.importexport::default.text_no_import_file')
-
-
diff --git a/extensions/igniterlabs/importexport/actions/importcontroller/import_container.blade.php b/extensions/igniterlabs/importexport/actions/importcontroller/import_container.blade.php deleted file mode 100644 index 8bb2fb3..0000000 --- a/extensions/igniterlabs/importexport/actions/importcontroller/import_container.blade.php +++ /dev/null @@ -1,6 +0,0 @@ -
- {!! $importPrimaryFormWidget->render() !!} - @if ($importSecondaryFormWidget) - {!! $importSecondaryFormWidget->render() !!} - @endif -
diff --git a/extensions/igniterlabs/importexport/actions/importcontroller/import_file_upload.blade.php b/extensions/igniterlabs/importexport/actions/importcontroller/import_file_upload.blade.php deleted file mode 100644 index d4371f1..0000000 --- a/extensions/igniterlabs/importexport/actions/importcontroller/import_file_upload.blade.php +++ /dev/null @@ -1,35 +0,0 @@ -
-
- -
- @lang('igniterlabs.importexport::default.button_choose') - @lang('igniterlabs.importexport::default.button_change') - -
- -
-
diff --git a/extensions/igniterlabs/importexport/actions/importcontroller/import_result.blade.php b/extensions/igniterlabs/importexport/actions/importcontroller/import_result.blade.php deleted file mode 100644 index 31b8fdd..0000000 --- a/extensions/igniterlabs/importexport/actions/importcontroller/import_result.blade.php +++ /dev/null @@ -1,79 +0,0 @@ -
-
-
-
-

@lang('igniterlabs.importexport::default.text_import_created')

-

{{ $importResults->created }}

-
-
-

@lang('igniterlabs.importexport::default.text_import_updated')

-

{{ $importResults->updated }}

-
- @if ($importResults->skippedCount) -
-

@lang('igniterlabs.importexport::default.text_import_skipped')

-

{{ $importResults->skippedCount }}

-
- @endif - @if ($importResults->warningCount) -
-

@lang('igniterlabs.importexport::default.text_import_warnings')

-

{{ $importResults->warningCount }}

-
- @endif -
-

@lang('igniterlabs.importexport::default.text_import_errors')

-

{{ $importResults->errorCount }}

-
-
- - @if ($importResults->hasMessages) - @php - $tabs = [ - 'skipped' => lang('igniterlabs.importexport::default.text_import_skipped'), - 'warnings' => lang('igniterlabs.importexport::default.text_import_warnings'), - 'errors' => lang('igniterlabs.importexport::default.text_import_errors'), - ]; - - if (!$importResults->skippedCount) unset($tabs['skipped']); - if (!$importResults->warningCount) unset($tabs['warnings']); - if (!$importResults->errorCount) unset($tabs['errors']); - @endphp -
- -
- @foreach ($tabs as $code => $tab) -
-
    - @foreach ($importResults->{$code} as $row => $message) -
  • - {{ sprintf(lang('igniterlabs.importexport::default.text_import_row'), $row + 2) }} - - {{ $message }} -
  • - @endforeach -
-
- @endforeach -
-
- @endif -
-
- diff --git a/extensions/igniterlabs/importexport/classes/ImportExportManager.php b/extensions/igniterlabs/importexport/classes/ImportExportManager.php deleted file mode 100644 index b64f5f8..0000000 --- a/extensions/igniterlabs/importexport/classes/ImportExportManager.php +++ /dev/null @@ -1,89 +0,0 @@ -listImportExportsForType($type), $name, $default); - } - - public function listImportExportsForType($type) - { - return array_get($this->listImportExports(), $type, []); - } - - // - // Registration - // - - /** - * Returns a list of the registered import/exports. - * @return array - */ - public function listImportExports() - { - if (self::$importExportCache === null) { - (new static)->loadImportExports(); - } - - return self::$importExportCache; - } - - /** - * Loads registered import/exports from extensions - * @return void - */ - public function loadImportExports() - { - if (!self::$importExportCache) { - self::$importExportCache = []; - } - - $registeredResources = ExtensionManager::instance()->getRegistrationMethodValues('registerImportExport'); - foreach ($registeredResources as $extensionCode => $records) { - $this->registerImportExports($extensionCode, $records); - } - } - - /** - * Registers the import/exports. - */ - public function registerImportExports($extensionCode, array $definitions) - { - foreach ($definitions as $type => $definition) { - if (!in_array($type, ['import', 'export'])) { - continue; - } - - $this->registerImportExportsForType($type, $extensionCode, $definition); - } - } - - public function registerImportExportsForType($type, $extensionCode, array $definitions) - { - $defaultDefinitions = [ - 'label' => null, - 'description' => null, - 'model' => null, - 'configFile' => null, - ]; - - foreach ($definitions as $name => $definition) { - $name = str_replace('.', '-', $extensionCode.'.'.$name); - - static::$importExportCache[$type][$name] = array_merge($defaultDefinitions, $definition); - } - } -} diff --git a/extensions/igniterlabs/importexport/composer.json b/extensions/igniterlabs/importexport/composer.json deleted file mode 100644 index 1e7e21c..0000000 --- a/extensions/igniterlabs/importexport/composer.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "igniterlabs/ti-ext-importexport", - "type": "tastyigniter-extension", - "description": "Import/Export Menu Items, Orders, Customers from/into any CSV or Microsoft Excel file to TastyIgniter.", - "keywords": [ - "tastyigniter", - "import", - "export" - ], - "license": "MIT", - "authors": [ - { - "name": "Igniter Labs Team" - } - ], - "require": { - "league/csv": "~9.1" - }, - "extra": { - "tastyigniter-extension": { - "code": "igniterlabs.importexport", - "name": "Import & Export Tool", - "icon": { - "class": "fas fa-file-import", - "backgroundColor": "#147EFB", - "color": "#FFFFFF" - }, - "homepage": "https://tastyigniter.com/marketplace/item/igniterlabs-importexport" - } - } -} diff --git a/extensions/igniterlabs/importexport/controllers/ImportExport.php b/extensions/igniterlabs/importexport/controllers/ImportExport.php deleted file mode 100644 index 40edb8b..0000000 --- a/extensions/igniterlabs/importexport/controllers/ImportExport.php +++ /dev/null @@ -1,76 +0,0 @@ - 'Import Records', - 'configFile' => '$/igniterlabs/importexport/models/config/importmodel', - 'redirect' => 'igniterlabs/importexport/importexport/import', - ]; - - public $exportConfig = [ - 'title' => 'Export Records', - 'configFile' => '$/igniterlabs/importexport/models/config/exportmodel', - 'redirect' => 'igniterlabs/importexport/importexport/export', - ]; - - protected $requiredPermissions = 'IgniterLabs.ImportExport.Manage'; - - public function __construct() - { - parent::__construct(); - - AdminMenu::setContext('importexport', 'tools'); - } - - public function index() - { - $pageTitle = lang('igniterlabs.importexport::default.text_index_title'); - Template::setTitle($pageTitle); - Template::setHeading($pageTitle); - } - - public function index_onLoadPopup() - { - $context = post('context'); - if (!in_array($context, ['import', 'export'])) { - throw new ApplicationException('Invalid type specified'); - } - - $this->vars['context'] = $context; - $this->vars['importExports'] = ImportExportManager::instance()->listImportExportsForType($context); - - return ['#importExportModalContent' => $this->makePartial('new_import_export_popup')]; - } - - public function index_onLoadForm() - { - $context = post('context'); - if (!in_array($context, ['import', 'export'])) { - throw new ApplicationException('Invalid type specified'); - } - - if (!strlen($code = post('code'))) { - throw new ApplicationException('You must choose a type to import'); - } - - if (!$config = ImportExportManager::instance()->getRecordConfig($context, $code)) { - throw new ApplicationException($code.' is not a registered import/export template'); - } - - return $this->redirect('igniterlabs/importexport/importexport/'.$context.'/'.$code); - } -} diff --git a/extensions/igniterlabs/importexport/language/en/default.php b/extensions/igniterlabs/importexport/language/en/default.php deleted file mode 100644 index 9d329a3..0000000 --- a/extensions/igniterlabs/importexport/language/en/default.php +++ /dev/null @@ -1,81 +0,0 @@ - 'Import/Export', - 'text_import_export_title' => 'New Import/Export', - 'text_import_title' => 'Import Records', - 'text_export_title' => 'Export Records', - 'text_history_title' => 'Import/Export History', - 'text_tab_title_import_primary' => 'Upload a CSV file', - 'text_tab_title_import_columns' => 'Match columns to import', - 'text_tab_title_import_secondary' => 'Set import options', - 'text_tab_title_export_primary' => 'Export output settings', - 'text_tab_title_export_columns' => 'Columns to export', - 'text_tab_title_export_secondary' => 'Set export options', - 'text_no_import_file' => 'Please upload a valid CSV file.', - 'text_import_row' => 'Row %s', - 'text_import_created' => 'Created', - 'text_import_updated' => 'Updated', - 'text_import_skipped' => 'Skipped', - 'text_import_warnings' => 'Warnings', - 'text_import_errors' => 'Errors', - 'text_import_skipped_rows' => 'Skipped Rows', - 'text_import_progress' => 'Import progress', - 'text_processing' => 'Processing...', - 'text_uploading' => 'Uploading...', - - 'label_export_record' => 'Choose record to export', - 'label_offset' => 'Offset', - 'label_limit' => 'Limit', - 'label_delimiter' => 'Delimiter Character', - 'label_enclosure' => 'Enclosure Character', - 'label_escape' => 'Escape Character', - 'label_columns' => 'Columns', - - 'label_import_record' => 'Choose record to import', - 'label_import_file' => 'Import file', - 'label_encoding' => 'File encoding', - 'label_import_columns' => 'Import Columns', - 'label_db_columns' => 'Database fields', - 'label_file_columns' => 'File Columns', - 'label_import_ignore' => 'Import/Ignore', - - 'button_import_records' => 'Import Records', - 'button_export_records' => 'Export Records', - 'button_upload' => 'Upload CSV', - 'button_choose' => 'Choose', - 'button_change' => 'Change', - - 'error_empty_import_columns' => 'Please specify some columns to import.', - 'error_empty_export_columns' => 'Please specify some columns to export.', - 'error_missing_model' => 'Missing the model property for %s', - 'error_mass_assignment' => "Mass assignment failed for Model attribute ':attribute'.", - 'error_empty_data' => 'There was no data supplied to export', - 'error_file_not_found' => 'File not found', - - 'help_offset' => 'Number of records to skip before exporting. Use 0 value to start from the first record, 100 to start exporting from the 101th record', - 'help_limit' => 'Number of records to export. If no value is given all records are exported.', - 'help_delimiter' => 'The character used to separate each field', - 'help_enclosure' => 'The character used to enclose each field', - - 'encodings' => [ - 'utf_8' => 'UTF-8', - 'us_ascii' => 'US-ASCII', - 'iso_8859_1' => 'ISO-8859-1 (Latin-1, Western European)', - 'iso_8859_2' => 'ISO-8859-2 (Latin-2, Central European)', - 'iso_8859_3' => 'ISO-8859-3 (Latin-3, South European)', - 'iso_8859_4' => 'ISO-8859-4 (Latin-4, North European)', - 'iso_8859_5' => 'ISO-8859-5 (Latin, Cyrillic)', - 'iso_8859_6' => 'ISO-8859-6 (Latin, Arabic)', - 'iso_8859_7' => 'ISO-8859-7 (Latin, Greek)', - 'iso_8859_8' => 'ISO-8859-8 (Latin, Hebrew)', - 'iso_8859_0' => 'ISO-8859-9 (Latin-5, Turkish)', - 'iso_8859_10' => 'ISO-8859-10 (Latin-6, Nordic)', - 'iso_8859_11' => 'ISO-8859-11 (Latin, Thai)', - 'iso_8859_13' => 'ISO-8859-13 (Latin-7, Baltic Rim)', - 'iso_8859_14' => 'ISO-8859-14 (Latin-8, Celtic)', - 'iso_8859_15' => 'ISO-8859-15 (Latin-9, Western European revision with euro sign)', - 'windows_1251' => 'Windows-1251 (CP1251)', - 'windows_1252' => 'Windows-1252 (CP1252)', - ], -]; diff --git a/extensions/igniterlabs/importexport/models/ExportModel.php b/extensions/igniterlabs/importexport/models/ExportModel.php deleted file mode 100644 index 7d6505b..0000000 --- a/extensions/igniterlabs/importexport/models/ExportModel.php +++ /dev/null @@ -1,183 +0,0 @@ - 'Column label', - * 'db_column_name2' => 'Another label', - * ], - * [...] - */ - abstract public function exportData($columns); - - /** - * Export data based on column names and labels. - * The $columns array should be in the format of: - * - * [ - * 'db_column_name1' => 'Column label', - * 'db_column_name2' => 'Another label', - * ... - * ] - * @return string - */ - public function export($columns, $options) - { - $data = $this->exportData(array_keys($columns)); - - return $this->processExportData($columns, $data, $options); - } - - /** - * Download a previously compiled export file. - * @param null $outputName - * @return \Symfony\Component\HttpFoundation\BinaryFileResponse - */ - public function download($name, $outputName = null) - { - if (!preg_match('/^ti-export-[0-9a-z]*$/i', $name)) { - throw new ApplicationException(lang('igniterlabs.importexport::default.error_file_not_found')); - } - - $csvPath = temp_path().'/'.$name; - if (!file_exists($csvPath)) { - throw new ApplicationException(lang('igniterlabs.importexport::default.error_file_not_found')); - } - - return Response::download($csvPath, $outputName)->deleteFileAfterSend(true); - } - - /** - * Converts a data collection to a CSV file. - * @return string - */ - protected function processExportData($columns, $results, $options) - { - if (!$results) { - throw new ApplicationException(lang('igniterlabs.importexport::default.error_empty_data')); - } - - $columns = $this->exportExtendColumns($columns); - - $csvWriter = $this->prepareCsvWriter($options, $columns, $results); - - $csvName = 'ti-export-'.md5(get_class($this)); - $csvPath = temp_path().'/'.$csvName; - $output = $csvWriter->toString(); - - File::put($csvPath, $output); - - return $csvName; - } - - /** - * Used to override column definitions at export time. - * @return array - */ - protected function exportExtendColumns($columns) - { - return $columns; - } - - protected function prepareCsvWriter($options, $columns, $results) - { - $defaultOptions = [ - 'firstRowTitles' => true, - 'useOutput' => false, - 'fileName' => 'export.csv', - 'delimiter' => null, - 'enclosure' => null, - 'escape' => null, - ]; - - $options = array_merge($defaultOptions, $options); - - $csvWriter = CsvWriter::createFromFileObject(new SplTempFileObject); - - $csvWriter->setOutputBOM(CsvWriter::BOM_UTF8); - - if (!is_null($options['delimiter'])) { - $csvWriter->setDelimiter($options['delimiter']); - } - - if (!is_null($options['enclosure'])) { - $csvWriter->setEnclosure($options['enclosure']); - } - - if (!is_null($options['escape'])) { - $csvWriter->setEscape($options['escape']); - } - - // Insert headers - if ($options['firstRowTitles']) { - $csvWriter->insertOne($this->getColumnHeaders($columns)); - } - - // Insert records - foreach ($results as $result) { - $csvWriter->insertOne($this->processExportRow($columns, $result)); - } - - if ($options['useOutput']) { - $csvWriter->output($options['fileName']); - } - - return $csvWriter; - } - - protected function getColumnHeaders($columns) - { - $headers = []; - foreach ($columns as $label) { - $headers[] = lang($label); - } - - return $headers; - } - - protected function processExportRow($columns, $record) - { - $results = []; - foreach ($columns as $column => $label) { - $results[] = array_get($record, $column); - } - - return $results; - } - - /** - * Implodes a single dimension array using pipes (|) - * Multi dimensional arrays are not allowed. - * @param string $delimiter - * @return string - */ - protected function encodeArrayValue($data, $delimiter = '|') - { - $newData = []; - foreach ($data as $value) { - if (is_array($value)) { - $newData[] = 'Array'; - } else { - $newData[] = str_replace($delimiter, '\\'.$delimiter, $value); - } - } - - return implode($delimiter, $newData); - } -} diff --git a/extensions/igniterlabs/importexport/models/ImportModel.php b/extensions/igniterlabs/importexport/models/ImportModel.php deleted file mode 100644 index 9550564..0000000 --- a/extensions/igniterlabs/importexport/models/ImportModel.php +++ /dev/null @@ -1,251 +0,0 @@ - 0, - 'created' => 0, - 'errors' => [], - 'warnings' => [], - 'skipped' => [], - ]; - - /** - * Called when data has being imported. - * The $results array should be in the format of: - * - * [ - * 'db_name1' => 'Some value', - * 'db_name2' => 'Another value' - * ], - * [...] - */ - abstract public function importData($results); - - /** - * Import data based on column names matching header indexes in the CSV. - * The $matches array should be in the format of: - * - * [ - * 0 => [db_column_name1, db_column_name2], - * 1 => [db_column_name3], - * ... - * ] - * - * The key (0, 1) is the column index in the CSV and the value - * is another array of target database column names. - * @param array $options - */ - public function import($matches, $options = []) - { - $path = $this->getImportFilePath(); - $data = $this->processImportData($path, $matches, $options); - - return $this->importData($data); - } - - public function getImportFilePath() - { - return temp_path().'/ti-import-'.md5(get_class($this)).'.csv'; - } - - /** - * Converts column index to database column map to an array containing - * database column names and values pulled from the CSV file. Eg: - * - * [0 => [first_name], 1 => [last_name]] - * - * Will return: - * - * [first_name => Chef, last_name => Sam], - * [first_name => John, last_name => Doe], - * [...] - * - * @return array - */ - protected function processImportData($filePath, $matches, $options) - { - $csvReader = $this->prepareCsvReader($options, $filePath, $matches); - - $result = []; - $csvStatement = CsvStatement::create(); - $contents = $csvStatement->process($csvReader); - foreach ($contents as $row) { - $result[] = $this->processImportRow($row, $matches); - } - - return $result; - } - - protected function prepareCsvReader($options, $filePath) - { - $defaultOptions = [ - 'firstRowTitles' => true, - 'delimiter' => null, - 'enclosure' => null, - 'escape' => null, - 'encoding' => null, - ]; - - $options = array_merge($defaultOptions, $options); - - $csvReader = CsvReader::createFromPath($filePath, 'r+'); - - // Filter out empty rows - // $csvReader->addFilter(function (array $row) { - // return count($row) > 1 || reset($row) !== null; - // }); - - if (!is_null($options['delimiter'])) { - $csvReader->setDelimiter($options['delimiter']); - } - - if (!is_null($options['enclosure'])) { - $csvReader->setEnclosure($options['enclosure']); - } - - if (!is_null($options['escape'])) { - $csvReader->setEscape($options['escape']); - } - - // if ($options['firstRowTitles']) - // $csvReader->setOffset(1); - - if (is_null($options['encoding']) && $csvReader->isActiveStreamFilter()) { - $csvReader->appendStreamFilter(sprintf( - '%s%s:%s', - 'igniter.csv.transcode.', - strtolower($options['encoding']), - 'utf-8' - )); - } - - return $csvReader; - } - - /** - * Converts a single row of CSV data to the column map. - * @return array - */ - protected function processImportRow($rowData, $matches) - { - $newRow = []; - - foreach ($matches as $columnIndex => $dbNames) { - $value = array_get($rowData, $columnIndex); - foreach ((array)$dbNames as $dbName) { - $newRow[$dbName] = $value; - } - } - - return $newRow; - } - - protected function decodeArrayValue($value, $delimiter = '|') - { - if (strpos($value, $delimiter) === false) { - return [$value]; - } - - $data = preg_split('~(?resultStats['errorCount'] = count($this->resultStats['errors']); - $this->resultStats['warningCount'] = count($this->resultStats['warnings']); - $this->resultStats['skippedCount'] = count($this->resultStats['skipped']); - - $this->resultStats['hasMessages'] = ( - $this->resultStats['errorCount'] > 0 || - $this->resultStats['warningCount'] > 0 || - $this->resultStats['skippedCount'] > 0 - ); - - return (object)$this->resultStats; - } - - protected function logUpdated() - { - $this->resultStats['updated']++; - } - - protected function logCreated() - { - $this->resultStats['created']++; - } - - protected function logError($rowIndex, $message) - { - $this->resultStats['errors'][$rowIndex] = $message; - } - - protected function logWarning($rowIndex, $message) - { - $this->resultStats['warnings'][$rowIndex] = $message; - } - - protected function logSkipped($rowIndex, $message) - { - $this->resultStats['skipped'][$rowIndex] = $message; - } -} diff --git a/extensions/igniterlabs/importexport/models/config/exportmodel.php b/extensions/igniterlabs/importexport/models/config/exportmodel.php deleted file mode 100644 index 8e63993..0000000 --- a/extensions/igniterlabs/importexport/models/config/exportmodel.php +++ /dev/null @@ -1,70 +0,0 @@ - [ - 'toolbar' => [ - 'buttons' => [ - 'exportRecords' => [ - 'label' => 'lang:igniterlabs.importexport::default.button_export_records', - 'class' => 'btn btn-primary', - 'data-request' => 'onExport', - 'data-progress-indicator' => 'igniterlabs.importexport::default.text_processing', - ], - ], - ], - 'fields' => [ - 'step_primary' => [ - 'label' => 'lang:igniterlabs.importexport::default.text_tab_title_export_primary', - 'type' => 'section', - ], - 'offset' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_offset', - 'type' => 'number', - 'span' => 'left', - 'comment' => 'lang:igniterlabs.importexport::default.help_offset', - ], - 'limit' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_limit', - 'type' => 'number', - 'span' => 'right', - 'comment' => 'lang:igniterlabs.importexport::default.help_limit', - ], - 'delimiter' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_delimiter', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => ',', - 'comment' => 'lang:igniterlabs.importexport::default.help_delimiter', - ], - 'enclosure' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_enclosure', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => '"', - 'comment' => 'lang:igniterlabs.importexport::default.help_enclosure', - ], - 'escape' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_escape', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => '\\', - ], - 'step_columns' => [ - 'label' => 'lang:igniterlabs.importexport::default.text_tab_title_export_columns', - 'type' => 'section', - ], - 'export_columns' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_columns', - 'type' => 'partial', - 'path' => '$/igniterlabs/importexport/actions/exportcontroller/export_columns', - ], - 'step_secondary' => [ - 'label' => 'lang:igniterlabs.importexport::default.text_tab_title_export_secondary', - 'type' => 'section', - ], - ], - ], -]; diff --git a/extensions/igniterlabs/importexport/models/config/importmodel.php b/extensions/igniterlabs/importexport/models/config/importmodel.php deleted file mode 100644 index 1bee314..0000000 --- a/extensions/igniterlabs/importexport/models/config/importmodel.php +++ /dev/null @@ -1,72 +0,0 @@ - [ - 'toolbar' => [ - 'buttons' => [ - 'back' => [ - 'label' => 'lang:admin::lang.button_icon_back', - 'class' => 'btn btn-outline-secondary', - 'href' => 'igniterlabs/importexport/importexport', - ], - 'importRecords' => [ - 'label' => 'lang:igniterlabs.importexport::default.button_import_records', - 'class' => 'btn btn-primary', - 'data-request' => 'onImport', - 'data-progress-indicator' => 'igniterlabs.importexport::default.text_processing', - ], - ], - ], - 'fields' => [ - 'step_primary' => [ - 'label' => 'lang:igniterlabs.importexport::default.text_tab_title_import_primary', - 'type' => 'section', - ], - 'import_file' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_import_file', - 'type' => 'partial', - 'path' => '$/igniterlabs/importexport/actions/importcontroller/import_file_upload', - 'span' => 'left', - ], - 'encoding' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_encoding', - 'type' => 'select', - 'span' => 'right', - ], - 'delimiter' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_delimiter', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => ',', - 'comment' => 'lang:igniterlabs.importexport::default.help_delimiter', - ], - 'enclosure' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_enclosure', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => '"', - 'comment' => 'lang:igniterlabs.importexport::default.help_enclosure', - ], - 'escape' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_escape', - 'type' => 'text', - 'span' => 'left', - 'cssClass' => 'flex-width', - 'default' => '\\', - ], - 'step_columns' => [ - 'label' => 'lang:igniterlabs.importexport::default.text_tab_title_import_columns', - 'type' => 'section', - ], - 'import_columns' => [ - 'label' => 'lang:igniterlabs.importexport::default.label_import_columns', - 'type' => 'partial', - 'cssClass' => 'mb-0', - 'path' => '$/igniterlabs/importexport/actions/importcontroller/import_columns', - 'emptyMessage' => 'lang:igniterlabs.importexport::default.text_no_import_file', - ], - ], - ], -]; diff --git a/extensions/igniterlabs/importexport/traits/ImportExportHelper.php b/extensions/igniterlabs/importexport/traits/ImportExportHelper.php deleted file mode 100644 index 77496a6..0000000 --- a/extensions/igniterlabs/importexport/traits/ImportExportHelper.php +++ /dev/null @@ -1,212 +0,0 @@ -controller->makePartial('import_export_'.$partial, $params + $this->vars, false); - if (!$contents) { - $contents = $this->makePartial($partial, $params); - } - - return $contents; - } - - protected function getModelForType($type) - { - if (!is_null($this->{$type.'Model'})) { - return $this->{$type.'Model'}; - } - - $modelClass = $this->getConfig('record[model]'); - if (!$modelClass) { - throw new ApplicationException(sprintf(lang('igniterlabs.importexport::default.error_missing_model'), $type)); - } - - return $this->{$type.'Model'} = new $modelClass; - } - - protected function makeListColumns($configFile) - { - $columns = $this->loadConfig($configFile, [], 'columns'); - if (!is_array($columns)) { - return null; - } - - $result = []; - foreach ($columns as $attribute => $column) { - if (is_array($column)) { - $result[$attribute] = array_get($column, 'label', $attribute); - } else { - $result[$attribute] = $column ?: $attribute; - } - } - - return $result; - } - - protected function checkPermissions() - { - $permissions = (array)$this->getConfig('record[permissions]'); - - if ($permissions && !AdminAuth::getUser()->hasPermission($permissions)) { - return Redirect::back(302, [], Admin::url('dashboard')); - } - } - - protected function getRedirectUrl() - { - $redirect = $this->getConfig('redirect'); - - if (!is_null($redirect)) { - return $redirect ? Admin::url($redirect) : 'javascript:;'; - } - - return $this->controller->refresh(); - } - - protected function makePrimaryFormWidgetForType($model, $type) - { - $configFile = $this->getConfig('configFile'); - $modelConfig = $this->loadConfig($configFile, ['form'], 'form'); - $widgetConfig = array_except($modelConfig, 'toolbar'); - $widgetConfig['model'] = $model; - $widgetConfig['alias'] = $type.'PrimaryForm'; - $widgetConfig['cssClass'] = $type.'-primary-form'; - - $widget = $this->makeWidget(\Admin\Widgets\Form::class, $widgetConfig); - - $widget->bindEvent('form.extendFieldsBefore', function () use ($type, $widget) { - $this->controller->{$type.'FormExtendFieldsBefore'}($widget); - }); - - $widget->bindEvent('form.extendFields', function ($fields) use ($type, $widget) { - $this->controller->{$type.'FormExtendFields'}($widget, $fields); - }); - - $widget->bindEvent('form.beforeRefresh', function ($holder) { - $holder->data = []; - }); - - $widget->bindToController(); - - if (isset($modelConfig['toolbar']) && isset($this->controller->widgets['toolbar'])) { - $toolbarWidget = $this->controller->widgets['toolbar']; - if ($toolbarWidget instanceof Toolbar) { - $toolbarWidget->addButtons(array_get($modelConfig['toolbar'], 'buttons', [])); - } - - $this->{$type.'ToolbarWidget'} = $toolbarWidget; - } - - return $widget; - } - - protected function loadRecordConfig($type, $recordName) - { - $config = $this->getConfig(); - $config['record'] = ImportExportManager::instance()->getRecordConfig($type, $recordName); - - $this->setConfig($config); - } - - protected function makeSecondaryFormWidgetForType($model, $type) - { - if ( - (!$configFile = $this->getConfig('record[configFile]')) || - (!$fields = $this->loadConfig($configFile, [], 'fields')) - ) { - return null; - } - - $widgetConfig['fields'] = $fields; - $widgetConfig['model'] = $model; - $widgetConfig['alias'] = $type.'SecondaryForm'; - $widgetConfig['arrayName'] = ucfirst($type).'Secondary'; - $widgetConfig['cssClass'] = $type.'-secondary-form'; - - $widget = $this->makeWidget(\Admin\Widgets\Form::class, $widgetConfig); - - $widget->bindToController(); - - return $widget; - } - - protected function processExportColumnsFromPost() - { - $result = []; - $definitions = $this->getExportColumns(); - - $columns = post('export_columns', []); - foreach ($columns as $column) { - $result[$column] = array_get($definitions, $column, '???'); - } - - return $result; - } - - protected function getFormatOptionsFromPost() - { - $options['delimiter'] = post('delimiter'); - $options['enclosure'] = post('enclosure'); - $options['escape'] = post('escape'); - $options['encoding'] = post('encoding'); - - return $options; - } - - protected function createCsvReader($path) - { - $reader = CsvReader::createFromPath($path, 'r'); - $options = $this->getFormatOptionsFromPost(); - - if ($options['delimiter'] !== null) { - $reader->setDelimiter($options['delimiter']); - } - - if ($options['enclosure'] !== null) { - $reader->setEnclosure($options['enclosure']); - } - - if ($options['escape'] !== null) { - $reader->setEscape($options['escape']); - } - - if (!is_null($options['encoding']) && $reader->isActiveStreamFilter()) { - $reader->appendStreamFilter(sprintf( - '%s%s:%s', - 'igniter.csv.transcode.', - strtolower($options['encoding']), - 'utf-8' - )); - } - - return $reader; - } - - protected function getImportMatchColumns() - { - $matches = post('match_columns', []); - $columns = array_filter(post('import_columns', [])); - if (!$matches || !$columns) { - throw new ApplicationException('Please select columns to import'); - } - - $result = []; - foreach ($matches as $index => $column) { - $result[$index] = array_get($columns, $index, $column); - } - - return $result; - } -} diff --git a/extensions/igniterlabs/importexport/views/importexport/export.blade.php b/extensions/igniterlabs/importexport/views/importexport/export.blade.php deleted file mode 100644 index 5acdada..0000000 --- a/extensions/igniterlabs/importexport/views/importexport/export.blade.php +++ /dev/null @@ -1,13 +0,0 @@ -
- {!! form_open([ - 'id' => 'form-widget', - 'role' => 'form', - 'method' => 'PATCH', - 'enctype' => 'multipart/form-data', - ]) !!} - - {!! $this->renderExport() !!} - - {!! form_close() !!} -
- diff --git a/extensions/igniterlabs/importexport/views/importexport/import.blade.php b/extensions/igniterlabs/importexport/views/importexport/import.blade.php deleted file mode 100644 index d4181b5..0000000 --- a/extensions/igniterlabs/importexport/views/importexport/import.blade.php +++ /dev/null @@ -1,12 +0,0 @@ -
- {!! form_open([ - 'id' => 'form-widget', - 'role' => 'form', - 'enctype' => 'multipart/form-data', - 'method' => 'POST', - ]) !!} - - {!! $this->renderImport() !!} - - {!! form_close() !!} -
diff --git a/extensions/igniterlabs/importexport/views/importexport/index.blade.php b/extensions/igniterlabs/importexport/views/importexport/index.blade.php deleted file mode 100644 index 9aa0125..0000000 --- a/extensions/igniterlabs/importexport/views/importexport/index.blade.php +++ /dev/null @@ -1,61 +0,0 @@ -
-
-
-
-
-
@lang('igniterlabs.importexport::default.text_import_export_title')
-
-
- - - -
-
-
-
-
@lang('igniterlabs.importexport::default.text_history_title')
-
-
-
-
-
-
-
-
-
diff --git a/extensions/igniterlabs/importexport/views/importexport/new_import_export_popup.blade.php b/extensions/igniterlabs/importexport/views/importexport/new_import_export_popup.blade.php deleted file mode 100644 index 3df970f..0000000 --- a/extensions/igniterlabs/importexport/views/importexport/new_import_export_popup.blade.php +++ /dev/null @@ -1,34 +0,0 @@ -{!! form_open([ - 'role' => 'form', - 'data-request' => 'onLoadForm', -]) !!} - - - - -{!! form_close() !!}