Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update post create to accept whatsapp posts #4957

Merged
merged 3 commits into from
Jun 3, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Phinx\Migration\AbstractMigration;

class AddContactIdToPosts extends AbstractMigration
{

public function change()
{
$this->table('posts')
->addColumn('contact_id', 'integer', [
'null' => true,
'after' => 'author_realname'
])
->update();
}
}
23 changes: 23 additions & 0 deletions src/Ushahidi/Contracts/Sources.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Ushahidi\Contracts;

/**
* Interface for post sources
*
* @author Ushahidi Team <team@ushahidi.com>
* @package DataSource
* @copyright 2013 Ushahidi
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License Version 3 (GPLv3)
*
*/
interface Sources
{
const WEB = 'web';
const MOBILE = 'mobile';
const SMS = 'sms';
const TWITTER = 'twitter';
const WHATSAPP = 'whatsapp';
const EMAIL = 'email';
const USSD = 'ussd';
}
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ public function getResponseRecipients($form_id, $created_after, $created_before)
->from('posts')
->where('form_id', '=', $form_id);
$query = $this->betweenDates($query, 'created', $created_before, $created_after);
$query = DB::select([DB::expr('COUNT(contact_id)'), 'total'])
$query = DB::select([DB::expr('COUNT(messages.contact_id)'), 'total'])
->distinct(true)
->from([$query,'targeted_posts'])
->join('messages', 'INNER')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use Illuminate\Support\Facades\Auth;
use Ushahidi\Core\Entity\Contact as ContactEntity;
use Ushahidi\Modules\V5\Models\Stage;
use Ushahidi\Contracts\Sources;
use Ushahidi\Contracts\Contact as ContractContact;

class CreateContactCommand implements Command
{
Expand Down Expand Up @@ -39,6 +41,21 @@ public static function fromRequest(ContactRequest $request): self
return new self(new ContactEntity($input));
}

public static function forWhatsapp($user_id, String $contact_number, String $type = "phone", $can_notify = 0): self
{

$user = Auth::user();
$input['user_id'] =$user_id ?? ($user ? $user->id : null);
$input['data_source'] = Sources::WHATSAPP;
$input['type'] = $type ?? ContractContact::PHONE;
$input['contact'] = $contact_number;
$input['can_notify'] = $can_notify ?? 0;
$input['created'] = time();
$input['updated'] = null;

return new self(new ContactEntity($input));
}

