You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

487 lines
15 KiB

  1. <?php
  2. namespace App\Models;
  3. use App\Models\File;
  4. use App\Models\Model;
  5. use App\Models\SoftDeletes;
  6. use App\Models\ReportableRelation;
  7. use Illuminate\Validation\Rule;
  8. use Illuminate\Http\UploadedFile;
  9. use Spatie\MediaLibrary\HasMedia;
  10. use Illuminate\Support\Facades\Cache;
  11. use Spatie\MediaLibrary\InteractsWithMedia;
  12. use Spatie\MediaLibrary\MediaCollections\Models\Media;
  13. class Business extends Model implements HasMedia
  14. {
  15. use SoftDeletes,
  16. InteractsWithMedia;
  17. const CONVERSION_NAME = 'avatar';
  18. const COLLECTION_NAME = 'avatars';
  19. public static $permissions = ['level'];
  20. protected $table = 'businesses';
  21. protected $fillable = ['name', 'slug', 'wallet','files_volume','cache', 'color', 'description', 'has_avatar', 'calculated_at', 'users'];
  22. protected $fillable_relations = [
  23. 'users'
  24. ];
  25. protected $reportable = [
  26. 'name', 'slug', 'wallet', 'files_volume', 'cache', 'calculated_at', // fields
  27. ['users' => 'business_user'] // relations [ name => pivot ]
  28. ];
  29. public $detach_relation = false;
  30. protected $casts = [
  31. 'has_avatar' => 'boolean',
  32. 'calculated_at' => 'datetime',
  33. ];
  34. public function getValueOf(?string $key)
  35. {
  36. $values = [
  37. 'business_id' => $this->id,
  38. 'workflow_id' => null,
  39. 'project_id' => null,
  40. 'sprint_id' => null,
  41. 'status_id' => null,
  42. 'system_id' => null,
  43. 'user_id' => null,
  44. 'task_id' => null,
  45. 'subject_id' => $this->id,
  46. ];
  47. if ($key && isset($values, $key)) {
  48. return $values[$key];
  49. }
  50. return $values;
  51. }
  52. public function rules()
  53. {
  54. return [
  55. 'name' => 'bail|required|string|min:2|max:255',
  56. 'color' => 'nullable|string|min:2|max:255',
  57. 'slug' => ['bail', 'required', 'string', 'min:2', 'max:255', 'regex:/^[a-zA-Z]+[a-zA-Z\d-]*(.*[a-zA-Z\d])+$/',
  58. Rule::unique($this->table, 'slug')->ignore($this->id)],
  59. 'description' => 'nullable|string|min:2|max:1000',
  60. ];
  61. }
  62. public function cost()
  63. {
  64. return $this->hasMany(Cost::class, 'business_id','id');
  65. }
  66. public function owners()
  67. {
  68. return $this->users()->wherePivot('level', '=', enum('levels.owner.id'));
  69. }
  70. public function members()
  71. {
  72. return $this->users()->wherePivot('owner', '!=', enum('levels.owner.id'));
  73. }
  74. public function users()
  75. {
  76. return $this->belongsToMany(
  77. User::class, 'business_user', 'business_id', 'user_id',
  78. 'id', 'id', __FUNCTION__
  79. )
  80. ->using(ReportableRelation::class)
  81. ->withPivot(self::$permissions);
  82. }
  83. public function tags()
  84. {
  85. return $this->hasMany(Tag::class, 'business_id', 'id');
  86. }
  87. public function projects()
  88. {
  89. return $this->hasMany(Project::class, 'business_id', 'id');
  90. }
  91. public function systems()
  92. {
  93. return $this->hasMany(System::class, 'business_id', 'id');
  94. }
  95. public function workflows()
  96. {
  97. return $this->hasMany(Workflow::class, 'business_id', 'id');
  98. }
  99. public function sprints()
  100. {
  101. return $this->hasMany(Sprint::class, 'business_id', 'id');
  102. }
  103. public function statuses()
  104. {
  105. return $this->hasMany(Status::class, 'business_id', 'id');
  106. }
  107. public function files()
  108. {
  109. return $this->hasMany(File::class, 'user_id', 'id');
  110. }
  111. public function transactions()
  112. {
  113. return $this->hasMany(Transaction::class, 'business_id', 'id');
  114. }
  115. public function updateRelations()
  116. {
  117. // users relations
  118. if (!empty($this->filled_relations['users']) || $this->detach_relation) {
  119. $this->dirties['users'] = $this->users()->sync($this->filled_relations['users'], $this->detach_relation);
  120. }
  121. }
  122. public static function info($businessId, $fresh = false)
  123. {
  124. $info = [];
  125. $fresh = true;
  126. if ($fresh){
  127. Cache::forget('business_info'.$businessId);
  128. }
  129. if (Cache::has('business_info'.$businessId)) {
  130. return Cache::get('business_info'.$businessId);
  131. } else {
  132. $business = self::findOrFail($businessId);
  133. $tags = $business->tags()->select('id', 'label', 'color')->get()->keyBy('id');
  134. $info['tags'] = $tags->pluck('id');
  135. $workflows = $business->workflows()->select ('id', 'business_id', 'name','desc')->get()->keyBy('id')
  136. ->load(['statuses'=> fn($q) => $q->select('id', 'business_id', 'workflow_id', 'name', 'state', 'order')])
  137. ->map(fn($q) => [
  138. 'id' => $q->id,
  139. 'business_id' => $q->business_id,
  140. 'name' => $q->name,
  141. 'desc' => $q->desc,
  142. 'statuses' => $q['statuses']->keyBy('id'),
  143. ]);
  144. $info['workflows'] = $workflows->map(fn($q) => ['statuses' => $q['statuses']->pluck('id')]);
  145. $users = $business->users()->select('id', 'name', 'email', 'mobile', 'username')->with('media')->get()
  146. ->keyBy('id')
  147. ->map(fn($u) => [
  148. 'id' => $u->id,
  149. 'name' => $u->name,
  150. 'email' => $u->email,
  151. 'mobile' => $u->mobile,
  152. 'username' => $u->get,
  153. 'avatar' => $u->has_avatar,
  154. 'level' => $u->pivot['level'],
  155. ]);
  156. $info['users'] = $users->map(fn($u) => [
  157. 'level' => $u['level']
  158. ]);
  159. $projects = $business->projects()->get()->keyBy('id')->load([
  160. 'members' => fn($q) => $q->select('id', 'level'),
  161. 'systems' => fn($q) => $q->select('id', 'project_id', 'name'),
  162. 'sprints' => fn($q) => $q->select('id', 'project_id', 'name', 'description', 'started_at', 'ended_at', 'active'),
  163. 'media',
  164. ]);
  165. $info['projects'] = $projects->map(function($q) use($users){
  166. return [
  167. 'avatar' => $q->has_avatar,
  168. 'systems' => $q->systems->pluck('id'),
  169. 'sprints' => $q->sprints->pluck('id'),
  170. 'members' => $users->keyBy('id')->map(function($u, $uid) use ($q){
  171. $project_user = $q->members->firstWhere('id', $uid);
  172. return $project_user? ['level' => $project_user->pivot->level, 'is_direct' => true]:
  173. ['level' => $q->private && $u['level'] != enum('levels.owner.id') ? enum('levels.inactive.id') : $u['level'],
  174. 'is_direct'=> $project_user ? true : false];
  175. })
  176. ];
  177. });
  178. $business_info = array_merge(
  179. $business->only('id', 'name', 'slug', 'color','wallet', 'files_volume'),
  180. ['avatar' => $business->has_avatar],
  181. compact(
  182. 'info',
  183. 'tags',
  184. 'workflows',
  185. 'users',
  186. 'projects'
  187. )
  188. );
  189. Cache::put('business_info'.$businessId , $business_info, config('app.cache_ttl'));
  190. return $business_info;
  191. }
  192. }
  193. public static function stats()
  194. {
  195. return [
  196. 'users' => [
  197. 10 => [
  198. 'statuses' => [
  199. 10 => 20,
  200. 30 => 40
  201. ],
  202. 'workflows' => [
  203. 10 => 20,
  204. 30 => 40
  205. ],
  206. 'tags' => [
  207. 10 => 20,
  208. 30 => 40
  209. ],
  210. 'project' => [
  211. 10 => 20,
  212. 30 => 40
  213. ],
  214. 'sprints' => [
  215. 10 => 20,
  216. 30 => 40
  217. ],
  218. 'works' => [
  219. ],
  220. '__subsystems' => [
  221. 10 => 20,
  222. 30 => 40
  223. ],
  224. ]
  225. ],
  226. 'workflows' => [
  227. 50 => [
  228. 'statuses' => [
  229. 20 => 50
  230. ],
  231. ]
  232. ],
  233. 'statuses' => [
  234. 10 => [
  235. 'users' => [
  236. ],
  237. 'projects' => [
  238. ]
  239. ]
  240. ],
  241. 'sprints' => [
  242. 10 => [
  243. 'statuses' => [
  244. 10 => [
  245. 10 => 1
  246. ]
  247. ]
  248. ]
  249. ]
  250. ];
  251. }
  252. public function reportActivity()
  253. {
  254. }
  255. public static function nuxtInfo($businessId)
  256. {
  257. if (empty($businessId)){
  258. return null;
  259. }
  260. Cache::forget('business_nuxt_info' . $businessId);
  261. return Cache::rememberForever('business_nuxt_info' . $businessId, function () use ($businessId) {
  262. $business = self::with([
  263. 'projects.members' => fn($q) => $q->select('id', 'name'),
  264. 'projects',
  265. 'tags',
  266. 'workflows.statuses',
  267. 'workflows',
  268. 'statuses',
  269. 'users',
  270. ])->findOrFail($businessId);
  271. $globals = [];
  272. $business->users->each(function ($u) use (&$globals) {
  273. $globals[$u->id] = $u->pivot->owner == true ? ['owner' => true] : $u->pivot->only(self::$permissions);
  274. });
  275. $projects = [];
  276. $business->projects->each(function ($p) use (&$projects, &$globals) {
  277. });
  278. $business->setRelation('projects', collect($projects));
  279. $business->setRelation('users', collect($globals));
  280. return $business;
  281. });
  282. }
  283. public static function infoOld($businessId)
  284. {
  285. if (empty($businessId))
  286. return null;
  287. Cache::forget('business_info' . $businessId);
  288. return Cache::rememberForever('business_info' . $businessId, function () use ($businessId) {
  289. $ob = [];
  290. $business = self::with([
  291. 'projects.members' => fn($q) => $q->select('id', 'name'),
  292. 'projects' => fn($q) => $q->select('id', 'business_id', 'private'),
  293. 'tags' => fn($q) => $q->select('id', 'business_id', 'label'),
  294. 'sprints' => fn($q) => $q->select('id','business_id','name', 'active'),
  295. 'workflows.statuses' => fn($q) => $q->select('id', 'name'),
  296. 'workflows' => fn($q) => $q->select('id', 'business_id', 'name'),
  297. 'statuses' => fn($q) => $q->select('id', 'business_id', 'name', 'state'),
  298. 'users' => fn($q) => $q->select('id', 'name'),
  299. ])->findOrFail($businessId);
  300. // permissions in business
  301. $permissions = [];
  302. $business->users->each(function ($user) use (&$permissions) {
  303. $permissions[$user->id] = $user->pivot->only(['owner']);
  304. $permissions[$user->id]['global_PA'] = $permissions[$user->id]['owner'] == true ?
  305. enum('roles.manager.id') : $user->pivot->PA;
  306. $permissions[$user->id]['global_FA'] = $permissions[$user->id]['owner'] == true ?
  307. enum('roles.manager.id') : $user->pivot->FA;
  308. $permissions[$user->id]['PA'] = [];
  309. $permissions[$user->id]['FA'] = [];
  310. });
  311. //projects
  312. $projects = [];
  313. $business->projects->each(function ($p) use (&$permissions, $business, &$projects) {
  314. $business->users->each(function ($user) use (&$permissions, $p) {
  315. $PA = null;
  316. $FA = null;
  317. if ($permissions[$user->id]['owner'] == true) {
  318. $PA = enum('roles.manager.id');
  319. $FA = enum('roles.manager.id');
  320. } else if (!empty($project_user = $p->getPermissions($user->id))) {
  321. $PA = $project_user->pivot->PA;
  322. $FA = $project_user->pivot->FA;
  323. } else if (empty($p->getPermissions($user->id))) {
  324. $PA = $p->private == false ? $permissions[$user->id]['global_PA'] : enum('roles.hidden.id') ;
  325. $FA = $p->private == false ? $permissions[$user->id]['global_FA'] : enum('roles.hidden.id');
  326. }
  327. if ($PA !== null && $FA !== null) {
  328. $permissions[$user->id]['PA'][$p->id] = $PA;
  329. $permissions[$user->id]['FA'][$p->id] = $FA;
  330. }
  331. });
  332. $projects[$p->id] ='';
  333. });
  334. //workflow
  335. $workflows = [];
  336. $business->workflows->each(function ($w) use (&$workflows) {
  337. $workflows[$w->id] = $w->statuses->pluck('id');
  338. });
  339. $ob['tags'] = $business->tags->pluck('id');
  340. $ob['statuses'] = $business->statuses;
  341. $ob['sprints'] = $business->sprints;
  342. $ob['workflows'] = $workflows;
  343. $ob['users'] = $permissions;
  344. $ob['projects'] = $projects;
  345. return collect($ob);
  346. });
  347. }
  348. public function registerMediaCollections(): void
  349. {
  350. $this->addMediaCollection(static::COLLECTION_NAME)
  351. ->acceptsMimeTypes([
  352. 'image/jpeg',
  353. 'image/png',
  354. 'image/tiff',
  355. 'image/gif',
  356. ])
  357. ->useDisk('public')
  358. ->singleFile();
  359. }
  360. public function registerMediaConversions(Media $media = null): void
  361. {
  362. $this->addMediaConversion(static::CONVERSION_NAME)
  363. ->width(200)
  364. ->height(200)
  365. ->queued()
  366. ->nonOptimized()
  367. ->performOnCollections(static::COLLECTION_NAME);
  368. }
  369. public function saveAsAvatar(UploadedFile $avatar): void
  370. {
  371. $this->addMedia($avatar)->toMediaCollection(static::COLLECTION_NAME);
  372. $this->update([
  373. 'has_avatar' => true,
  374. ]);
  375. @unlink($this->getFirstMedia(static::COLLECTION_NAME)->getPath());
  376. }
  377. public function deleteAvatar(): void
  378. {
  379. $path = $this->getFirstMedia(static::COLLECTION_NAME)->getPath();
  380. $this->getFirstMedia(static::COLLECTION_NAME)->delete();
  381. $this->update([
  382. 'has_avatar' => false,
  383. ]);
  384. @unlink($path);
  385. }
  386. public function getAvatarUrl(): ?string
  387. {
  388. if ($url = $this->getFirstMediaUrl(static::COLLECTION_NAME, static::CONVERSION_NAME)) {
  389. return $url;
  390. }
  391. return null;
  392. }
  393. }