Remove migration codepaths

This commit is contained in:
David Bomba
2026-04-14 10:08:12 +10:00
parent 1a9306eb2b
commit a8455d9a48
5 changed files with 45 additions and 483 deletions

View File

@@ -12,6 +12,7 @@
namespace App\Helpers\Cache;
use App\Utils\Ninja;
use Illuminate\Contracts\Redis\Factory as RedisFactory;
use Illuminate\Support\Facades\Cache;
@@ -21,6 +22,10 @@ class Atomic
{
$new_ttl = now()->addSeconds($ttl);
if (!Ninja::isHosted()) {
return Cache::add($key, $value, $new_ttl) ? true : false;
}
try {
/** @var RedisFactory $redis */
$redis = app('redis');
@@ -33,6 +38,10 @@ class Atomic
public static function get(string $key): mixed
{
if (!Ninja::isHosted()) {
return Cache::get($key);
}
try {
/** @var RedisFactory $redis */
$redis = app('redis');
@@ -44,6 +53,10 @@ class Atomic
public static function del(string $key): mixed
{
if (!Ninja::isHosted()) {
return Cache::forget($key);
}
try {
/** @var RedisFactory $redis */
$redis = app('redis');

View File

@@ -1,451 +0,0 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2026. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Controllers;
use App\Console\Commands\ImportMigrations;
use App\DataMapper\CompanySettings;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\StartMigration;
use App\Mail\ExistingMigration;
use App\Mail\Migration\MaxCompanies;
use App\Models\Company;
use App\Models\CompanyToken;
use App\Utils\Ninja;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
class MigrationController extends BaseController
{
use DispatchesJobs;
public bool $silent_migration = false;
public function __construct()
{
parent::__construct();
}
/**
* Purge Company.
*
* @OA\Post(
* path="/api/v1/migration/purge/{company}",
* operationId="postPurgeCompany",
* tags={"migration"},
* summary="Attempts to purge a company record and all its child records",
* description="Attempts to purge a company record and all its child records",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(
* name="company",
* in="path",
* description="The Company Hashed ID",
* example="D2J234DFA",
* required=true,
* @OA\Schema(
* type="string",
* format="string",
* ),
* ),
* @OA\Response(
* response=200,
* description="Success",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param Company $company
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
* @throws \Exception
*/
public function purgeCompany(Company $company)
{
if (Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id) {
return response()->json(['message' => 'Cannot purge this company'], 400);
}
$account = $company->account;
$company_id = $company->id;
$company->delete();
/*Update the new default company if necessary*/
if ($company_id == $account->default_company_id && $account->companies->count() >= 1) {
$new_default_company = $account->companies->first();
if ($new_default_company) {
$account->default_company_id = $new_default_company->id;
$account->save();
}
}
return response()->json(['message' => 'Company purged'], 200);
}
private function purgeCompanyWithForceFlag(Company $company)
{
if (Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id) {
return response()->json(['message' => 'Cannot purge this company'], 400);
}
$account = $company->account;
$company_id = $company->id;
$company->delete();
/*Update the new default company if necessary*/
if ($company_id == $account->default_company_id && $account->companies->count() >= 1) {
$new_default_company = $account->companies->first();
if ($new_default_company) {
$account->default_company_id = $new_default_company->id;
$account->save();
}
}
}
/**
* Purge Company but save settings.
*
* @OA\Post(
* path="/api/v1/migration/purge_save_settings/{company}",
* operationId="postPurgeCompanySaveSettings",
* tags={"migration"},
* summary="Attempts to purge a companies child records but save the company record and its settings",
* description="Attempts to purge a companies child records but save the company record and its settings",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(
* name="company",
* in="path",
* description="The Company Hashed ID",
* example="D2J234DFA",
* required=true,
* @OA\Schema(
* type="string",
* format="string",
* ),
* ),
* @OA\Response(
* response=200,
* description="Success",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param Request $request
* @param Company $company
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
*/
public function purgeCompanySaveSettings(Request $request, Company $company)
{
$company->clients()->forceDelete();
$company->products()->forceDelete();
$company->projects()->forceDelete();
$company->tasks()->forceDelete();
$company->vendors()->forceDelete();
$company->expenses()->forceDelete();
$company->purchase_orders()->forceDelete();
$company->bank_transaction_rules()->forceDelete();
$company->bank_transactions()->forceDelete();
// $company->bank_integrations()->forceDelete();
$company->all_activities()->forceDelete();
$settings = $company->settings;
/* Reset all counters to 1 after a purge */
$settings->recurring_invoice_number_counter = 1;
$settings->invoice_number_counter = 1;
$settings->quote_number_counter = 1;
$settings->client_number_counter = 1;
$settings->credit_number_counter = 1;
$settings->task_number_counter = 1;
$settings->expense_number_counter = 1;
$settings->recurring_expense_number_counter = 1;
$settings->recurring_quote_number_counter = 1;
$settings->vendor_number_counter = 1;
$settings->ticket_number_counter = 1;
$settings->payment_number_counter = 1;
$settings->project_number_counter = 1;
$settings->purchase_order_number_counter = 1;
$company->settings = $settings;
$company->save();
return response()->json(['message' => 'Settings preserved'], 200);
}
/**
* Start the migration from V1.
*
* @OA\Post(
* path="/api/v1/migration/start",
* operationId="postStartMigration",
* tags={"migration"},
* summary="Starts the migration from previous version of Invoice Ninja",
* description="Starts the migration from previous version of Invoice Ninja",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/X-API-PASSWORD"),
* @OA\Parameter(
* name="migration",
* in="query",
* description="The migraton file",
* example="migration.zip",
* required=true,
* @OA\Schema(
* type="object",
* format="file",
* ),
* ),
* @OA\Response(
* response=200,
* description="Success",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param Request $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|void
*/
public function startMigration(Request $request)
{
nlog('Starting Migration');
if ($request->has('silent_migration')) {
$this->silent_migration = true;
}
if ($request->companies) {
//handle Laravel 5.5 UniHTTP
$companies = json_decode($request->companies, true);
} else {
//handle Laravel 6 Guzzle
$companies = [];
foreach ($request->all() as $input) {
if ($input instanceof UploadedFile) {
} else {
$companies[] = json_decode($input, true);
}
}
}
foreach ($companies as $company) {
if (! is_array($company)) {
continue;
}
$company = (array) $company;
$user = auth()->user();
$company_count = $user->account->companies()->count();
$fresh_company = false;
// Look for possible existing company (based on company keys).
$existing_company = Company::query()->whereRaw('BINARY `company_key` = ?', [$company['company_key']])->first();
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($user->account->companies()->first()->settings));
App::setLocale($user->account->companies()->first()->getLocale());
if (! $existing_company && $company_count >= 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if (!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
} elseif ($existing_company && $company_count > 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if (!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
}
$checks = [
'existing_company' => $existing_company ? (bool) 1 : false,
'force' => array_key_exists('force', $company) ? (bool) $company['force'] : false,
];
// If there's existing company and ** no ** force is provided - skip migration.
if ($checks['existing_company'] == true && $checks['force'] == false) {
nlog('Migrating: Existing company without force. (CASE_01)');
$nmo = new NinjaMailerObject();
$nmo->mailable = new ExistingMigration($existing_company);
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first();
$nmo->to_user = $user;
if (!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
}
// If there's existing company and force ** is provided ** - purge the company and migrate again.
if ($checks['existing_company'] == true && $checks['force'] == true) {
nlog('purging the existing company here');
$this->purgeCompanyWithForceFlag($existing_company);
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$account->default_company_id = $fresh_company->id;
$account->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
// If there's no existing company migrate just normally.
if ($checks['existing_company'] == false) {
nlog('creating fresh company');
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
$migration_file = $request->file($company['company_index'])
->storeAs(
'migrations',
$request->file($company['company_index'])->getClientOriginalName(),
'public'
);
if (app()->environment() == 'testing') {
nlog('environment is testing = bailing out now');
return;
}
nlog('starting migration job');
nlog($migration_file);
if (Ninja::isHosted()) {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration)->onQueue('migration');
} else {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration);
}
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
}
}

View File

@@ -44,6 +44,13 @@ class UploadMigrationFileRequest extends Request
$rules['migration'] = ['required', 'file', 'mimes:zip'];
}
// Validate all uploaded files are zip archives
foreach ($this->allFiles() as $key => $file) {
if (app()->environment() !== 'testing') {
$rules[$key] = ['file', 'mimes:zip'];
}
}
return $rules;
}
}

51
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "60e926dbeffcbb5209476e7dfb73e541",
"content-hash": "eea5d68e79fe44b71abfaf94c9418652",
"packages": [
{
"name": "apimatic/core",
@@ -384,16 +384,16 @@
},
{
"name": "aws/aws-sdk-php",
"version": "3.378.2",
"version": "3.379.0",
"source": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-php.git",
"reference": "df2a6c362ddce2ede3ac3a8286f5788847e614b4"
"reference": "a50c3cc2c59f5ebeb56cbe170e6f144034b252b6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/df2a6c362ddce2ede3ac3a8286f5788847e614b4",
"reference": "df2a6c362ddce2ede3ac3a8286f5788847e614b4",
"url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/a50c3cc2c59f5ebeb56cbe170e6f144034b252b6",
"reference": "a50c3cc2c59f5ebeb56cbe170e6f144034b252b6",
"shasum": ""
},
"require": {
@@ -475,9 +475,9 @@
"support": {
"forum": "https://github.com/aws/aws-sdk-php/discussions",
"issues": "https://github.com/aws/aws-sdk-php/issues",
"source": "https://github.com/aws/aws-sdk-php/tree/3.378.2"
"source": "https://github.com/aws/aws-sdk-php/tree/3.379.0"
},
"time": "2026-04-10T18:13:27+00:00"
"time": "2026-04-13T18:11:10+00:00"
},
{
"name": "babenkoivan/elastic-adapter",
@@ -9878,27 +9878,26 @@
},
{
"name": "predis/predis",
"version": "v3.4.2",
"version": "v2.4.1",
"source": {
"type": "git",
"url": "https://github.com/predis/predis.git",
"reference": "2033429520d8997a7815a2485f56abe6d2d0e075"
"reference": "07105e050622ed80bd60808367ced9e379f31530"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/predis/predis/zipball/2033429520d8997a7815a2485f56abe6d2d0e075",
"reference": "2033429520d8997a7815a2485f56abe6d2d0e075",
"url": "https://api.github.com/repos/predis/predis/zipball/07105e050622ed80bd60808367ced9e379f31530",
"reference": "07105e050622ed80bd60808367ced9e379f31530",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0",
"psr/http-message": "^1.0|^2.0"
"php": "^7.2 || ^8.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.3",
"phpstan/phpstan": "^1.9",
"phpunit/phpcov": "^6.0 || ^8.0",
"phpunit/phpunit": "^8.0 || ~9.4.4"
"phpunit/phpunit": "^8.0 || ^9.4"
},
"suggest": {
"ext-relay": "Faster connection with in-memory caching (>=0.6.2)"
@@ -9929,7 +9928,7 @@
],
"support": {
"issues": "https://github.com/predis/predis/issues",
"source": "https://github.com/predis/predis/tree/v3.4.2"
"source": "https://github.com/predis/predis/tree/v2.4.1"
},
"funding": [
{
@@ -9937,7 +9936,7 @@
"type": "github"
}
],
"time": "2026-03-09T20:33:04+00:00"
"time": "2025-11-12T18:00:11+00:00"
},
{
"name": "psr/cache",
@@ -18735,16 +18734,16 @@
},
{
"name": "larastan/larastan",
"version": "v3.9.4",
"version": "v3.9.5",
"source": {
"type": "git",
"url": "https://github.com/larastan/larastan.git",
"reference": "41db11d7d6417e7164482252c380bdc03fc41397"
"reference": "aa637ef3c9102490e0fa9a7ea4fbdbbce4471f34"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/larastan/larastan/zipball/41db11d7d6417e7164482252c380bdc03fc41397",
"reference": "41db11d7d6417e7164482252c380bdc03fc41397",
"url": "https://api.github.com/repos/larastan/larastan/zipball/aa637ef3c9102490e0fa9a7ea4fbdbbce4471f34",
"reference": "aa637ef3c9102490e0fa9a7ea4fbdbbce4471f34",
"shasum": ""
},
"require": {
@@ -18813,7 +18812,7 @@
],
"support": {
"issues": "https://github.com/larastan/larastan/issues",
"source": "https://github.com/larastan/larastan/tree/v3.9.4"
"source": "https://github.com/larastan/larastan/tree/v3.9.5"
},
"funding": [
{
@@ -18821,7 +18820,7 @@
"type": "github"
}
],
"time": "2026-04-02T07:08:56+00:00"
"time": "2026-04-11T20:10:30+00:00"
},
{
"name": "laravel/boost",
@@ -19490,11 +19489,11 @@
},
{
"name": "phpstan/phpstan",
"version": "2.1.46",
"version": "2.1.47",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"reference": "a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/79015445d8bd79e62b29140f12e5bfced1dcca65",
"reference": "79015445d8bd79e62b29140f12e5bfced1dcca65",
"shasum": ""
},
"require": {
@@ -19539,7 +19538,7 @@
"type": "github"
}
],
"time": "2026-04-01T09:25:14+00:00"
"time": "2026-04-13T15:49:08+00:00"
},
{
"name": "phpunit/php-code-coverage",

View File

@@ -307,12 +307,6 @@ Route::group(['middleware' => ['throttle:api', 'token_auth', 'valid_json','local
Route::post('logout', [LogoutController::class, 'index'])->name('logout');
Route::post('migrate', [MigrationController::class, 'index'])->name('migrate.start');
Route::post('migration/purge/{company}', [MigrationController::class, 'purgeCompany'])->middleware('password_protected');
Route::post('migration/purge_save_settings/{company}', [MigrationController::class, 'purgeCompanySaveSettings'])->middleware('password_protected');
Route::post('migration/start', [MigrationController::class, 'startMigration']);
Route::post('one_time_token', [OneTimeTokenController::class, 'create']);
Route::resource('payments', PaymentController::class); // name = (payments. index / create / show / update / destroy / edit