Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions app/Filament/Pages/Companies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php

namespace App\Filament\Pages;

use App\Filament\Resources\UserResource;
use App\Services\CompanyAggregator;
use Filament\Actions\Action;
use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedTable;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class Companies extends Page implements HasTable
{
use InteractsWithTable;

protected static \BackedEnum|string|null $navigationIcon = 'heroicon-o-building-office-2';

protected static ?string $navigationLabel = 'Companies';

protected static ?string $title = 'Companies';

protected static ?int $navigationSort = 2;

public function table(Table $table): Table
{
return $table
->records(function (
?string $search,
?string $sortColumn,
?string $sortDirection,
int $page,
int $recordsPerPage,
): LengthAwarePaginator {
$records = app(CompanyAggregator::class)->aggregate();

$records = $records
->when(
filled($search),
fn (Collection $data): Collection => $data->filter(
fn (array $record): bool => str_contains(
Str::lower($record['domain']),
Str::lower($search),
),
),
);

if (filled($sortColumn)) {
$records = $records->sortBy(
$sortColumn,
SORT_REGULAR,
($sortDirection ?? 'desc') === 'desc',
);
} else {
$records = $records->sortByDesc('users_count');
}

$records = $records->values();
$total = $records->count();

$pageItems = $records
->forPage($page, $recordsPerPage)
->mapWithKeys(fn (array $record): array => [$record['domain'] => $record]);

return new LengthAwarePaginator(
items: $pageItems,
total: $total,
perPage: $recordsPerPage,
currentPage: $page,
);
})
->columns([
TextColumn::make('domain')
->label('Domain')
->sortable()
->copyable(),
TextColumn::make('users_count')
->label('Users')
->sortable()
->numeric(),
TextColumn::make('earliest_signup')
->label('Earliest signup')
->dateTime()
->sortable(),
TextColumn::make('latest_signup')
->label('Latest signup')
->dateTime()
->sortable(),
])
->defaultSort('users_count', 'desc')
->searchable()
->actions([
Action::make('viewUsers')
->label('Users')
->icon('heroicon-o-users')
->color('gray')
->url(fn (array $record): string => UserResource::getUrl('index', [
'tableSearch' => $record['domain'],
])),
])
->paginated([10, 25, 50, 100]);
}

public function content(Schema $schema): Schema
{
return $schema
->components([
EmbeddedTable::make(),
]);
}
}
33 changes: 33 additions & 0 deletions app/Listeners/NotifyAccountsOfNewCompanyDomain.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Listeners;

use App\Notifications\NewCompanyDomainRegistered;
use App\Services\CompanyAggregator;
use App\Support\ConsumerEmailDomains;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Notification;

class NotifyAccountsOfNewCompanyDomain
{
public function __construct(
public CompanyAggregator $companies,
) {}

public function handle(Registered $event): void
{
$user = $event->user;
$domain = ConsumerEmailDomains::domainFromEmail($user->email);

if (! ConsumerEmailDomains::isCompanyDomain($domain)) {
return;
}

if ($this->companies->countUsersForDomain($domain) !== 1) {
return;
}

Notification::route('mail', config('companies.accounts_email'))
->notify(new NewCompanyDomainRegistered($user, $domain));
}
}
38 changes: 38 additions & 0 deletions app/Notifications/NewCompanyDomainRegistered.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\Notifications;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewCompanyDomainRegistered extends Notification implements ShouldQueue
{
use Queueable;

public function __construct(
public User $user,
public string $domain,
) {}

/**
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['mail'];
}

public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('New company domain: '.$this->domain)
->greeting('A new company domain just signed up.')
->line("**Domain:** {$this->domain}")
->line("**Name:** {$this->user->name}")
->line("**Email:** {$this->user->email}")
->line('**Signed up:** '.$this->user->created_at?->toDayDateTimeString());
}
}
2 changes: 2 additions & 0 deletions app/Providers/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Providers;

use App\Listeners\NotifyAccountsOfNewCompanyDomain;
use App\Listeners\StripeWebhookHandledListener;
use App\Listeners\StripeWebhookReceivedListener;
use App\Listeners\SuppressMailNotificationListener;
Expand All @@ -23,6 +24,7 @@ class EventServiceProvider extends ServiceProvider
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
NotifyAccountsOfNewCompanyDomain::class,
],
WebhookReceived::class => [
StripeWebhookReceivedListener::class,
Expand Down
74 changes: 74 additions & 0 deletions app/Services/CompanyAggregator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace App\Services;

use App\Models\User;
use App\Support\ConsumerEmailDomains;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class CompanyAggregator
{
/**
* @return Collection<string, array{domain: string, users_count: int, earliest_signup: mixed, latest_signup: mixed}>
*/
public function aggregate(): Collection
{
$domainExpression = $this->domainExpression();

$rows = User::query()
->select([
DB::raw("{$domainExpression} as domain"),
DB::raw('COUNT(*) as users_count'),
DB::raw('MIN(created_at) as earliest_signup'),
DB::raw('MAX(created_at) as latest_signup'),
])
->whereNotNull('email')
->where('email', 'like', '%@%')
->groupBy(DB::raw($domainExpression))
->get();

return $rows
->filter(fn ($row): bool => ConsumerEmailDomains::isCompanyDomain($row->domain))
->mapWithKeys(fn ($row): array => [
$row->domain => [
'domain' => $row->domain,
'users_count' => (int) $row->users_count,
'earliest_signup' => $row->earliest_signup,
'latest_signup' => $row->latest_signup,
],
]);
}

/**
* @return Collection<int, User>
*/
public function usersForDomain(string $domain): Collection
{
$domain = strtolower($domain);
$domainExpression = $this->domainExpression();

return User::query()
->whereRaw("{$domainExpression} = ?", [$domain])
->orderBy('created_at')
->get();
}

public function countUsersForDomain(string $domain): int
{
$domain = strtolower($domain);
$domainExpression = $this->domainExpression();

return User::query()
->whereRaw("{$domainExpression} = ?", [$domain])
->count();
}

protected function domainExpression(): string
{
return match (DB::connection()->getDriverName()) {
'sqlite' => "lower(substr(email, instr(email, '@') + 1))",
default => "LOWER(SUBSTRING_INDEX(email, '@', -1))",
};
}
}
50 changes: 50 additions & 0 deletions app/Support/ConsumerEmailDomains.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Support;

use Illuminate\Support\Str;

class ConsumerEmailDomains
{
public static function extract(?string $email): ?string
{
if (! filled($email) || ! str_contains($email, '@')) {
return null;
}

$domain = strtolower(trim(Str::afterLast($email, '@')));

return $domain !== '' ? $domain : null;
}

public static function isConsumer(?string $domain): bool
{
if (! filled($domain)) {
return true;
}

$domain = strtolower($domain);

if (in_array($domain, config('companies.consumer_domains', []), true)) {
return true;
}

foreach (config('companies.consumer_domain_prefixes', []) as $prefix) {
if (str_starts_with($domain, $prefix)) {
return true;
}
}

return false;
}

public static function isCompanyDomain(?string $domain): bool
{
return filled($domain) && ! static::isConsumer($domain);
}

public static function domainFromEmail(?string $email): ?string
{
return static::extract($email);
}
}
Loading