Skip to content

Instantly share code, notes, and snippets.

@ahsanmster
Created November 2, 2022 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahsanmster/c3dbf2e7893cde74cc59f6a035a972ef to your computer and use it in GitHub Desktop.
Save ahsanmster/c3dbf2e7893cde74cc59f6a035a972ef to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Commands\RunOnceCommand;
use App\Jobs\ReleasePhoneNumbers;
use App\Models\Setting;
use App\Models\SmsPhoneManager;
use App\Models\SmsPhoneTransactionLog;
use App\Models\TwilioBrandData;
use App\Models\User;
use App\Models\UserBrand;
use App\Models\UserCampaign;
use App\Services\CSPService;
use App\Services\GuzzleHttpWrapper;
use App\Services\SMS\Providers\TwilioService;
use App\Services\UserService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use SignalWire\Rest\Client as SignalWireClient;
class DisableSystem10DLC extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'disable-system-10dlc {user_ids?} ';
/**
* The console command description.
*
* @var string
*/
protected $description = 'release users phone numbers';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$userIds = !empty($this->argument('user_ids')) ? explode(',', $this->argument('user_ids')) : [];
$users = $this->getAllUsers($userIds);
$bar = $this->output->createProgressBar(count($users));
foreach ($users as $user) {
$this->info("Processing User: ".$user->id);
// Release date need to update
// User setting need to store last processing user and process likewise
if ($user->reg_ref_type != 1)
$user->fill(['reg_ref_type' => 1])->save();
$isTwilioClosed = false;
if (empty($userIds))
$this->updateLastProcessingUserId($user->id);
$phoneNumbers = $this->getSystemPhoneNumbersOfUser($user->id);
$campaigns = UserCampaign::getCampaignsByUser($user->id, true);
$brand = UserBrand::query()->where('user_id', $user->id)->first();
$settingObject = [];
if ($phoneNumbers->count() == 0 && $campaigns->count() == 0 && !($brand)) {
$bar->advance();
continue;
}
Log::channel('disable_10dlc')->info(PHP_EOL . "________Processing User : " . $user->id);
$logObject = [
"email" => $user->email,
"id" => $user->id
];
if ($phoneNumbers->count() > 0) {
$logObject['releasedPhoneNumberCount'] = $phoneNumbers->count();
$settingObject['releasedPhoneNumberCount'] = $phoneNumbers->count();
Log::channel('disable_10dlc')->info("User is having total system phone numbers : " . $phoneNumbers->count());
$twilioPhoneNumbers = $phoneNumbers->whereIn('purchase_from', [SmsPhoneManager::FROM_TWILIO_3, SmsPhoneManager::FROM_TWILIO_2, SmsPhoneManager::FROM_TWILIO]);
$telinetPhoneNumbers = $phoneNumbers->where('purchase_from', SmsPhoneManager::FROM_TELINET);
$signalwirePhoneNumbers = $phoneNumbers->where('purchase_from', SmsPhoneManager::FROM_SIGNALWIRE);
if ($twilioPhoneNumbers->count() > 0) {
$this->closeSubAccountOfTwilio($user);
$isTwilioClosed = true;
}
if ($telinetPhoneNumbers->count() > 0) {
$this->releaseNumbersFromTelinet($telinetPhoneNumbers);
}
if ($signalwirePhoneNumbers->count() > 0) {
$this->releaseNumbersFromSignalwire($signalwirePhoneNumbers);
}
}
if ($campaigns->count() > 0) {
foreach ($campaigns as $campaign) {
switch ($campaign->provider_id) {
case SmsPhoneManager::FROM_SIGNALWIRE:
case SmsPhoneManager::FROM_TELINET:
$this->removeFromCSP($campaign);
break;
case SmsPhoneManager::FROM_TWILIO_3:
if (!$isTwilioClosed) {
$this->closeSubAccountOfTwilio($user);
$isTwilioClosed = true;
}
Log::channel('disable_10dlc')->info("Removed Campaign id / csp id : ", ['id' => $campaign->id, 'csp_id' => $campaign->csp_campaign_id]);
break;
}
//Deactivate Campaign from database and also delete
$campaign->update(['status' => UserCampaign::STATUS_DEACTIVATED_BY_USER]);
$settingObject['released_campaign_id'] = $campaign->id . "__" . $campaign->csp_campaign_id;
$campaign->delete();
}
} else {
$logObject['campaignReleasedFromCsp'] = 'NO';
Log::channel('disable_10dlc')->info("NO active campaign found in user!");
}
if ($brand) {
if (!in_array($brand->provider, [SmsPhoneManager::FROM_TWILIO_3])) {
CSPService::deleteBrand($brand->csp_brand_id);
} else {
if (!$isTwilioClosed) {
$this->closeSubAccountOfTwilio($user);
}
}
$logObject['brandReleased'] = 'YES | ' . $brand->profile_type == 1 ? "STANDARD(44)" : "STARTER(0)";
$settingObject['released_brand'] = $brand->csp_brand_id;
$settingObject['released_brand_type'] = $brand->profile_type == 1 ? "STANDARD(44)" : "STARTER(0)";
$brand->delete();
}
(new UserService())->userCommonSettings($user, $settingObject);
Log::channel('disable_10dlc')->info("User Successfully processed : ", $logObject);
$bar->advance();
}
}
public function getAllUsers($userIds = [])
{
$query = User::query();
if (!empty($userIds))
$query->whereIn('id', $userIds);
$query->where('user_type', 2);
$lastProcessingUser = Setting::query()->where('title', 'last_processing_user_id')->first();
if ($lastProcessingUser)
$query->where('id', '>=', $lastProcessingUser->description);
$query->orderBy('id');
return $query->cursor();
}
public function getSystemPhoneNumbersOfUser($userId)
{
$systemProviders = [
SmsPhoneManager::FROM_TELNYX_1,
SmsPhoneManager::FROM_TELNYX_2,
SmsPhoneManager::FROM_TWILIO,
SmsPhoneManager::FROM_INTELIQUENT,
SmsPhoneManager::FROM_TWILIO_2,
SmsPhoneManager::FROM_TWILIO_3,
SmsPhoneManager::FROM_TELNYX_3,
SmsPhoneManager::FROM_SIGNALWIRE,
SmsPhoneManager::FROM_PLIVO,
SmsPhoneManager::FROM_TELINET,
SmsPhoneManager::FROM_FLOWROUTE,
];
return SmsPhoneManager::query()->where('user_id', $userId)
->whereIn('purchase_from', $systemProviders)
->where('is_released', 1)
->where('release_log', 'like', '%complete_system_10dlc_disable%')
->get();
}
public function closeSubAccountOfTwilio($user)
{
$twilioSubAccount = TwilioBrandData::query()->where('user_id', $user->id)->first();
if($twilioSubAccount) {
(new TwilioService())->deleteSubAccountTwilio($twilioSubAccount->sub_account_sid);
Log::channel('disable_10dlc')->info("Close Twilio Sub-Account : " . $twilioSubAccount->sub_account_sid);
}
}
public function removeFromCSP($campaign)
{
CSPService::deActiveCampaign($campaign->csp_campaign_id);
Log::channel('disable_10dlc')->info("Removed Campaign id / csp id:", ['id' => $campaign->id, 'csp_id' => $campaign->csp_campaign_id]);
sleep(1);
}
public function releaseNumbersFromTelinet($phoneNumbers)
{
$token = config('params.telinet.telinet_api_key');
$apiUrl = config('params.telinet.telinet_api_base_url') . "user/dids/remove/bulk";
// Initialize the guzzle wrapper
$guzzleWrapper = resolve(GuzzleHttpWrapper::class);
$dids = [];
foreach ($phoneNumbers as $phoneNumber) {
$dids[] = str_replace('+1', '', $phoneNumber->purchased_number);
}
$body = [
'token' => $token,
'numbers' => json_encode($dids),
];
try {
$request = $guzzleWrapper->postGuzzleHttp($apiUrl, $body);
$result = json_decode($request);
foreach ($phoneNumbers as $phoneNumber) {
$phoneNumber->fill(['release_date' => Carbon::now()])->save();
}
Log::channel('telinet')->info('TELINET DISCONNECT - RESULT - DATA', ['data' => $result]);
} catch (\Exception $e) {
$this->failed($e->getCode());
}
}
public function releaseNumbersFromSignalwire($phoneNumbers)
{
$projectId = config('params.signalwire.project_id');
$token = config('params.signalwire.token');
$spaceURL = config('params.signalwire.space_url');
$signalWireClient = new SignalWireClient(
$projectId,
$token,
array(
'signalwireSpaceUrl' => $spaceURL
)
);
foreach ($phoneNumbers as $phoneNumber) {
$phone_data = SmsPhoneTransactionLog::where('phone_id', $phoneNumber->id)->where('order_id', '!=', 'recurring')->first();
try {
$difference = dateDifference($phoneNumber->purchase_date_time, date('Y-m-d H:i:s'));
$phoneNumber->timestamps = false;
if ($difference >= 15 && $phone_data) {
$signalWireClient->incomingPhoneNumbers($phone_data->order_id)->delete();
$phoneNumber->fill(['release_date' => Carbon::now()])->save();
}
} catch (\Exception $e) {
Log::channel('disable_10dlc')->info("Error Releasing SignalWire Number : " . $e->getMessage());
}
}
}
public function updateLastProcessingUserId($userId)
{
Setting::query()->updateOrCreate(
['title' => 'last_processing_user_id'],
[
'title' => 'last_processing_user_id',
'description' => $userId,
'editable' => true,
'is_deleted' => false
]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment