diff --git a/.env.example b/.env.example index 7e350ea7..51d44f7d 100644 --- a/.env.example +++ b/.env.example @@ -3,13 +3,22 @@ APP_KEY= APP_DEBUG=true APP_URL=http://localhost APP_NAME=BEEP + +APP_FALLBACK_LOCALE=en +APP_FAKER_LOCALE=en_US +APP_MAINTENANCE_DRIVER=file +APP_MAINTENANCE_STORE=database +# PHP_CLI_SERVER_WORKERS=4 + +BCRYPT_ROUNDS=12 APP_LOCALE=en BETA=false ALLOWED_ORIGINS="*" LOG_CHANNEL=stack -WEBHOOK_URL= +LOG_STACK=single +LOG_SLACK_WEBHOOK_URL= DB_CONNECTION=mysql DB_HOST=mysql @@ -33,11 +42,14 @@ INFLUXDB_UDP_PORT=4444 INFLUXDB_DBNAME=bee_data INFLUXDB_PASSWORD=pass_influx -BROADCAST_DRIVER=log -CACHE_DRIVER=redis +BROADCAST_CONNECTION=log +CACHE_STORE=redis QUEUE_CONNECTION=sync SESSION_DRIVER=redis SESSION_LIFETIME=126 +SESSION_ENCRYPT=false +SESSION_PATH=/ +SESSION_DOMAIN=null SESSION_CONNECTION=default MEMCACHED_HOST=127.0.0.1 @@ -52,12 +64,12 @@ REDIS_HOST=redis REDIS_PASSWORD=null REDIS_PORT=6379 -MAIL_DRIVER=smtp +MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=username MAIL_PASSWORD=password -MAIL_ENCRYPTION=tls +MAIL_SCHEME=null PUSHER_APP_ID= PUSHER_KEY= @@ -81,7 +93,7 @@ AWS_ACCESS_KEY_ID=null AWS_SECRET_ACCESS_KEY=null AWS_DEFAULT_REGION=eu-central-1 AWS_BUCKET=null -AWS_URL=https://assets.beep.nl +AWS_URL=https://assets.beep.nl/ IMAGE_STORAGE=public IMAGE_RESIZE_PIXELS=2000 diff --git a/.gitignore b/.gitignore index 514cb37d..5f838376 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +*.log /vendor !resources/views/vendor/ @@ -24,7 +25,7 @@ Homestead.json Homestead.yaml .env .env.docs -.phpunit.result.cache +/.phpunit.cache .DS_Store .phpintel .log @@ -33,8 +34,10 @@ Homestead.yaml npm-debug.log yarn-error.log /.idea +/.nova /.vscode /.vagrant /node_modules dump.rdb +/storage/pail diff --git a/app/BeeRace.php b/app/BeeRace.php index 8ce229c7..8cb69872 100644 --- a/app/BeeRace.php +++ b/app/BeeRace.php @@ -2,11 +2,10 @@ namespace App; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Guarded; use Illuminate\Database\Eloquent\Model; -class BeeRace extends Model -{ - protected $fillable = ['name', 'type', 'synonyms', 'continents']; - protected $guarded = ['id']; - -} +#[Fillable('name', 'type', 'synonyms', 'continents')] +#[Guarded('id')] +class BeeRace extends Model {} diff --git a/app/Category.php b/app/Category.php index ec7d54aa..8b54305a 100644 --- a/app/Category.php +++ b/app/Category.php @@ -2,55 +2,55 @@ namespace App; +use Cache; +use Illuminate\Database\Eloquent\Attributes\Appends; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Guarded; +use Illuminate\Database\Eloquent\Attributes\Hidden; +use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\Relations\HasOne; use Kalnoy\Nestedset\NodeTrait; use LaravelLocalization; -use Cache; +#[Table('categories')] +#[Fillable('name', 'category_input_id', 'physical_quantity_id', 'parent_id', 'description', 'source', 'icon', 'type', 'required')] +#[Guarded('id')] +#[Hidden('created_at', 'updated_at', 'category_input_id', 'physical_quantity_id', '_lft', '_rgt', 'pivot', 'input_type', 'options', 'old_id')] +#[Appends('input', 'trans', 'unit')] class Category extends Model { use NodeTrait; - protected $table = 'categories'; - - protected $fillable = ['name', 'category_input_id', 'physical_quantity_id', 'parent_id', 'description', 'source', 'icon', 'type', 'required']; - protected $guarded = ['id']; - - protected $hidden = ['created_at','updated_at', 'category_input_id', 'physical_quantity_id','_lft','_rgt','pivot','input_type','options','old_id']; - - protected $appends = ['input','trans','unit']; //'parent' - - public static $types= - [ - 'checklist' => 'Hive checklist item', - 'research' => 'Research specific item', - 'system' => 'System (required for interface)', - ]; + public static $types = + [ + 'checklist' => 'Hive checklist item', + 'research' => 'Research specific item', + 'system' => 'System (required for interface)', + ]; public static function boot() { parent::boot(); - static::created(function($c) - { + static::created(function ($c) { $c->forgetCache(); }); - static::updated(function($c) - { + static::updated(function ($c) { $c->forgetCache(); }); - static::deleted(function($c) - { + static::deleted(function ($c) { $c->forgetCache(); - Translation::where('type','category')->where('name', $c->name)->delete(); + Translation::where('type', 'category')->where('name', $c->name)->delete(); }); } public function forgetCache() { - + Cache::forget('cat-'.$this->id.'-input-type'); Cache::forget('root-'.$this->id.'-anc'); Cache::forget('root-'.$this->id.'-trans-anc'); @@ -60,9 +60,8 @@ public function forgetCache() Cache::forget("queen-race-$this->id-name"); $locales = Language::pluck('twochar'); - - foreach ($locales as $locale) - { + + foreach ($locales as $locale) { // Category Cache::forget('trans-'.$this->id.'-'.$this->name); Cache::forget('trans-'.$this->id.'-'.$this->name.'-lan'); @@ -73,7 +72,7 @@ public function forgetCache() Cache::forget('area-type-array-'.$locale); Cache::forget('area-type-array-'.$locale.'-translated'); } - + self::forgetTaxonomyListCache(); } @@ -90,12 +89,13 @@ public static function forgetTaxonomyListCache() // Relations public function getInputAttribute() { - if ($this->category_input_id != null) - { + if ($this->category_input_id != null) { $type = CategoryInput::where('id', $this->category_input_id)->value('type'); - if ($type) + if ($type) { return $type; + } } + return null; } @@ -119,51 +119,55 @@ public function getTransAttribute() return $this->trans(); } - public function getUnitAttribute($value=null) // PGe 2022-05-23: apparently the $value is filled with '' in case of an append + public function getUnitAttribute($value = null) // PGe 2022-05-23: apparently the $value is filled with '' in case of an append { - if (empty($value)) + if (empty($value)) { $value = 'abbreviation'; + } - if ($this->physical_quantity_id != null && $this->physicalQuantity) + if ($this->physical_quantity_id != null && $this->physicalQuantity) { return $this->physicalQuantity()->value($value); + } return null; } public function getPhysicalQuantityNameAttribute() { - if ($this->physical_quantity_id != null && $this->physicalQuantity) + if ($this->physical_quantity_id != null && $this->physicalQuantity) { return $this->physicalQuantity()->value('name'); + } return null; } - - public function physicalQuantity() + + public function physicalQuantity(): HasOne { return $this->hasOne(PhysicalQuantity::class, 'id', 'physical_quantity_id'); } - public function checklists() + public function checklists(): BelongsToMany { return $this->belongsToMany(Checklist::class, 'checklist_category'); } - public function inputType() + public function inputType(): HasOne { return $this->hasOne(CategoryInput::class, 'id', 'category_input_id'); } - public function isSystem() { - if ($this->type == 'system') + if ($this->type == 'system') { return true; + } $ancTypeArr = $this->ancestors->pluck('type')->toArray(); - if (in_array('system', $ancTypeArr)) + if (in_array('system', $ancTypeArr)) { return true; - //die(print_r(['anc'=>$ancTypeArr, 'cat'=>$this->name])); + } + // die(print_r(['anc'=>$ancTypeArr, 'cat'=>$this->name])); return false; } @@ -171,8 +175,9 @@ public function isSystem() public function physicalQuantityId() { $quan = $this->physicalQuantity; - if (isset($quan)) + if (isset($quan)) { return $quan->id; + } return null; } @@ -180,8 +185,9 @@ public function physicalQuantityId() public function inputTypeName() { $type = $this->inputType; - if (isset($type)) + if (isset($type)) { return $type->name; + } return ''; } @@ -189,8 +195,9 @@ public function inputTypeName() public function inputTypeType() { $type = $this->inputType; - if (isset($type)) + if (isset($type)) { return $type->type; + } return ''; } @@ -198,8 +205,9 @@ public function inputTypeType() public function inputTypeIcon() { $type = $this->inputType; - if (isset($type)) + if (isset($type)) { return $type->glyphIcon(); + } return ''; } @@ -207,8 +215,9 @@ public function inputTypeIcon() public function inputTypeId() { $type = $this->inputType; - if (isset($type)) + if (isset($type)) { return $type->id; + } return null; } @@ -216,47 +225,51 @@ public function inputTypeId() public function inputRange() { $type = $this->inputType; - $range= []; - $types= ['boolean','boolean_yes_red','score_quality','score_amount','smileys_3']; + $range = []; + $types = ['boolean', 'boolean_yes_red', 'score_quality', 'score_amount', 'smileys_3']; - if (isset($type)) - { + if (isset($type)) { $inputType = $type->type; - if (in_array($inputType, $types)) - { + if (in_array($inputType, $types)) { $type_trans_array = __("taxonomy.$inputType"); - //dd($type_trans_array); - for ($i=0; $i < count($type_trans_array); $i++) + // dd($type_trans_array); + for ($i = 0; $i < count($type_trans_array); $i++) { $range[] = "$i=".$type->render($i); - } - else - { - if (isset($type->min)) array_push($range, __('crud.min').': '.$type->min); - if (isset($type->max)) array_push($range, __('crud.max').': '.$type->max); + } + } else { + if (isset($type->min)) { + array_push($range, __('crud.min').': '.$type->min); + } + if (isset($type->max)) { + array_push($range, __('crud.max').': '.$type->max); + } } } + return count($range) == 0 ? null : implode("\n", $range); } -public function translation($language_abbr) + public function translation($language_abbr) { - return Cache::rememberForever('trans-'.$this->id.'-'.$language_abbr, function () use ($language_abbr){ + return Cache::rememberForever('trans-'.$this->id.'-'.$language_abbr, function () use ($language_abbr) { $lang_id = Language::where('abbreviation', $language_abbr)->pluck('id'); - if ($lang_id) - return Translation::where('type','category')->where('language_id', $lang_id)->where('name', $this->name)->value('translation'); - + if ($lang_id) { + return Translation::where('type', 'category')->where('language_id', $lang_id)->where('name', $this->name)->value('translation'); + } + return $this->name; }); } public function translations() { - return Cache::rememberForever('trans-'.$this->id.'-'.$this->name.'-lan', function (){ - $trans = Translation::where('type','category')->where('name', $this->name)->pluck('translation','language_id'); - if ($trans) + return Cache::rememberForever('trans-'.$this->id.'-'.$this->name.'-lan', function () { + $trans = Translation::where('type', 'category')->where('name', $this->name)->pluck('translation', 'language_id'); + if ($trans) { return $trans; - - return [['translation'=>$this->name, 'language_id'=>0]]; + } + + return [['translation' => $this->name, 'language_id' => 0]]; }); } @@ -269,57 +282,61 @@ public function trans() public function transName($locale = null) { - if ($locale == null) + if ($locale == null) { $locale = LaravelLocalization::getCurrentLocale(); - - return Cache::rememberForever('trans-'.$this->id.'-'.$locale.'-'.$this->name, function () use ($locale){ + } + + return Cache::rememberForever('trans-'.$this->id.'-'.$locale.'-'.$this->name, function () use ($locale) { $trans = $this->trans; + return isset($trans[$locale]) ? $trans[$locale] : $this->name; }); } - public function ancName($locale = null, $sep = " > ") + public function ancName($locale = null, $sep = ' > ') { - if ($locale == null) + if ($locale == null) { $locale = LaravelLocalization::getCurrentLocale(); - - return Cache::rememberForever('trans-'.$this->id.'-'.$locale.'-'.$this->name.'-anc', function () use ($locale, $sep){ - $ancest = $this->getAncestors()->map(function($item,$key) use ($locale, $sep){ + } + + return Cache::rememberForever('trans-'.$this->id.'-'.$locale.'-'.$this->name.'-anc', function () use ($locale, $sep) { + $ancest = $this->getAncestors()->map(function ($item, $key) use ($locale, $sep) { return $item->transName($locale).$sep; }); + return $ancest->implode(''); }); } public function rootName($locale = null) { - if ($locale == null) + if ($locale == null) { $locale = LaravelLocalization::getCurrentLocale(); + } - $ancest = Cache::rememberForever('root-'.$this->id.'-trans-anc', function () - { + $ancest = Cache::rememberForever('root-'.$this->id.'-trans-anc', function () { return $this->getAncestors(); }); - if ($ancest->count() > 0) + if ($ancest->count() > 0) { return $ancest->get(0)->transName($locale); + } - return ""; + return ''; } public function rootNodeName() { - $ancest = Cache::rememberForever('root-'.$this->id.'-anc', function () - { + $ancest = Cache::rememberForever('root-'.$this->id.'-anc', function () { return $this->getAncestors(); }); - if ($ancest->count() > 0) + if ($ancest->count() > 0) { return $ancest->get(0)->name; + } - return ""; + return ''; } - public function useAmount() { $i = InspectionItem::where('category_id', $this->id)->count(); @@ -331,36 +348,37 @@ public function useAmount() $q = Queen::where('race_id', $this->id)->count(); $o = isset($this->old_id) ? 1 : 0; - $total_usage = $i+$v+$h+$f+$l+$s+$q+$o; + $total_usage = $i + $v + $h + $f + $l + $s + $q + $o; return $total_usage; } // // finding on ::type() - // public function scopeType() + // public function scopeType() // { // return $this->inputTypeType; // } // //finding on ::name() - // public function scopeName($query, $name) + // public function scopeName($query, $name) // { // return $query->where('name', $name); // } // // finding on ::name() - // public function scopeTypeName($query, $type, $name) + // public function scopeTypeName($query, $type, $name) // { // return $query->where('type', $type)->where('name', $name); // } - //finding on ::child() - public static function findCategoryByParentAndName($parent_name, $name) + // finding on ::child() + public static function findCategoryByParentAndName($parent_name, $name) { - //$parent = self::whereJoin('name', $parent_name)->whereJoin('children.name', $name)->first(); + // $parent = self::whereJoin('name', $parent_name)->whereJoin('children.name', $name)->first(); $parent = self::where('name', $parent_name)->first(); - if (isset($parent)) + if (isset($parent)) { return $parent->children()->where('name', $name)->first(); + } return new Category; } @@ -368,90 +386,95 @@ public static function findCategoryByParentAndName($parent_name, $name) public static function findCategoryIdByParentAndName($parent_name, $name) { $cat = self::findCategoryByParentAndName($parent_name, $name); - if (isset($cat)) + if (isset($cat)) { return $cat->id; + } return null; } - public static function descendentsByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn=['system']) + public static function descendentsByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn = ['system']) { $category = self::findCategoryByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn); - //die(print_r($category->toArray())); - if (isset($category)) + // die(print_r($category->toArray())); + if (isset($category)) { return self::whereDescendantOf($category)->get(); + } return []; } - public static function findCategoryByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn=['system']) + public static function findCategoryByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn = ['system']) { $root = self::whereIsRoot()->where('name', $root_name)->first(); - if ($root_name === $parent_name && isset($root)) + if ($root_name === $parent_name && isset($root)) { $parent = $root; - else + } else { $parent = self::descendantsAndSelf($root)->whereIn('type', $whereTypeIn)->where('name', $parent_name)->first(); + } - //dd($parent); - if (isset($parent)) + // dd($parent); + if (isset($parent)) { return $parent->children()->where('name', $name)->first(); + } return new Category; } - public static function findCategoryIdByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn=['system']) + public static function findCategoryIdByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn = ['system']) { $cat = self::findCategoryByRootParentAndName($root_name, $parent_name, $name, $whereTypeIn); - if (isset($cat)) + if (isset($cat)) { return $cat->id; + } return null; } - public static function getRootIds($order=true) + public static function getRootIds($order = true) { $locale = LaravelLocalization::getCurrentLocale(); - if ($order) - return self::whereIsRoot()->whereNotIn('type', ['system'])->get()->sortBy("trans.$locale", SORT_NATURAL|SORT_FLAG_CASE)->pluck('id')->toArray(); + if ($order) { + return self::whereIsRoot()->whereNotIn('type', ['system'])->get()->sortBy("trans.$locale", SORT_NATURAL | SORT_FLAG_CASE)->pluck('id')->toArray(); + } return self::whereIsRoot()->whereNotIn('type', ['system'])->get()->pluck('id')->toArray(); } - public static function getTaxonomy($rootNodes=null, $order=true, $flat=false, $whereNotInTypes=['system']) + public static function getTaxonomy($rootNodes = null, $order = true, $flat = false, $whereNotInTypes = ['system']) { $locale = LaravelLocalization::getCurrentLocale(); - if (gettype($rootNodes) !== 'array' || count($rootNodes) == 0) - { - if ($order === true) - $rootNodes = self::whereIsRoot()->whereNotIn('type', ['system'])->get()->sortBy("trans.$locale", SORT_NATURAL|SORT_FLAG_CASE)->pluck('id'); - else + if (gettype($rootNodes) !== 'array' || count($rootNodes) == 0) { + if ($order === true) { + $rootNodes = self::whereIsRoot()->whereNotIn('type', ['system'])->get()->sortBy("trans.$locale", SORT_NATURAL | SORT_FLAG_CASE)->pluck('id'); + } else { $rootNodes = self::whereIsRoot()->whereNotIn('type', ['system'])->pluck('id'); + } } - - $taxonomy = collect(); - foreach ($rootNodes as $node) - { - if ($flat == true && ($order === null || $order === false)) - $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node) ); - else if ($flat == true && $order === true) - $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node)->sortBy("trans.$locale", SORT_NATURAL|SORT_FLAG_CASE) ); - else if ($flat == false && $order === null) - $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node)->toTree() ); - else if ($flat == false) - { - if (gettype($order) == 'array' && count($order) > 0) - $taxonomy = $taxonomy->merge(self::descendantsAndSelf($node)->whereNotIn('type', $whereNotInTypes)->sortBy(function($cat, $key) use ($order) { return array_search($cat->id, $order); })->toTree()); - else - $taxonomy = $taxonomy->merge(self::descendantsAndSelf($node)->whereNotIn('type', $whereNotInTypes)->sortBy("trans.$locale", SORT_NATURAL|SORT_FLAG_CASE)->toTree()); + + $taxonomy = collect(); + foreach ($rootNodes as $node) { + if ($flat == true && ($order === null || $order === false)) { + $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node)); + } elseif ($flat == true && $order === true) { + $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node)->sortBy("trans.$locale", SORT_NATURAL | SORT_FLAG_CASE)); + } elseif ($flat == false && $order === null) { + $taxonomy = $taxonomy->merge(self::whereNotIn('type', $whereNotInTypes)->descendantsAndSelf($node)->toTree()); + } elseif ($flat == false) { + if (gettype($order) == 'array' && count($order) > 0) { + $taxonomy = $taxonomy->merge(self::descendantsAndSelf($node)->whereNotIn('type', $whereNotInTypes)->sortBy(function ($cat, $key) use ($order) { + return array_search($cat->id, $order); + })->toTree()); + } else { + $taxonomy = $taxonomy->merge(self::descendantsAndSelf($node)->whereNotIn('type', $whereNotInTypes)->sortBy("trans.$locale", SORT_NATURAL | SORT_FLAG_CASE)->toTree()); + } } } return $taxonomy; } - - } diff --git a/app/CategoryFactory.php b/app/CategoryFactory.php index a8d4e0d1..f8855afe 100644 --- a/app/CategoryFactory.php +++ b/app/CategoryFactory.php @@ -6,148 +6,122 @@ class CategoryFactory { - - public function __construct() - { - - } + public function __construct() {} public function get_old_ids_array() { $checklist_ids = collect(); - $root_cats = Category::whereIsRoot()->whereNotIn('type',['system'])->get(); - foreach ($root_cats as $root) - { + $root_cats = Category::whereIsRoot()->whereNotIn('type', ['system'])->get(); + foreach ($root_cats as $root) { $checklist_ids = $checklist_ids->merge(Category::whereDescendantOrSelf($root)->where('old_id', '<>', 'null')->pluck('id')); } - foreach ($checklist_ids as $id) - { + foreach ($checklist_ids as $id) { $checklist_ids = $checklist_ids->merge(Category::whereAncestorOrSelf($id)->pluck('id')); } $checklist_ids = $checklist_ids->unique()->toArray(); + return $checklist_ids; } public function parse_taxonomy($saveToDatabase = true) { - $content = Storage::get('taxonomy.json'); - $json = json_decode($content); - $collect = collect($json); + $content = Storage::get('taxonomy.json'); + $json = json_decode($content); + $collect = collect($json); $taxonomy = $collect->flatten(1)->toArray()[0]->body->outline[0]->outline; - $tax_arr = $this->recurse([], $taxonomy, $saveToDatabase); + $tax_arr = $this->recurse([], $taxonomy, $saveToDatabase); return $tax_arr; } - public function recurse($arr, $cat, $save) - { - // direct categories - if (isset($cat->outline)) - { - if (is_array($cat->outline)) - { - foreach($cat->outline as $o) - { - if (isset($o->_text)) - { - $lbl = $this->formatCategoryString($o->_text, $save); - if (isset($o->outline)) - { - $arr[$lbl] = $this->recurse([], $o, $save); - } - else - { - $arr = $this->addValue($arr, $o->_text, $save); - } - } - } - } - else if (isset($cat->outline->_text)) - { - $arr = $this->addValue($arr, $cat->outline->_text, $save); - } - } + public function recurse($arr, $cat, $save) + { + // direct categories + if (isset($cat->outline)) { + if (is_array($cat->outline)) { + foreach ($cat->outline as $o) { + if (isset($o->_text)) { + $lbl = $this->formatCategoryString($o->_text, $save); + if (isset($o->outline)) { + $arr[$lbl] = $this->recurse([], $o, $save); + } else { + $arr = $this->addValue($arr, $o->_text, $save); + } + } + } + } elseif (isset($cat->outline->_text)) { + $arr = $this->addValue($arr, $cat->outline->_text, $save); + } + } - // sub categories - foreach($cat as $c) - { - if (isset($c->outline)) - { - $lbl1 = $this->formatCategoryString($c->_text, $save); - $arr[$lbl1] = []; + // sub categories + foreach ($cat as $c) { + if (isset($c->outline)) { + $lbl1 = $this->formatCategoryString($c->_text, $save); + $arr[$lbl1] = []; - foreach ($c->outline as $t) - { - if (isset($t->_text)) - { - $lbl2 = $this->formatCategoryString($t->_text, $save); + foreach ($c->outline as $t) { + if (isset($t->_text)) { + $lbl2 = $this->formatCategoryString($t->_text, $save); - if (isset($t->outline)) - { - $arr[$lbl1][$lbl2] = $this->recurse([], $t, $save); - } - else - { - $arr[$lbl1] = $this->addValue($arr[$lbl1], $t->_text, $save); - } - } - } - } - } + if (isset($t->outline)) { + $arr[$lbl1][$lbl2] = $this->recurse([], $t, $save); + } else { + $arr[$lbl1] = $this->addValue($arr[$lbl1], $t->_text, $save); + } + } + } + } + } - return $arr; - } + return $arr; + } - public function addValue($arr, $txt, $save) - { - $lbl = $this->formatCategoryString($txt, $save); - array_push($arr, $lbl); - return $arr; - } + public function addValue($arr, $txt, $save) + { + $lbl = $this->formatCategoryString($txt, $save); + array_push($arr, $lbl); - public function formatCategoryString($str, $save=false) - { - $out = str_replace(' / ', '_', $str); - $out = str_replace(' ', '_', $out); - $out = strtolower($out); - $out = urlencode($out); + return $arr; + } - if ($save) - Translation::saveText('en_gb', $out, 'category', $str); + public function formatCategoryString($str, $save = false) + { + $out = str_replace(' / ', '_', $str); + $out = str_replace(' ', '_', $out); + $out = strtolower($out); + $out = urlencode($out); + + if ($save) { + Translation::saveText('en_gb', $out, 'category', $str); + } - return $out; - } + return $out; + } - public function saveDynamicCategories($categories, $parent_id=null) - { - if (is_array($categories)) - { - foreach ($categories as $name => $category) - { + public function saveDynamicCategories($categories, $parent_id = null) + { + if (is_array($categories)) { + foreach ($categories as $name => $category) { - if (is_array($category)) - { - $cat = new Category; - $cat->type = 'list'; - $cat->name = $name; - $cat->parent_id = $parent_id; - $cat->category_input_id = $this->getCatrgoryInputId('list', 'list'); - $cat->save(); - $this->saveDynamicCategories($category, $cat->id); - } - else - { - $cat = new Category; - $cat->type = $name; - $cat->name = $category; - $cat->parent_id = $parent_id; - $cat->category_input_id = $this->getCatrgoryInputId($name, 'list_item'); - $cat->save(); - } - } - } - else - { + if (is_array($category)) { + $cat = new Category; + $cat->type = 'list'; + $cat->name = $name; + $cat->parent_id = $parent_id; + $cat->category_input_id = $this->getCatrgoryInputId('list', 'list'); + $cat->save(); + $this->saveDynamicCategories($category, $cat->id); + } else { + $cat = new Category; + $cat->type = $name; + $cat->name = $category; + $cat->parent_id = $parent_id; + $cat->category_input_id = $this->getCatrgoryInputId($name, 'list_item'); + $cat->save(); + } + } + } else { $cat = new Category; $cat->type = 'list_item'; $cat->name = $categories; @@ -155,51 +129,44 @@ public function saveDynamicCategories($categories, $parent_id=null) $cat->category_input_id = $this->getCatrgoryInputId($categories, 'list_item'); $cat->save(); } - } + } - public function getCatrgoryInputId($type, $fallbackType) - { - if (CategoryInput::where('type', $type)->count() > 0) - return CategoryInput::where('type', $type)->value('id'); - - return CategoryInput::where('type', $fallbackType)->value('id'); - } + public function getCatrgoryInputId($type, $fallbackType) + { + if (CategoryInput::where('type', $type)->count() > 0) { + return CategoryInput::where('type', $type)->value('id'); + } + return CategoryInput::where('type', $fallbackType)->value('id'); + } - public function saveStaticCategories($categories) - { - foreach ($categories as $base_key => $base_cat) - { + public function saveStaticCategories($categories) + { + foreach ($categories as $base_key => $base_cat) { $base = new Category; - $base->type = $base_key; - $base->name = $base_key; + $base->type = $base_key; + $base->name = $base_key; $base->save(); - foreach ($base_cat as $cat_key => $cat_obj) - { - - if (is_array($cat_obj)) - { + foreach ($base_cat as $cat_key => $cat_obj) { + + if (is_array($cat_obj)) { $parent = new Category; - $parent->type = 'category'; - $parent->name = $cat_key; + $parent->type = 'category'; + $parent->name = $cat_key; $parent->parent_id = $base->id; $parent->save(); - foreach ($cat_obj as $name => $type) - { - - if (is_array($type)) - { + foreach ($cat_obj as $name => $type) { + + if (is_array($type)) { $child = new Category; - $child->type = 'select'; - $child->name = $name; + $child->type = 'select'; + $child->name = $name; $child->parent_id = $parent->id; - $child->options = implode(',',$type); + $child->options = implode(',', $type); $child->save(); - } - else - { + } else { $cat = new Category; $cat->type = $type; $cat->name = $name; @@ -207,12 +174,10 @@ public function saveStaticCategories($categories) $cat->save(); } } - } - else - { + } else { $cat = new Category; - $cat->type = 'category'; - $cat->name = $cat_obj; + $cat->type = 'category'; + $cat->name = $cat_obj; $cat->parent_id = $base->id; $cat->save(); } @@ -220,91 +185,86 @@ public function saveStaticCategories($categories) } Category::fixTree(); // kalnoy/nestedset: to fix the tree to fill _lft and _rgt columns - } - - + } - public function saveOldCategories() - { - $categories = [ - 'action' =>[ - 'food'=>[ - 'sugar_concentration_perc'=>'number', - 'litres_of_suger_water'=>'number', - ], - 'disease'=>[ - 'varroa_treatment'=>['apistan','formic_acid','lactic_acid','oxalic_acid','powdered_sugar','other'], - ], - 'reminder'=>[ - 'reminder'=>'text', - 'remind_date'=>'date', + public function saveOldCategories() + { + $categories = [ + 'action' => [ + 'food' => [ + 'sugar_concentration_perc' => 'number', + 'litres_of_suger_water' => 'number', ], - 'colony'=>[ - 'split_colony'=>'boolean', - 'merge_colonies'=>'boolean', - ], - 'size', - 'queen'=>[ - 'queen_introduced'=>'text', - 'queen_cells_removed'=>'number', - 'queen_cells_left'=>'number', - ], - 'harvest'=>[ - 'kg_honey_harvested'=>'number', - 'frames_with_honey_left'=>'number', - ], - 'tools', - 'other' + 'disease' => [ + 'varroa_treatment' => ['apistan', 'formic_acid', 'lactic_acid', 'oxalic_acid', 'powdered_sugar', 'other'], + ], + 'reminder' => [ + 'reminder' => 'text', + 'remind_date' => 'date', + ], + 'colony' => [ + 'split_colony' => 'boolean', + 'merge_colonies' => 'boolean', + ], + 'size', + 'queen' => [ + 'queen_introduced' => 'text', + 'queen_cells_removed' => 'number', + 'queen_cells_left' => 'number', + ], + 'harvest' => [ + 'kg_honey_harvested' => 'number', + 'frames_with_honey_left' => 'number', + ], + 'tools', + 'other', ], - 'condition' =>[ - 'overall'=>[ - 'positive_impression'=>'score', - 'needs_attention'=>'boolean', - 'notes'=>'text', - ], - 'activity', - 'brood', - 'development'=>[ - 'frames_with_bees'=>'number', - 'all_stages_of_brood_types'=>['eggs','larvae','pupae'], - 'queen_present'=>'boolean', - 'queen_cells'=>'number', - 'queen_cells_types'=>['swarm','supercedure','emergency'], - ], - 'disease'=>[ - 'varroa_count'=>'number', - ], - 'flight', - 'food'=>[ - 'sufficient_food'=>'score', - 'frames_with_honey'=>'number', - 'frames_with_pollen'=>'number', - ], - 'frame_stability', + 'condition' => [ + 'overall' => [ + 'positive_impression' => 'score', + 'needs_attention' => 'boolean', + 'notes' => 'text', + ], + 'activity', + 'brood', + 'development' => [ + 'frames_with_bees' => 'number', + 'all_stages_of_brood_types' => ['eggs', 'larvae', 'pupae'], + 'queen_present' => 'boolean', + 'queen_cells' => 'number', + 'queen_cells_types' => ['swarm', 'supercedure', 'emergency'], + ], + 'disease' => [ + 'varroa_count' => 'number', + ], + 'flight', + 'food' => [ + 'sufficient_food' => 'score', + 'frames_with_honey' => 'number', + 'frames_with_pollen' => 'number', + ], + 'frame_stability', 'health', - 'loss'=>[ - 'colony_lost'=>'boolean', - 'colony_lost_reason'=>'text', - ], - 'size', - 'space', - 'strength', - 'temper', - 'queen', - 'winter_hardness', - 'other' + 'loss' => [ + 'colony_lost' => 'boolean', + 'colony_lost_reason' => 'text', + ], + 'size', + 'space', + 'strength', + 'temper', + 'queen', + 'winter_hardness', + 'other', ], - 'hive_layer'=>['brood','honey','grid','empty'], - 'hive_frame'=>['wax','block','other'], - 'location' =>['fixed','movable','temporary','other'], - 'production'=>['honey', 'wax', 'pollen', 'other'], - 'setting' =>['app', 'general', 'sensor'], - 'sensor' =>['beep','hiveeyes','arnia','manual','other'], - ]; + 'hive_layer' => ['brood', 'honey', 'grid', 'empty'], + 'hive_frame' => ['wax', 'block', 'other'], + 'location' => ['fixed', 'movable', 'temporary', 'other'], + 'production' => ['honey', 'wax', 'pollen', 'other'], + 'setting' => ['app', 'general', 'sensor'], + 'sensor' => ['beep', 'hiveeyes', 'arnia', 'manual', 'other'], + ]; $this->saveStaticCategories($categories); - } - + } } - - diff --git a/app/CategoryInput.php b/app/CategoryInput.php index 6083d0f7..65231292 100644 --- a/app/CategoryInput.php +++ b/app/CategoryInput.php @@ -2,26 +2,23 @@ namespace App; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Hidden; +use Illuminate\Database\Eloquent\Attributes\Table; +use Illuminate\Database\Eloquent\Attributes\WithoutTimestamps; use Illuminate\Database\Eloquent\Model; -use Moment\Moment; -use App\Category; -use App\Hive; -use App\Location; +use Illuminate\Database\Eloquent\Relations\BelongsTo; use LaravelLocalization; +#[Table('category_inputs')] +#[WithoutTimestamps] +#[Fillable('name', 'type', 'min', 'max', 'decimals', 'icon')] +#[Hidden('icon')] class CategoryInput extends Model { - protected $table = 'category_inputs'; - - public $fillable = ['name','type','min','max','decimals','icon']; - - public $hidden = ['icon']; - - public $timestamps = false; - // Relations - public function category() + public function category(): BelongsTo { return $this->belongsTo(Category::class, 'category_id'); } @@ -30,14 +27,17 @@ public function name_plus() { $out = $this->name; - if (isset($this->min)) + if (isset($this->min)) { $out .= ' | min:'.$this->min; + } - if (isset($this->max)) + if (isset($this->max)) { $out .= ' | max:'.$this->max; + } - if (isset($this->decimals)) + if (isset($this->decimals)) { $out .= ' | decimals:'.$this->decimals; + } return $out; } @@ -47,61 +47,64 @@ public static function getTypeId($type) return CategoryInput::where('type', $type)->value('id'); } - public static function selectList() { - $list = []; + $list = []; + + foreach (CategoryInput::orderBy('name')->get() as $ci) { + $list[$ci->id] = $ci->name_plus(); + } - foreach(CategoryInput::orderBy('name')->get() as $ci) - $list[$ci->id] = $ci->name_plus(); - - return $list; + return $list; } public function render($val, $locale = null) { - if (!isset($val) || $val === null) + if (! isset($val) || $val === null) { return null; + } - if ($locale == null) + if ($locale == null) { $locale = LaravelLocalization::getCurrentLocale(); + } - $intVal = intval($val); + $intVal = intval($val); $type_array = __('taxonomy.'.$this->type); - switch($this->type) - { + switch ($this->type) { case 'select': case 'options': case 'list_item': $name = null; $cat = Category::find($intVal); - if ($cat) + if ($cat) { $name = $cat->transName($locale); + } - if ($name) + if ($name) { $val = $name; + } break; case 'list': $optionNames = []; - foreach(explode(',', $val) as $option) - { + foreach (explode(',', $val) as $option) { $name = null; $cat = Category::find($option); - if ($cat) + if ($cat) { $name = $cat->transName($locale); + } - if ($name) + if ($name) { array_push($optionNames, $name); + } } - $val = implode(',',$optionNames); + $val = implode(',', $optionNames); break; case 'date': - if (isset($val) && $val != null) - { + if (isset($val) && $val != null) { $time = strtotime($val); $val = date('Y-m-d H:i:s', $time); } @@ -112,74 +115,76 @@ public function render($val, $locale = null) case 'score_quality': case 'score_amount': case 'smileys_3': - if ($intVal > -1 && $intVal < count($type_array)) + if ($intVal > -1 && $intVal < count($type_array)) { $val = $type_array[$intVal]; + } break; case 'select_hive': $hive = Hive::find($intVal); - if ($hive) + if ($hive) { $val = $hive->name; + } break; case 'select_apiary': case 'select_location': $loc = Location::find($intVal); - if ($loc) + if ($loc) { $val = $loc->name; + } break; } + return $val; } public function glyphIcon() { - $icons = - [ - 'boolean' => 'ok-sign', + $icons = + [ + 'boolean' => 'ok-sign', 'boolean_yes_red' => 'remove-sign', - 'date' => 'calendar', - 'list' => 'list-alt', + 'date' => 'calendar', + 'list' => 'list-alt', 'list_item' => 'unchecked', - 'number' => 'stats', + 'number' => 'stats', 'number_0_decimals' => 'stats', 'number_1_decimals' => 'stats', 'number_2_decimals' => 'stats', 'number_3_decimals' => 'stats', - 'number_negative' => 'stats', + 'number_negative' => 'stats', 'number_percentage' => 'resize-horizontal', - 'number_positive' => 'stats', - 'options' => 'record', - 'text' => 'align-left', - 'barcode' => 'barcode', + 'number_positive' => 'stats', + 'options' => 'record', + 'text' => 'align-left', + 'barcode' => 'barcode', 'bee_subspecies' => 'queen', - 'color_picker' => 'eyedropper', - 'file' => 'save-file', - 'grade' => 'bookmark', - 'image' => 'picture', - 'label' => 'tag', - 'number_degrees' => 'view-360', - 'score' => 'star-empty', - 'score_amount' => 'star-empty', + 'color_picker' => 'eyedropper', + 'file' => 'save-file', + 'grade' => 'bookmark', + 'image' => 'picture', + 'label' => 'tag', + 'number_degrees' => 'view-360', + 'score' => 'star-empty', + 'score_amount' => 'star-empty', 'score_quality' => 'star-empty', - 'select' => 'collapse-down', - 'select_apiary'=> 'th', - 'select_continent'=> 'globe', - 'select_country'=> 'globe', - 'select_hive' => 'credit-card', + 'select' => 'collapse-down', + 'select_apiary' => 'th', + 'select_continent' => 'globe', + 'select_country' => 'globe', + 'select_hive' => 'credit-card', 'select_hive_layer' => 'credit-card', 'select_hive_layer_frame' => 'credit-card', - 'select_location'=> 'map-marker', - 'slider' => 'minus', + 'select_location' => 'map-marker', + 'slider' => 'minus', 'smileys_3' => 'star', - ]; + ]; - return isset($icons[$this->type]) ? $icons[$this->type] : 'alert'; + return isset($icons[$this->type]) ? $icons[$this->type] : 'alert'; } - } - diff --git a/app/Checklist.php b/app/Checklist.php index 2022894f..6fade093 100644 --- a/app/Checklist.php +++ b/app/Checklist.php @@ -2,49 +2,30 @@ namespace App; +use Auth; +use Illuminate\Database\Eloquent\Attributes\Appends; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Hidden; +use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\SoftDeletes; -use App\Category; -use App\Taxonomy; -use Auth; - use Illuminate\Support\Facades\DB; +#[Table('checklists', 'id')] +#[Fillable('name', 'type', 'description')] +#[Hidden('pivot', 'deleted_at', 'users')] +#[Appends('category_ids', 'required_ids', 'owner', 'researches')] class Checklist extends Model { use SoftDeletes; - /** - * The database table used by the model. - * - * @var string - */ - protected $table = 'checklists'; - - /** - * The database primary key value. - * - * @var string - */ - protected $primaryKey = 'id'; - - /** - * Attributes that should be mass-assignable. - * - * @var array - */ - protected $fillable = ['name', 'type', 'description']; - - protected $hidden = ['pivot','deleted_at', 'users']; - - protected $appends = ['category_ids', 'required_ids', 'owner', 'researches']; - // check for deletion of linked items - protected static function boot() { + protected static function boot() + { parent::boot(); - - static::deleting(function($item) - { + + static::deleting(function ($item) { DB::table('checklist_category')->where('checklist_id', $item->id)->delete(); DB::table('checklist_user')->where('checklist_id', $item->id)->delete(); DB::table('checklist_hive')->where('checklist_id', $item->id)->delete(); @@ -53,7 +34,7 @@ protected static function boot() { public function getCategoryIdsAttribute() { - return $this->categoryIdArray(); + return $this->categoryIdArray(); } public function getRequiredIdsAttribute() @@ -63,17 +44,15 @@ public function getRequiredIdsAttribute() public function getOwnerAttribute() { - return $this->users->contains(Auth::user()); + return $this->users->contains(Auth::user()); } public function getResearchesAttribute() { - return $this->researches()->pluck('name'); + return $this->researches()->pluck('name'); } - - - public function categories() + public function categories(): BelongsToMany { return $this->belongsToMany(Category::class, 'checklist_category')->withPivot('order')->orderBy('order'); } @@ -83,62 +62,62 @@ public function categoryIdArray() return $this->categories()->pluck('id')->toArray(); } - public function users() + public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'checklist_user'); } - public function hives() + public function hives(): BelongsToMany { return $this->belongsToMany(Hive::class, 'checklist_hive'); } - public function researches() + public function researches(): BelongsToMany { return $this->belongsToMany(Research::class, 'checklist_research'); } - - public function getOrderedChecklist($selectedCatIds=[], $includeNotSelected=true) + + public function getOrderedChecklist($selectedCatIds = [], $includeNotSelected = true) { $taxonomyRootIds = Taxonomy::getRootIds(); - $cheklistRootIds = array_intersect($selectedCatIds, $taxonomyRootIds); // order root nodes by defined order in checklist - if ($includeNotSelected) - $cheklistRootIds = array_merge($cheklistRootIds, array_diff($taxonomyRootIds, $cheklistRootIds)); // add rest of (not selected categories) + $cheklistRootIds = array_intersect($selectedCatIds, $taxonomyRootIds); // order root nodes by defined order in checklist + if ($includeNotSelected) { + $cheklistRootIds = array_merge($cheklistRootIds, array_diff($taxonomyRootIds, $cheklistRootIds)); + } // add rest of (not selected categories) $taxonomy = Taxonomy::getTaxonomy($cheklistRootIds, $selectedCatIds); + return $taxonomy; } public function syncCategories($categories) { - if (isset($categories) && count($categories) > 0) - { + if (isset($categories) && count($categories) > 0) { $cat_with_order = array_flip($categories); - foreach ($cat_with_order as $cat_id => $value) - { - $parents = Taxonomy::ancestorsOf($cat_id)->whereNotIn('type',['system'])->pluck('id')->toArray(); - if (count($parents) > 0) - { - foreach ($parents as $p) - { - if (in_array($p, $categories) == false) - $cat_with_order[$p] = ['order'=>$value]; + foreach ($cat_with_order as $cat_id => $value) { + $parents = Taxonomy::ancestorsOf($cat_id)->whereNotIn('type', ['system'])->pluck('id')->toArray(); + if (count($parents) > 0) { + foreach ($parents as $p) { + if (in_array($p, $categories) == false) { + $cat_with_order[$p] = ['order' => $value]; + } } } - $cat_with_order[$cat_id] = ['order'=>$value]; + $cat_with_order[$cat_id] = ['order' => $value]; } - if (count($categories) > 0) - { + if (count($categories) > 0) { $this->categories()->sync($cat_with_order); $this->touch(); // set Checklist updated_at + return true; } } + return false; } public static function selectList() { - return Checklist::orderBy('name')->pluck('name','id'); + return Checklist::orderBy('name')->pluck('name', 'id'); } } diff --git a/app/ChecklistFactory.php b/app/ChecklistFactory.php index ab4808a2..da59f035 100644 --- a/app/ChecklistFactory.php +++ b/app/ChecklistFactory.php @@ -2,239 +2,224 @@ namespace App; -use App\Checklist; -use App\Category; -use App\CategoryFactory; -use App\User; -use App\Inspection; -use App\InspectionItem; - -class ChecklistFactory +class ChecklistFactory { - public function __construct() { - $this->categoryFactory = new CategoryFactory; - $this->std_checklist_type = 'beep_v2'; - $this->std_checklist_name = 'Beep v2'; - $this->old_inspection_items = ['notes'=>27, 'attention'=>26, 'impression'=>25, 'reminder'=>8, 'reminder_date'=>9]; - $this->old_inspection_texts = ['Varroatelling: '=>37, 'Resterende moerdoppen: '=>17]; + $this->categoryFactory = new CategoryFactory; + $this->std_checklist_type = 'beep_v2'; + $this->std_checklist_name = 'Beep v2'; + $this->old_inspection_items = ['notes' => 27, 'attention' => 26, 'impression' => 25, 'reminder' => 8, 'reminder_date' => 9]; + $this->old_inspection_texts = ['Varroatelling: ' => 37, 'Resterende moerdoppen: ' => 17]; $this->old_list_category_ids = [6, 32, 35]; // lists } - // Convert category_id's and tables from old database (v1: seeded categories) to new (v2: dynamic taxonomy categories) - public function convertUsersChecklists($users, $debug=false) + public function convertUsersChecklists($users, $debug = false) { // remove already existing copies of checklists Checklist::where('type', 'like', '%_copy%')->forceDelete(); // perform magic - $count = ['locations'=>0, 'inspections'=>0, 'conditions'=>0, 'actions'=>0, 'hives'=>0, 'hive_layers'=>0, 'hive_layer_frames'=>0, 'queens'=>0, 'sensors'=>0]; + $count = ['locations' => 0, 'inspections' => 0, 'conditions' => 0, 'actions' => 0, 'hives' => 0, 'hive_layers' => 0, 'hive_layer_frames' => 0, 'queens' => 0, 'sensors' => 0]; - $this->non_system_categories = Category::where('old_id','!=',null)->get();//getTaxonomy(null, false, true); - print_r(['non_system_categories'=>$this->non_system_categories->pluck('old_id','id')->toArray()]); + $this->non_system_categories = Category::where('old_id', '!=', null)->get(); // getTaxonomy(null, false, true); + print_r(['non_system_categories' => $this->non_system_categories->pluck('old_id', 'id')->toArray()]); - $stdChecklist = $this->getStandardChecklist(); - $fallBackOfFallBacks = Category::where('name','not_assigned_in_migration')->value('id',938); // id=938 - $fallback_loc_type_id = $fallBackOfFallBacks; + $stdChecklist = $this->getStandardChecklist(); + $fallBackOfFallBacks = Category::where('name', 'not_assigned_in_migration')->value('id', 938); // id=938 + $fallback_loc_type_id = $fallBackOfFallBacks; $fallback_hive_type_id = $fallBackOfFallBacks; - $fallback_bee_race_id = $fallBackOfFallBacks; - $fallback_hive_layer_id= $fallBackOfFallBacks; - $fallback_hive_frame_id= $fallBackOfFallBacks; - $fallback_sensor_id = $fallBackOfFallBacks; - - $loc_type_cats = Category::descendentsByRootParentAndName('apiary', 'apiary', 'type'); - $hive_type_cats = Category::descendentsByRootParentAndName('hive', 'hive', 'type'); - $bee_race_cats = Category::descendentsByRootParentAndName('bee_colony', 'characteristics', 'subspecies'); + $fallback_bee_race_id = $fallBackOfFallBacks; + $fallback_hive_layer_id = $fallBackOfFallBacks; + $fallback_hive_frame_id = $fallBackOfFallBacks; + $fallback_sensor_id = $fallBackOfFallBacks; + + $loc_type_cats = Category::descendentsByRootParentAndName('apiary', 'apiary', 'type'); + $hive_type_cats = Category::descendentsByRootParentAndName('hive', 'hive', 'type'); + $bee_race_cats = Category::descendentsByRootParentAndName('bee_colony', 'characteristics', 'subspecies'); $hive_layer_cats = Category::descendentsByRootParentAndName('hive', 'app', 'hive_layer'); $hive_frame_cats = Category::descendentsByRootParentAndName('hive', 'app', 'hive_frame'); - $hive_sensor_cats= Category::descendentsByRootParentAndName('hive', 'app', 'sensor'); - - if ($loc_type_cats->where('name','fixed')->count() > 0) - $fallback_loc_type_id = $loc_type_cats->where('name','fixed')->pluck('id')[0]; + $hive_sensor_cats = Category::descendentsByRootParentAndName('hive', 'app', 'sensor'); - if ($hive_type_cats->where('name','custom')->count() > 0) - $fallback_hive_type_id = $hive_type_cats->where('name','custom')->pluck('id')[0]; + if ($loc_type_cats->where('name', 'fixed')->count() > 0) { + $fallback_loc_type_id = $loc_type_cats->where('name', 'fixed')->pluck('id')[0]; + } - if ($bee_race_cats->where('name','other')->count() > 0) - $fallback_bee_race_id = $bee_race_cats->where('name','other')->pluck('id')[0]; + if ($hive_type_cats->where('name', 'custom')->count() > 0) { + $fallback_hive_type_id = $hive_type_cats->where('name', 'custom')->pluck('id')[0]; + } - if ($hive_layer_cats->where('name','brood')->count() > 0) - $fallback_hive_layer_id = $hive_layer_cats->where('name','brood')->pluck('id')[0]; + if ($bee_race_cats->where('name', 'other')->count() > 0) { + $fallback_bee_race_id = $bee_race_cats->where('name', 'other')->pluck('id')[0]; + } - if ($hive_frame_cats->where('name','wax')->count() > 0) - $fallback_hive_frame_id = $hive_frame_cats->where('name','wax')->pluck('id')[0]; + if ($hive_layer_cats->where('name', 'brood')->count() > 0) { + $fallback_hive_layer_id = $hive_layer_cats->where('name', 'brood')->pluck('id')[0]; + } - if ($hive_sensor_cats->where('name','other')->count() > 0) - $fallback_sensor_id = $hive_sensor_cats->where('name','other')->pluck('id')[0]; + if ($hive_frame_cats->where('name', 'wax')->count() > 0) { + $fallback_hive_frame_id = $hive_frame_cats->where('name', 'wax')->pluck('id')[0]; + } - print_r(['new_cat_ids'=> ['loc'=>$loc_type_cats->pluck('name','id')->toArray(), 'hive'=>$hive_type_cats->pluck('name','id')->toArray(), 'bee'=>$bee_race_cats->pluck('name','id')->toArray(), 'layer'=>$hive_layer_cats->pluck('name','id')->toArray(), 'frame'=>$hive_frame_cats->pluck('name','id')->toArray(), 'sensor'=>$hive_sensor_cats->pluck('name','id')->toArray()]]); - print_r(['fallback_ids'=>['loc'=>$fallback_loc_type_id, 'hive'=>$fallback_hive_type_id, 'bee'=>$fallback_bee_race_id, 'layer'=>$fallback_hive_layer_id, 'frame'=>$fallback_hive_frame_id, 'sensor'=>$fallback_sensor_id]]); + if ($hive_sensor_cats->where('name', 'other')->count() > 0) { + $fallback_sensor_id = $hive_sensor_cats->where('name', 'other')->pluck('id')[0]; + } + + print_r(['new_cat_ids' => ['loc' => $loc_type_cats->pluck('name', 'id')->toArray(), 'hive' => $hive_type_cats->pluck('name', 'id')->toArray(), 'bee' => $bee_race_cats->pluck('name', 'id')->toArray(), 'layer' => $hive_layer_cats->pluck('name', 'id')->toArray(), 'frame' => $hive_frame_cats->pluck('name', 'id')->toArray(), 'sensor' => $hive_sensor_cats->pluck('name', 'id')->toArray()]]); + print_r(['fallback_ids' => ['loc' => $fallback_loc_type_id, 'hive' => $fallback_hive_type_id, 'bee' => $fallback_bee_race_id, 'layer' => $fallback_hive_layer_id, 'frame' => $fallback_hive_frame_id, 'sensor' => $fallback_sensor_id]]); - foreach ($users as $user) - { + foreach ($users as $user) { // create or get checklist - if ($debug == false || $user->checklists()->count() == 0) + if ($debug == false || $user->checklists()->count() == 0) { $this->createUserChecklist($user, $stdChecklist); + } // 'location' =>['fixed','movable','temporary','other'], (65,66,67,68) - foreach ($user->locations as $location) + foreach ($user->locations as $location) { $count['locations'] += $this->changeCategoryIdToNew($loc_type_cats, $location, 'category_id', $fallback_loc_type_id); + } // 'sensor' =>['beep','hiveeyes','arnia','manual','other'] - foreach ($user->sensors as $sensor) + foreach ($user->sensors as $sensor) { $count['sensors'] += $this->changeCategoryIdToNew($hive_sensor_cats, $sensor, 'category_id', $fallback_sensor_id); - + } // Change hives/inspections - foreach ($user->hives()->withTrashed()->get() as $hive) - { - $count['hives'] += $this->changeCategoryIdToNew($hive_type_cats, $hive, 'hive_type_id', $fallback_hive_type_id); - if($hive->queen()->count() > 0) + foreach ($user->hives()->withTrashed()->get() as $hive) { + $count['hives'] += $this->changeCategoryIdToNew($hive_type_cats, $hive, 'hive_type_id', $fallback_hive_type_id); + if ($hive->queen()->count() > 0) { $count['queens'] += $this->changeCategoryIdToNew($bee_race_cats, $hive->queen, 'race_id', $fallback_bee_race_id); + } // Transfer hive_layers, hive_layer_frame category_id's to taxonomy // hive_layer.category_id, hive_layer_frame.category_id // 'hive_layer'=>['brood','honey','grid','empty'], (56,57,58,59) // 'hive_frame'=>['wax','block','other'], (61,62,63) - foreach ($hive->layers()->withTrashed()->get() as $hive_layer) - { + foreach ($hive->layers()->withTrashed()->get() as $hive_layer) { $count['hive_layers'] += $this->changeCategoryIdToNew($hive_layer_cats, $hive_layer, 'category_id', $fallback_hive_layer_id); - foreach ($hive_layer->frames()->withTrashed()->get() as $layer_frame) + foreach ($hive_layer->frames()->withTrashed()->get() as $layer_frame) { $count['hive_layer_frames'] += $this->changeCategoryIdToNew($hive_frame_cats, $layer_frame, 'category_id', $fallback_hive_frame_id); + } } - //die(print_r($hive->actions()->pluck('created_at')->toArray())); - //die(print_r(['user'=>$user->name, 'count'=>$count])); + // die(print_r($hive->actions()->pluck('created_at')->toArray())); + // die(print_r(['user'=>$user->name, 'count'=>$count])); } - print_r(['id'=>$user->id, 'user'=>$user->name, 'count'=>$count]); + print_r(['id' => $user->id, 'user' => $user->name, 'count' => $count]); } - print_r(['total_count'=>$count]); + print_r(['total_count' => $count]); - if ($debug) - die('End of debug output'); + if ($debug) { + exit('End of debug output'); + } } public function createUserChecklist($user, $checklist) { - $hasNewChecklist = $user->checklists()->where('type',$checklist->type.'_copy')->count() > 0 ? true : false; - - if ($hasNewChecklist == false) - { - $new = ['type'=>$checklist->type.'_copy', 'name'=>$checklist->name.' - '.$user->name]; + $hasNewChecklist = $user->checklists()->where('type', $checklist->type.'_copy')->count() > 0 ? true : false; + + if ($hasNewChecklist == false) { + $new = ['type' => $checklist->type.'_copy', 'name' => $checklist->name.' - '.$user->name]; $chk = $user->checklists()->create($new); $chk->syncCategories($checklist->category_ids); } } - public function getStandardChecklist() { - $query = Checklist::where('type', $this->std_checklist_type)->orderBy('id', 'desc'); - $check_model = [ 'name' => $this->std_checklist_name, 'type' => $this->std_checklist_type, 'description' => 'Beep v1 kastkaart / hive checklist']; - $check = null; + $query = Checklist::where('type', $this->std_checklist_type)->orderBy('id', 'desc'); + $check_model = ['name' => $this->std_checklist_name, 'type' => $this->std_checklist_type, 'description' => 'Beep v1 kastkaart / hive checklist']; + $check = null; - if ($query->count() == 0) - { + if ($query->count() == 0) { $check = new Checklist($check_model); $check->save(); // create standard checklist $checklist_ids = $this->categoryFactory->get_old_ids_array(); - //die(print_r($checklist_ids)); + // die(print_r($checklist_ids)); $check->categories()->sync($checklist_ids); - } - else - { + } else { $check = $query->first(); } - //print_r(['getStandardChecklist'=>$check->toArray()]); - + // print_r(['getStandardChecklist'=>$check->toArray()]); + return $check; } // $a => action/condition: {'hive_id', 'category_id', 'text', 'number', 'score', 'boolean', 'date'} private function createInspectionItem($a, $ins, $debug) { - $cat_id = null; - $cat_type = null; - $ins_i = null; - $ins_id = $ins->id; - $old_id = $a->category_id; - $found = $this->non_system_categories->where('old_id',$old_id)->where('type', '!=', 'system')->count(); + $cat_id = null; + $cat_type = null; + $ins_i = null; + $ins_id = $ins->id; + $old_id = $a->category_id; + $found = $this->non_system_categories->where('old_id', $old_id)->where('type', '!=', 'system')->count(); $is_core_item = array_search($old_id, $this->old_inspection_items); - - if ($is_core_item !== false) - { - if ($debug) - echo("INS $ins->id: Found inspection core item $is_core_item \r\n"); - } - else if ($found == 0) - { - //print_r($this->non_system_categories->sortBy('old_id')->pluck('old_id','name')->toArray()); - echo("INS $ins->id: $old_id not found in ".$this->non_system_categories->count()." non_system_categories\r\n"); - //print_r($a->toArray()); - //die(print_r($this->non_system_categories->toArray())); + + if ($is_core_item !== false) { + if ($debug) { + echo "INS $ins->id: Found inspection core item $is_core_item \r\n"; + } + } elseif ($found == 0) { + // print_r($this->non_system_categories->sortBy('old_id')->pluck('old_id','name')->toArray()); + echo "INS $ins->id: $old_id not found in ".$this->non_system_categories->count()." non_system_categories\r\n"; + + // print_r($a->toArray()); + // die(print_r($this->non_system_categories->toArray())); return 0; - } - else if ($found == 1) - { - $cat = $this->non_system_categories->where('old_id',$old_id)->first(); - $cat_id = $cat->id; - $cat_type = $cat->input; - if ($debug) - echo("INS $ins->id: Found 1 cat with $old_id: $cat_id\r\n"); - } - else if ($found > 1) // boolean + value item - { - if ($debug) - echo("INS $ins->id: Found $found cat with $old_id \r\n"); - - foreach ($this->non_system_categories->where('old_id',$old_id) as $cat) - { - if ($cat->isSystem() == false) - { + } elseif ($found == 1) { + $cat = $this->non_system_categories->where('old_id', $old_id)->first(); + $cat_id = $cat->id; + $cat_type = $cat->input; + if ($debug) { + echo "INS $ins->id: Found 1 cat with $old_id: $cat_id\r\n"; + } + } elseif ($found > 1) { // boolean + value item + if ($debug) { + echo "INS $ins->id: Found $found cat with $old_id \r\n"; + } + + foreach ($this->non_system_categories->where('old_id', $old_id) as $cat) { + if ($cat->isSystem() == false) { $cat_type = $cat->input; - if($cat_type == 'boolean' || $cat_type == 'boolean_yes_red') - { - $data = ['value'=>'1', 'inspection_id'=>$ins_id, 'category_id'=>$cat->id]; + if ($cat_type == 'boolean' || $cat_type == 'boolean_yes_red') { + $data = ['value' => '1', 'inspection_id' => $ins_id, 'category_id' => $cat->id]; $ins_i = InspectionItem::create($data); - if ($debug) - echo("INS $ins->id: $cat_type created cat $cat->id\r\n"); - } - else - { + if ($debug) { + echo "INS $ins->id: $cat_type created cat $cat->id\r\n"; + } + } else { $cat_id = $cat->id; } } } } - - $value = null; + $value = null; - - if (isset($a) && gettype($a) == 'object') - { - if ($a->text !== null) + if (isset($a) && gettype($a) == 'object') { + if ($a->text !== null) { $value = substr($a->text, 0, 1024); - else if ($a->number !== null) + } elseif ($a->number !== null) { $value = "$a->number"; - else if($a->score !== null) + } elseif ($a->score !== null) { $value = "$a->score"; - else if($a->boolean !== null) + } elseif ($a->boolean !== null) { $value = "$a->boolean"; - else if($a->date !== null) + } elseif ($a->date !== null) { $value = "$a->date"; + } } - if ($value === null || $value === 'null' || $value === '') - { - if ($debug == false) + if ($value === null || $value === 'null' || $value === '') { + if ($debug == false) { $a->delete(); + } return 0; } @@ -244,33 +229,26 @@ private function createInspectionItem($a, $ins, $debug) // Items that have to be processed before new InspectionItem creation // Save core item, or gather list items - if ($is_core_item !== false) - { + if ($is_core_item !== false) { $ins->$is_core_item = $value; $ins->save(); $value = null; // don't create an inspection item, because a core item is already created $ins_i = true; // delete former item - } - else if (in_array($old_id, $this->old_list_category_ids)) // boolean list - { - $values = explode(',',$value); - //print_r(["old_ids options (list=$old_id)"=>$values]); - $cat_ids= []; - foreach ($values as $val) - { - $cat_opt = $this->non_system_categories->where('old_id',$val)->first(); // check if there is a list option with the name (or id) of the old_id - if ($cat_opt) - { + } elseif (in_array($old_id, $this->old_list_category_ids)) { // boolean list + $values = explode(',', $value); + // print_r(["old_ids options (list=$old_id)"=>$values]); + $cat_ids = []; + foreach ($values as $val) { + $cat_opt = $this->non_system_categories->where('old_id', $val)->first(); // check if there is a list option with the name (or id) of the old_id + if ($cat_opt) { $cat_opt_id = $cat_opt->id; - if ($cat_opt->input == 'boolean' || $cat_opt->input == 'boolean_yes_red') - { - $data = ['value'=>'1', 'inspection_id'=>$ins_id, 'category_id'=>$cat_opt_id]; + if ($cat_opt->input == 'boolean' || $cat_opt->input == 'boolean_yes_red') { + $data = ['value' => '1', 'inspection_id' => $ins_id, 'category_id' => $cat_opt_id]; $ins_i = InspectionItem::create($data); - if ($debug) - echo("INS $ins->id: boolean_list_item_created cat $cat_opt_id from old_id $val\r\n"); - } - else if ($cat_opt_id) // list items - { + if ($debug) { + echo "INS $ins->id: boolean_list_item_created cat $cat_opt_id from old_id $val\r\n"; + } + } elseif ($cat_opt_id) { // list items array_push($cat_ids, $cat_opt_id); } } @@ -278,28 +256,24 @@ private function createInspectionItem($a, $ins, $debug) } $value = implode(',', $cat_ids); } - + // Save to new inspection item - if ($value !== null && $value !== '' && $cat_id !== null) - { - if ($cat_type == 'text') - { + if ($value !== null && $value !== '' && $cat_id !== null) { + if ($cat_type == 'text') { $preFixText = array_search($old_id, $this->old_inspection_texts); - if ($preFixText !== false) - { - $value = $preFixText.$value; - } - else if ($debug) - { - echo("INS $ins->id: No prefix Text item for old_id=$old_id ".Category::where('id',$cat_id)->first()->ancName()."\r\n"); + if ($preFixText !== false) { + $value = $preFixText.$value; + } elseif ($debug) { + echo "INS $ins->id: No prefix Text item for old_id=$old_id ".Category::where('id', $cat_id)->first()->ancName()."\r\n"; } } - - $data = ['value'=>"$value", 'inspection_id'=>$ins_id, 'category_id'=>$cat_id]; + + $data = ['value' => "$value", 'inspection_id' => $ins_id, 'category_id' => $cat_id]; $ins_i = InspectionItem::create($data); - if ($debug && $ins_i) - echo("INS $ins->id: InspectionItem created type: $cat_type, cat: $cat_id, value: $value\r\n"); + if ($debug && $ins_i) { + echo "INS $ins->id: InspectionItem created type: $cat_type, cat: $cat_id, value: $value\r\n"; + } // if ($debug) // { @@ -307,46 +281,42 @@ private function createInspectionItem($a, $ins, $debug) // print_r(['cat_id'=>$cat_id, 'ins_i'=>$ins_i]); // } } - - if ($ins_i) - { - if ($debug == false) + + if ($ins_i) { + if ($debug == false) { $a->delete(); + } return 1; } + return 0; } - private function changeCategoryIdToNew($categories, $item, $cat_field='category_id', $fallback_cat_id=null) + private function changeCategoryIdToNew($categories, $item, $cat_field = 'category_id', $fallback_cat_id = null) { - if (gettype($item) == 'object') - { + if (gettype($item) == 'object') { $new_cat_id = null; - $new_cat = $categories->where('old_id', $item->$cat_field); + $new_cat = $categories->where('old_id', $item->$cat_field); - if ($new_cat->count() > 0) - { + if ($new_cat->count() > 0) { $new_cat_id = $new_cat->pluck('id')[0]; - } - else - { - if ($categories->where('id', $item->$cat_field)->count() == 0) // if new category id is already assigned, ignore + } else { + if ($categories->where('id', $item->$cat_field)->count() == 0) { // if new category id is already assigned, ignore $new_cat_id = $fallback_cat_id; + } } - //print_r(['item'=>$item->name, "$cat_field"=>$item->$cat_field, 'new_cat_id'=>$new_cat_id, 'fallback_cat_id'=>$fallback_cat_id]); + // print_r(['item'=>$item->name, "$cat_field"=>$item->$cat_field, 'new_cat_id'=>$new_cat_id, 'fallback_cat_id'=>$fallback_cat_id]); - if ($new_cat_id && $item->$cat_field != $new_cat_id) - { + if ($new_cat_id && $new_cat_id != $item->$cat_field) { $item->$cat_field = $new_cat_id; + return $item->save(); } + } else { + print_r(['changeCategoryIdToNew unknown item' => $item]); } - else - { - print_r(['changeCategoryIdToNew unknown item'=>$item]); - } + return 0; } - } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php deleted file mode 100644 index 03c5140d..00000000 --- a/app/Console/Kernel.php +++ /dev/null @@ -1,64 +0,0 @@ -call( - function () - { - Weather::updateLocations(); - } - )->everyFiveMinutes(); - - $schedule->call( - function () - { - AlertRule::parseRules(); - } - )->everyMinute(); - - $schedule->call( - function () - { - FlashLog::parseUnparsedFlashlogs(); - } - )->everyFiveMinutes(); - } - - /** - * Register the Closure based commands for the application. - * - * @return void - */ - protected function commands() - { - $this->load(__DIR__.'/Commands'); - - require base_path('routes/console.php'); - } -} diff --git a/app/Continent.php b/app/Continent.php index 27dc6bbd..1174d8b4 100644 --- a/app/Continent.php +++ b/app/Continent.php @@ -2,11 +2,10 @@ namespace App; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Guarded; use Illuminate\Database\Eloquent\Model; -class Continent extends Model -{ - protected $fillable = ['name', 'abbr']; - protected $guarded = ['id']; - -} +#[Fillable('name', 'abbr')] +#[Guarded('id')] +class Continent extends Model {} diff --git a/app/Device.php b/app/Device.php index b76fd004..740c6499 100644 --- a/app/Device.php +++ b/app/Device.php @@ -2,109 +2,120 @@ namespace App; -use Iatstuti\Database\Support\CascadeSoftDeletes; +use App\Models\Alert; +use App\Models\FlashLog; +use Auth; +use Cache; +use DB; +use Dyrynda\Database\Support\CascadeSoftDeletes; +use Illuminate\Database\Eloquent\Attributes\Appends; +use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Guarded; +use Illuminate\Database\Eloquent\Attributes\Hidden; +use Illuminate\Database\Eloquent\Attributes\Table; +use Illuminate\Database\Eloquent\Attributes\WithoutTimestamps; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Log; -use DB; -use Cache; -use Auth; use InfluxDB; -use App\Models\Alert; -use App\Models\FlashLog; use Moment\Moment; +#[Table('sensors')] +#[WithoutTimestamps] +#[Fillable('user_id', 'hive_id', 'category_id', 'name', 'key', 'last_message_received', 'hardware_id', 'firmware_version', 'hardware_version', 'boot_count', 'measurement_interval_min', 'measurement_transmission_ratio', 'ble_pin', 'battery_voltage', 'next_downlink_message', 'last_downlink_result', 'datetime', 'datetime_offset_sec', 'former_key_list', 'rtc', 'log_file_info')] +#[Guarded('id')] +#[Hidden('user_id', 'category_id', 'deleted_at', 'hive', 'former_key_list')] +#[Appends('type', 'hive_name', 'location_name', 'owner', 'online')] class Device extends Model { - use SoftDeletes, CascadeSoftDeletes; + use CascadeSoftDeletes, SoftDeletes; - protected $table = 'sensors'; protected $cascadeDeletes = ['sensorDefinitions']; - protected $fillable = ['user_id', 'hive_id', 'category_id', 'name', 'key', 'last_message_received', 'hardware_id', 'firmware_version', 'hardware_version', 'boot_count', 'measurement_interval_min', 'measurement_transmission_ratio', 'ble_pin', 'battery_voltage', 'next_downlink_message', 'last_downlink_result', 'datetime', 'datetime_offset_sec', 'former_key_list', 'rtc', 'log_file_info']; - protected $guarded = ['id']; - protected $hidden = ['user_id', 'category_id', 'deleted_at', 'hive', 'former_key_list']; - protected $appends = ['type','hive_name', 'location_name', 'owner', 'online']; - protected $casts = ['log_file_info'=>'array']; - - public $timestamps = false; public static function boot() { parent::boot(); static::created(function ($d) { - //Log::info("Created Device $d->id $d->name"); + // Log::info("Created Device $d->id $d->name"); $d->empty_cache(); }); static::updated(function ($d) { $empty_cache = false; - if ($d->wasChanged('deleted_at')) - { + if ($d->wasChanged('deleted_at')) { Log::info("Updated Device id=$d->id deleted_at to $d->deleted_at"); $empty_cache = true; } - if ($d->wasChanged('user_id')) - { + if ($d->wasChanged('user_id')) { Log::info("Updated Device id=$d->id user_id to $d->user_id"); $empty_cache = true; } - if ($d->wasChanged('firmware_version')) - { + if ($d->wasChanged('firmware_version')) { Log::info("Updated Device id=$d->id firmware_version to $d->firmware_version"); $empty_cache = true; } - if ($d->wasChanged('hive_id')) - { + if ($d->wasChanged('hive_id')) { Log::info("Updated Device id=$d->id hive_id to $d->hive_id"); $empty_cache = true; } - if ($d->wasChanged('key')) - { + if ($d->wasChanged('key')) { Log::info("Updated Device id=$d->id key to $d->key"); $empty_cache = true; } - if ($d->wasChanged('name')) - { + if ($d->wasChanged('name')) { Log::info("Updated Device id=$d->id name to $d->name"); $empty_cache = true; } - if ($empty_cache) + if ($empty_cache) { $d->empty_cache(); + } }); static::deleted(function ($d) { - //Log::info("Deleted Device $d->id $d->name"); + // Log::info("Deleted Device $d->id $d->name"); $d->empty_cache(); }); } - public function empty_cache($clear_users=true) + protected function casts(): array + { + return [ + 'log_file_info' => 'array', + ]; + } + + public function empty_cache($clear_users = true) { Cache::forget('device-'.$this->id.'-hive-'.$this->hive_id.'-user-ids'); Cache::forget('device-'.$this->id.'-hive-'.$this->hive_id.'-rule-ids'); Cache::forget('device-'.$this->id.'-calibrations-measurement-types'); - + Cache::forget('device-'.$this->id.'-calibrations-measurement-types-0'); + Cache::forget('device-'.$this->id.'-calibrations-measurement-types-1'); + Log::debug("Device ID $this->id cache emptied"); - if ($clear_users) + if ($clear_users) { User::emptyIdCache($this->user_id, 'device'); + } } - - public static function cacheRequestRate($name, $retention_sec=86400) + public static function cacheRequestRate($name, $retention_sec = 86400) { - Cache::remember($name.'-time', $retention_sec, function () use ($name) - { + Cache::remember($name.'-time', $retention_sec, function () use ($name) { Cache::forget($name.'-count'); + return time(); }); - if (Cache::has($name.'-count')) + if (Cache::has($name.'-count')) { Cache::increment($name.'-count'); - else + } else { Cache::put($name.'-count', 1); + } } @@ -116,59 +127,66 @@ public function getTypeAttribute() public function getHiveNameAttribute() { - if (isset($this->hive)) + if (isset($this->hive)) { return $this->hive->name; + } return ''; } public function getLocationIdAttribute() { - if (isset($this->hive)) + if (isset($this->hive)) { return $this->hive->location_id; + } return null; } public function getLocationNameAttribute() { - if (isset($this->hive)) + if (isset($this->hive)) { return $this->hive->getLocationAttribute(); + } return ''; } public function getOwnerAttribute() { - if (Auth::check() && $this->user_id == Auth::user()->id) + if (Auth::check() && $this->user_id == Auth::user()->id) { return true; + } return false; } public function getOnlineAttribute() { - $refresh_min = max(15, $this->getRefreshMin() * 2); - $min_msg_date = date('Y-m-d H:i:s', time()-(60*$refresh_min)); // at least - if (isset($this->last_message_received) && $this->last_message_received > $min_msg_date) + $refresh_min = max(15, $this->getRefreshMin() * 2); + $min_msg_date = date('Y-m-d H:i:s', time() - (60 * $refresh_min)); // at least + if (isset($this->last_message_received) && $this->last_message_received > $min_msg_date) { return true; + } return false; } public function checkLogOutdated() { - if (isset($this->log_file_info['created_date'])) - return ($this->flashlogs()->where('updated_at' , '>', $this->log_file_info['created_date'])->count() > 0); - + if (isset($this->log_file_info['created_date'])) { + return $this->flashlogs()->where('updated_at', '>', $this->log_file_info['created_date'])->count() > 0; + } + return false; } public function researchNames() { $res = $this->researches(); - if ($res->count() > 0) + if ($res->count() > 0) { return implode(', ', $res->pluck('name')->toArray()); + } return ''; } @@ -178,27 +196,28 @@ public function allKeys() { $keys = [$this->key]; - if (isset($this->former_key_list)) - { + if (isset($this->former_key_list)) { $keys = array_merge($keys, explode(',', $this->former_key_list)); } // add upper or lowercase key $add_keys = []; - foreach ($keys as $key) - { + foreach ($keys as $key) { $key_low = strtolower($key); $key_upp = strtoupper($key); - if ($key_low !== $key) + if ($key_low !== $key) { $add_keys[] = $key_low; + } - if ($key_upp !== $key) + if ($key_upp !== $key) { $add_keys[] = $key_upp; + } } - if (count($add_keys) > 0) + if (count($add_keys) > 0) { $keys = array_merge($keys, $add_keys); + } - //die(print_r($where_keys)); + // die(print_r($where_keys)); return $keys; } @@ -207,33 +226,37 @@ public function influxWhereKeys() $keys = $this->allKeys(); $where_keys = '("key" = \''.implode('\' OR "key" = \'', $keys).'\')'; - //die(print_r($where_keys)); + + // die(print_r($where_keys)); return $where_keys; } public function addFormerKey($key) { - if (!isset($key) || $key == '' || $key == null) + if (! isset($key) || $key == '' || $key == null) { return false; + } $keys = []; - if (isset($this->former_key_list)) + if (isset($this->former_key_list)) { $keys = explode(',', $this->former_key_list); + } - if (in_array($key, $keys) === false) + if (in_array($key, $keys) === false) { $keys[] = $key; + } - if (count($keys) > 0) - { + if (count($keys) > 0) { $this->former_key_list = implode(',', $keys); $this->save(); + return true; } + return false; } - - public function sensorDefinitions() + public function sensorDefinitions(): HasMany { return $this->hasMany(SensorDefinition::class); } @@ -253,54 +276,58 @@ public function activeTypeDateSensorDefinitions($input_measurement_id, $output_m $io_sds = $this->sensorDefinitions()->where('input_measurement_id', $input_measurement_id)->where('output_measurement_id', $output_measurement_id)->get(); // If empty collection, or only one, return sensor_defs collection for all data - if ($io_sds->count() < 2) + if ($io_sds->count() < 2) { return $io_sds; + } // If more than 1, chech which one to use $sd_during = $io_sds->whereBetween('updated_at', [$start, $end])->sortByDesc('updated_at')->unique('input_measurement_id', 'output_measurement_id'); - if ($sd_during->count() > 0) - { - foreach($sd_during as $sd) + if ($sd_during->count() > 0) { + foreach ($sd_during as $sd) { $sd_ids[] = $sd->id; + } } // Add first before or at start $sd_before = $io_sds->where('updated_at', '<=', $start)->sortByDesc('updated_at')->first(); - if ($sd_before) + if ($sd_before) { $sd_ids[] = $sd_before->id; + } // If none, add first after end - if (count($sd_ids) == 0) - { + if (count($sd_ids) == 0) { $sd_next = $io_sds->where('updated_at', '>=', $end)->sortBy('updated_at')->first(); - if ($sd_next) + if ($sd_next) { $sd_ids[] = $sd_next->id; + } } // If none, add the only calibration - if (count($sd_ids) == 0&& $io_sds->count() == 1) + if (count($sd_ids) == 0 && $io_sds->count() == 1) { $sd_ids[] = $io_sds->first()->id; + } return $this->sensorDefinitions()->whereIn('id', $sd_ids)->orderBy('updated_at', 'desc')->get(); } - public function hive() + public function hive(): BelongsTo { return $this->belongsTo(Hive::class); } public function location() { - if (isset($this->hive)) + if (isset($this->hive)) { return $this->hive->location()->first(); + } return null; } - public function user() + public function user(): BelongsTo { return $this->belongsTo(User::class); } @@ -310,12 +337,12 @@ public function researches() return $this->user->researches(); } - public function alerts() + public function alerts(): HasMany { return $this->hasMany(Alert::class); } - public function flashLogs() + public function flashLogs(): HasMany { return $this->hasMany(FlashLog::class); } @@ -323,33 +350,34 @@ public function flashLogs() public function getMeasurementsPerDay() { $device_interval_min = isset($this->measurement_interval_min) && $this->measurement_interval_min > 0 ? $this->measurement_interval_min : 15; + return round(1440 / $device_interval_min); } - public function getFlashLogsHtml($start_date='2019-01-01') + public function getFlashLogsHtml($start_date = '2019-01-01') { - $flogs = $this->flashlogs()->where('created_at', '>', $start_date)->orderByDesc('created_at')->get(); // get files after start, because can only be filled with data about start date + $flogs = $this->flashlogs()->where('created_at', '>', $start_date)->orderByDesc('created_at')->get(); // get files after start, because can only be filled with data about start date $flogs_count = $flogs->count(); $flogs_valid = 0; - $html = '