/**
* @return ContactEntity
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Jenssegers\Agent\Facades\Agent;
use Ushahidi\Core\Entity\Post as PostEntity;
use Ushahidi\Modules\V5\Models\Stage;
use Ushahidi\Contracts\Sources;

class CreatePostCommand implements Command
{
Expand Down Expand Up @@ -52,7 +53,7 @@ public static function createFromRequest(PostRequest $request): self
$input['slug'] = Post::makeSlug($request->input('slug') ?? $request->input('title'));
$input['user_id'] = $request->input('user_id') ?? ($user ? $user->id : null);
$input['author_email'] = $request->input('author_email') ?? ($user ? $user->email : null);
$input['author_realname'] = $request->input('author_realname') ??($user ? $user->realname : null);
$input['author_realname'] = $request->input('author_realname') ?? ($user ? $user->realname : null);
$input['form_id'] = $request->input('form_id');
$input['parent_id'] = $request->input('parent_id');
$input['type'] = $request->input('type');
Expand All @@ -63,10 +64,18 @@ public static function createFromRequest(PostRequest $request): self
$input['locale'] = $request->input('locale') ?? PostEntity::DEFAULT_LOCAL;
$input['base_language'] = $request->input('base_language') ?? PostEntity::DEFAULT_LOCAL;
$input['published_to'] = $request->input('published_to');
if (Agent::isMobile() && Agent::browser() == false) {
$input['source'] = 'mobile';

if ($request->input('source') === Sources::WHATSAPP) {
$input['author_email'] = null;
$input['author_realname'] = $request->input('contact')['contact'] ;
$input['source'] = Sources::WHATSAPP;
$input['contact_id'] = $request->input('contact_id');
// To Do : this temporary to store contact object in metadata to avoid duplicated join
$input['metadata']['contact'] = $request->input('contact');
} elseif (Agent::isMobile() && Agent::browser() == false) {
$input['source'] = Sources::MOBILE;
} elseif (($browser = Agent::browser()) && isset($browser)) {
$input['source'] = 'web';
$input['source'] = Sources::WEB;
}
$input['metadata']['source'] = [
'platform' => Agent::platform(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Ushahidi\Modules\V5\Http\Resources\MessagePointerResource;
use Ushahidi\Modules\V5\Http\Resources\LockCollection;
use Ushahidi\Modules\V5\Http\Resources\Survey\TaskCollection;
use Ushahidi\Contracts\Sources;

class FindPostByIdQueryHandler extends AbstractPostQueryHandler
{
Expand Down Expand Up @@ -78,7 +79,18 @@ private function addHydrateRelationships(Post $post, array $hydrates)
break;
case 'contact':
$post->contact = null;
if ($post->message) {
if ($post->source === Sources::WHATSAPP) {
if ($this->userHasManagePostPermissions()) {
if (isset($post->metadata['contact'])) {
// $post->contact = Contact::find($post->contact_id); // not good in case there are many whatsapp posts this will be problem for the DB
$post->contact = (new Contact)->fill($post->metadata['contact']);
}
} else {
if (isset($post->metadata['contact']['id'])) {
$post->contact = (new Contact)->fill(['id'=>$post->metadata['contact']['id']]);
}
}
} elseif ($post->message) {
if ($this->userHasManagePostPermissions()) {
$post->contact = $post->message->contact;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Ushahidi\Modules\V5\Http\Resources\MessagePointerResource;
use Ushahidi\Modules\V5\Http\Resources\LockCollection;
use Ushahidi\Modules\V5\Http\Resources\Survey\TaskCollection;
use Ushahidi\Modules\V5\Models\Contact;
use Ushahidi\Contracts\Sources;

class ListPostsQueryHandler extends AbstractPostQueryHandler
{
Expand Down Expand Up @@ -83,6 +85,17 @@ private function addHydrateRelationships(Post $post, array $hydrates)
break;
case 'contact':
$post->contact = null;
if ($post->source === Sources::WHATSAPP) {
if ($this->userHasManagePostPermissions()) {
if (isset($post->metadata['contact'])) {
$post->contact = (new Contact)->fill($post->metadata['contact']);
}
} else {
if (isset($post->metadata['contact']['id'])) {
$post->contact = (new Contact)->fill(['id'=>$post->metadata['contact']['id']]);
}
}
}
if ($post->message) {
if ($this->userHasManagePostPermissions()) {
$post->contact = $post->message->contact;
Expand Down
47 changes: 47 additions & 0 deletions src/Ushahidi/Modules/V5/Http/Controllers/PostController.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@
use Ushahidi\Contracts\Permission;
use Ushahidi\Core\Concerns\AdminAccess;

use Ushahidi\Modules\V5\Actions\Contact\Commands\CreateContactCommand;
use Ushahidi\Modules\V5\Actions\Contact\Queries\FetchContactQuery;
use Ushahidi\Modules\V5\Actions\Contact\Queries\FetchContactByIdQuery;
use Ushahidi\Modules\V5\Models\Contact;
use Ushahidi\Contracts\Sources;
use Ushahidi\Contracts\Contact as ContractContact;

class PostController extends V5Controller
{

Expand Down Expand Up @@ -101,6 +108,37 @@ private function runAuthorizer($ability, $object)
return $user;
}

/**
* Gets the whatsapp contact from the request. If there are no contacts it creates one
*
* @param Request $request
* @return Contact
*/
private function getWhatsappContact(PostRequest $request):Contact
{
$search_request = new Request();
$search_request->merge([
'data_source'=>Sources::WHATSAPP,
'contact'=>$request->input('contact')['contact']
]);
$contacts = $this->queryBus->handle(FetchContactQuery::FromRequest($search_request));

if (count($contacts) > 0) {
$contact = $contacts->first();
} else {
$contact_id = $this->commandBus->handle(
CreateContactCommand::forWhatsapp(
$request->input('user_id'),
$request->input('contact')['contact'],
$request->input('contact')['type'] ?? ContractContact::PHONE,
$request->input('contact')['can_notify'] ?? 0
)
);
$contact = $this->queryBus->handle(new FetchContactByIdQuery($contact_id));
}

return $contact;
}

