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.

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