Skip to content

Commit

Permalink
Merge pull request #1654 from bakaphp/development
Browse files Browse the repository at this point in the history
Feat: receiver parser
  • Loading branch information
kaioken committed Jul 9, 2024
2 parents a0f1835 + 07e6af0 commit 534ce98
Show file tree
Hide file tree
Showing 11 changed files with 417 additions and 48 deletions.
6 changes: 4 additions & 2 deletions config/scout.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
use Kanvas\Social\Messages\Models\Message;
use Kanvas\Social\UsersLists\Models\UserList as ModelUserList;
use Kanvas\Users\Models\Users;
use Silber\Bouncer\Database\Role as SilberRole;

return [

/*
|--------------------------------------------------------------------------
| Default Search Engine
Expand Down Expand Up @@ -146,6 +146,9 @@
Role::class => [
'filterableAttributes' => ['scope', 'name', 'title'],
],
SilberRole::class => [
'filterableAttributes' => ['scope', 'name', 'title'],
],
ModelUserList::class => [
'filterableAttributes' => [
'apps_id',
Expand All @@ -161,5 +164,4 @@
],
],
],

];
33 changes: 25 additions & 8 deletions graphql/schemas/Guild/people.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ type People {
contacts: [Contact!]! @hasMany
address: [Address!]! @hasMany
employment_history: [PeopleEmploymentHistory!]
@hasMany(
relation: "employmentHistory"
)
@hasMany(relation: "employmentHistory")
files: [Filesystem!]!
@paginate(
defaultCount: 25
Expand All @@ -40,7 +38,7 @@ type PeopleEmploymentHistory {
start_date: Date!
end_date: Date
status: Int!
income_type: String
income_type: String
}

type PeopleRelationship {
Expand Down Expand Up @@ -87,15 +85,27 @@ extend type Query @guard {
peoples(
search: String @search
where: _
@whereConditions(columns: ["id", "uuid", "companies_id", "dob", "name", "firstname", "lastname"])
@whereConditions(
columns: [
"id"
"uuid"
"companies_id"
"dob"
"name"
"firstname"
"lastname"
]
)
hasEmails: _
@whereHasConditions(relation: "emails", columns: ["id", "value"])
hasPhones: _
@whereHasConditions(relation: "phones", columns: ["id", "value"])
hasTags: _
@whereHasConditions(relation: "tags", columns: ["name"])
hasTags: _ @whereHasConditions(relation: "tags", columns: ["name"])
hasAddress: _
@whereHasConditions(relation: "address", columns: ["address", "city", "state", "zip"])
@whereHasConditions(
relation: "address"
columns: ["address", "city", "state", "zip"]
)
hasCustomFields: _
@whereHasConditions(
relation: "customFields"
Expand All @@ -117,6 +127,13 @@ extend type Query @guard {
defaultCount: 25
scopes: ["fromApp", "fromCompany"]
)

peopleCount: Int
@count(
model: "Kanvas\\Guild\\Customers\\Models\\People"
scopes: ["fromApp", "fromCompany", "notDeleted"]
)

}

extend type Mutation @guard {
Expand Down
1 change: 1 addition & 0 deletions src/Domains/Guild/Customers/DataTransferObject/People.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Baka\Users\Contracts\UserInterface;
use DateTime;
use Kanvas\Companies\Models\CompaniesBranches;
use Kanvas\Guild\Customers\Enums\ContactTypeEnum;
use Spatie\LaravelData\Attributes\DataCollectionOf;
use Spatie\LaravelData\Attributes\WithCast;
use Spatie\LaravelData\Casts\DateTimeInterfaceCast;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
namespace Kanvas\Guild\Leads\Actions;

use Baka\Support\Str;
use Kanvas\Guild\Customers\Enums\ContactTypeEnum;
use Kanvas\Guild\Leads\Models\Lead;

class ConvertJsonTemplateToLeadAction
class ConvertJsonTemplateToLeadStructureAction
{
public function __construct(
protected Lead $lead,
protected array $template,
protected array $data
) {
Expand All @@ -19,30 +19,23 @@ public function __construct(
/**
* Map to lead fields.
*/
public function execute(): Lead
public function execute(): array
{
$newMapping = $this->parseLead($this->data, $this->template);

if (method_exists($this->lead, 'setCustomFields')) {
$this->lead->setCustomFields($newMapping['customField']);
}

if (method_exists($this->lead, 'disableWorkflows')) {
$this->lead->disableWorkflows();
}

$this->lead->saveOrFail($newMapping['modelInfo']);
return $newMapping;
}

public function processFunctions(Lead $lead, array $newMapping): void
{
if (isset($newMapping['function']) && ! empty($newMapping['function'])) {
foreach ($newMapping['function'] as $key => $value) {
$this->lead->{$key}($value);
if (method_exists($this->lead, $key)) {
$this->lead->{$key}($value);
$lead->{$key}($value);
if (method_exists($lead, $key)) {
$lead->{$key}($value);
}
}
}

return $this->lead;
}

/**
Expand Down Expand Up @@ -92,26 +85,66 @@ public function loopArrayAndReplaceDotNotion(array $array): array
public function parseLead(array $request, array $template): array
{
$parsedData = [];
$customFields = [];

// Iterate through the template
// Initialize people structure with placeholders
$peopleStructure = [
'firstname' => null,
'lastname' => null,
'contacts' => [],
];

// Iterate through the template and map values accordingly
foreach ($template as $path => $info) {
$value = $this->getValueFromPath($request, $path);

if ($info['type'] === 'string') {
$parsedData['modelInfo'][$info['name']] = $value;
} elseif ($info['type'] === 'customField') {
$parsedData['customField'][$info['name']] = $value;
} elseif ($info['type'] === 'function') {
$functionName = $info['function'];
if (method_exists($this, $functionName) && isset($info['json'])) {
$parsedData['function'][$functionName] = $this->{$functionName}($request, $info['json']);
}
}
$name = $info['name'];
$type = $info['type'];

match ($type) {
'string' => $this->mapStringType($peopleStructure, $parsedData, $name, $value),
'customField' => $customFields[$name] = $value,
'function' => $this->mapFunctionType($parsedData, $request, $info, $name),
default => null
};
}

$parsedData['custom_fields'] = $customFields;
$parsedData['people'] = $peopleStructure;

return $parsedData;
}

private function mapStringType(array &$peopleStructure, array &$parsedData, string $name, $value): void
{
match ($name) {
'firstname' => $peopleStructure['firstname'] = $value,
'lastname' => $peopleStructure['lastname'] = $value,
'email' => $this->addContact($peopleStructure['contacts'], ContactTypeEnum::EMAIL->value, $value),
'phone' => $this->addContact($peopleStructure['contacts'], ContactTypeEnum::PHONE->value, $value),
default => null
};

$parsedData[$name] = $value;
}

private function addContact(array &$contacts, int $contactTypeId, ?string $value): void
{
if ($value) {
$contacts[] = [
'contacts_types_id' => $contactTypeId,
'value' => $value,
];
}
}

private function mapFunctionType(array &$parsedData, array $request, array $info, string $name): void
{
$functionName = $info['function'];
if (method_exists($this, $functionName) && isset($info['json'])) {
$parsedData['function'][$functionName] = $this->{$functionName}($request, $info['json']);
}
}

public function getValueFromPath(array $array, string $path): string
{
$values = [];
Expand All @@ -137,6 +170,9 @@ public function getValueFromPath(array $array, string $path): string
return implode(' ', $values);
}

/**
* @deprecated we need to refactor
*/
public function setPeople(array $request, array $json): array
{
$person = [];
Expand Down
2 changes: 2 additions & 0 deletions src/Domains/Guild/Leads/Actions/CreateLeadAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ public function execute(): Lead
//create people
$people = (new CreatePeopleAction($this->leadData->people))->execute();
$newLead->people_id = $people->getId();
$newLead->email = $people->getEmails()->isNotEmpty() ? $people->getEmails()->first()?->value : null;
$newLead->phone = $people->getPhones()->isNotEmpty() ? $people->getPhones()->first()?->value : null;
$newLead->saveOrFail();

$newLead->setCustomFields($this->leadData->custom_fields);
Expand Down
16 changes: 10 additions & 6 deletions src/Domains/Guild/Leads/DataTransferObject/Lead.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,27 +55,31 @@ public static function viaRequest(UserInterface $user, AppInterface $app, array
$user
);

$firstname = $request['people']['firstname'] ?? '';
$lastname = $request['people']['lastname'] ?? '';
$title = $request['title'] ?? $firstname . ' ' . $lastname . ' Opp';

return new self(
$app,
$branch,
$user,
(string) $request['title'],
(int) $request['pipeline_stage_id'],
(string) $title,
(int) ($request['pipeline_stage_id'] ?? 0),
People::from([
'app' => $app,
'branch' => $branch,
'user' => $user,
'firstname' => $request['people']['firstname'],
'lastname' => $request['people']['lastname'],
'firstname' => $firstname,
'lastname' => $lastname,
'contacts' => Contact::collect($request['people']['contacts'], DataCollection::class),
'address' => Address::collect($request['people']['address'], DataCollection::class),
'address' => Address::collect($request['people']['address'] ?? [], DataCollection::class),
'id' => $request['people']['id'] ?? 0,
'dob' => $request['people']['dob'] ?? null,
'facebook_contact_id' => $request['people']['facebook_contact_id'] ?? null,
'google_contact_id' => $request['people']['google_contact_id'] ?? null,
'apple_contact_id' => $request['people']['apple_contact_id'] ?? null,
'linkedin_contact_id' => $request['people']['linkedin_contact_id'] ?? null,
'custom_fields' => $request['people']['custom_fields'] ?? [],
'custom_fields' => $request['people']['custom_fields'] ?? [],
]),
(int) ($request['leads_owner_id'] ?? 0),
(int) ($request['type_id'] ?? 0),
Expand Down
9 changes: 9 additions & 0 deletions src/Domains/Guild/Leads/Jobs/CreateLeadsFromReceiverJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Kanvas\Guild\Leads\Jobs;

use Kanvas\Guild\Leads\Actions\ConvertJsonTemplateToLeadStructureAction;
use Kanvas\Guild\Leads\Actions\CreateLeadAction;
use Kanvas\Guild\Leads\Actions\CreateLeadAttemptAction;
use Kanvas\Guild\Leads\DataTransferObject\Lead;
Expand Down Expand Up @@ -31,6 +32,14 @@ public function execute(): array
$payload = $this->webhookRequest->payload;
$payload['branch_id'] = $leadReceiver->companies_branches_id;

if (! empty($leadReceiver->template) && is_array($leadReceiver->template)) {
$parseTemplate = new ConvertJsonTemplateToLeadStructureAction(
$leadReceiver->template,
$payload
);
$payload = $parseTemplate->execute();
}

$createLead = new CreateLeadAction(
Lead::viaRequest(
$leadReceiver->user,
Expand Down
5 changes: 5 additions & 0 deletions src/Domains/Guild/Leads/Models/LeadReceiver.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Kanvas\Guild\Leads\Models;

use Baka\Casts\Json;
use Baka\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Kanvas\Companies\Models\CompaniesBranches;
Expand Down Expand Up @@ -37,6 +38,10 @@ class LeadReceiver extends BaseModel
protected $table = 'leads_receivers';
protected $guarded = [];

protected $casts = [
'template' => Json::class
];

/**
* rotation
*/
Expand Down
4 changes: 3 additions & 1 deletion src/Kanvas/AccessControlList/Actions/CreateRoleAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Bouncer;
use Illuminate\Support\Facades\Validator;
use Kanvas\AccessControlList\Enums\RolesEnums;
use Kanvas\AccessControlList\Models\Role;
use Kanvas\Apps\Models\Apps;
use Kanvas\Companies\Models\Companies;
use Kanvas\Exceptions\ValidationException;
Expand Down Expand Up @@ -37,7 +38,7 @@ public function execute(?Companies $company = null): SilberRole

$validator = Validator::make(
[
'name' => $this->name
'name' => $this->name,
],
[
'name' => 'required|unique:roles,name,null,id,scope,' . RolesEnums::getScope($this->app),
Expand All @@ -48,6 +49,7 @@ public function execute(?Companies $company = null): SilberRole
throw new ValidationException($validator->errors()->first() . 'for roles in the current app');
}

Bouncer::useUserModel(Role::class);
$role = Bouncer::role()->firstOrCreate([
'name' => $this->name,
'title' => $this->title ?? $this->name,
Expand Down
Loading

0 comments on commit 534ce98

Please sign in to comment.