/**
* Display the specified resource.
Expand All @@ -113,6 +151,15 @@ public function store(PostRequest $request)
{

$this->runAuthorizer('store', [Post::class, $request->input('form_id'), $this->getUser()->getId()]);
if ($request->input('source') === 'whatsapp') {
$contact = $this->getWhatsappContact($request);
$request->merge([
'contact_id'=>$contact->id,
// To Do: this temporay soluation to save the contact object in posts metadata,
// bu this we can avoid extra diplicated join relation!
'contact' => $contact
]) ;
}
$id = $this->commandBus->handle(CreatePostCommand::createFromRequest($request));
$post = $this->queryBus->handle(
new FindPostByIdQuery(
Expand Down
4 changes: 3 additions & 1 deletion src/Ushahidi/Modules/V5/Models/Post/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class Post extends BaseModel
'content',
'author_email',
'author_realname',
'contact_id',
'status',
'published_to',
'locale',
Expand All @@ -66,7 +67,7 @@ class Post extends BaseModel
'color' => ['fields' => [], 'relationships' => ["survey"]],
'sets' => ['fields' => [], 'relationships' => ["sets"]],
'message' => ['fields' => [], 'relationships' => ['message']],
'contact' => ['fields' => [], 'relationships' => ['message']],
'contact' => ['fields' => ['metadata','source'], 'relationships' => ['message']],
'completed_stages' => ['fields' => [], 'relationships' => ["postStages"]],
'translations' => ['fields' => [], 'relationships' => ["translations"]],
'enabled_languages' => ['fields' => ['base_language'], 'relationships' => ['translations']],
Expand Down Expand Up @@ -158,6 +159,7 @@ class Post extends BaseModel
'content',
'author_email',
'author_realname',
'contact_id',
'status',
'published_to',
'locale',
Expand Down
17 changes: 12 additions & 5 deletions src/Ushahidi/Modules/V5/Repository/Post/EloquentPostRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Ushahidi\Core\Tool\BoundingBox;
use Illuminate\Support\Facades\Auth;
use Ushahidi\Modules\V5\Models\RolePermission;
use Ushahidi\Contracts\Sources;

class EloquentPostRepository implements PostRepository
{
Expand Down Expand Up @@ -213,17 +214,23 @@ private function setSearchCondition(PostSearchFields $search_fields, $query, boo
$builder_1->whereNull('messages.type')
->whereNull('posts.source');
});
$builder->orWhere('posts.source', 'web');
$builder->orWhere('posts.source', Sources::WEB);
$builder->orWhereIn('messages.type', $search_fields->source());
if (in_array('mobile', $search_fields->source())) {
$builder->orWhere('posts.source', 'mobile');
if (in_array(Sources::MOBILE, $search_fields->source())) {
$builder->orWhere('posts.source', Sources::MOBILE);
}
if (in_array(Sources::WHATSAPP, $search_fields->source())) {
$builder->orWhere('posts.source', Sources::WHATSAPP);
}
});
} else {
$query->where(function ($builder) use ($search_fields) {
$builder->WhereIn('messages.type', $search_fields->source());
if (in_array('mobile', $search_fields->source())) {
$builder->orWhere('posts.source', 'mobile');
if (in_array(Sources::MOBILE, $search_fields->source())) {
$builder->orWhere('posts.source', Sources::MOBILE);
}
if (in_array(Sources::WHATSAPP, $search_fields->source())) {
$builder->orWhere('posts.source', Sources::WHATSAPP);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ private function queryForWeb($survey_id, $created_after, $created_before)
public function getResponseRecipients($survey_id, SurveyStatesSearchFields $search_fields)
{
$query = DB::table('posts')
->selectRaw('COUNT(contact_id) as total')
->selectRaw('COUNT(messages.contact_id) as total')
->distinct()
->join('messages', 'messages.post_id', '=', 'posts.id')
->where('form_id', '=', $survey_id)
Expand Down
Loading