Merge remote-tracking branch 'origin/master' into oasis

# Conflicts:
#	app/Console/Commands/SetupDevEnvironment.php
#	app/Console/Kernel.php
#	app/Http/Resources/InvoiceResource.php
#	app/Http/Resources/UserResource.php
#	app/Models/User.php
#	composer.lock
#	config/app.php
#	config/custom-language-translations.php
#	config/language-translations.php
#	public/chunks/admin.js
#	public/chunks/app-language.js
#	public/chunks/dashboard.js
#	public/chunks/files.js
#	public/chunks/files~chunks/shared-files~chunks/shared/file-browser.js
#	public/chunks/files~chunks/shared-files~chunks/shared/file-browser~chunks/shared/single-file.js
#	public/chunks/invoices.js
#	public/chunks/pages.js
#	public/chunks/plan-subscribers.js
#	public/chunks/plans.js
#	public/chunks/platform.js
#	public/chunks/settings-invoices.js
#	public/chunks/settings-payment-methods.js
#	public/chunks/settings-subscription.js
#	public/chunks/shared-files.js
#	public/chunks/shared.js
#	public/chunks/shared/file-browser.js
#	public/chunks/user-invoices.js
#	public/chunks/user-subscription.js
#	public/chunks/users.js
#	public/js/main.js
#	public/mix-manifest.json
#	resources/js/components/FilesView/FileItemGrid.vue
#	resources/js/components/FilesView/FileItemList.vue
This commit is contained in:
Peter Papp
2021-04-29 11:06:14 +02:00
166 changed files with 2945 additions and 2876 deletions
+33 -48
View File
@@ -1,22 +1,12 @@
<?php
namespace App\Services;
use App;
use App\Models\Share;
use App\Models\File;
use App\Models\Folder;
use App\Http\Requests\FileFunctions\RenameItemRequest;
use App\Models\User;
use ByteUnits\Metric;
use Carbon\Carbon;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\Folder;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic as Image;
use Illuminate\Contracts\Routing\ResponseFactory;
use App\Http\Requests\FileFunctions\RenameItemRequest;
class DemoService
{
@@ -27,18 +17,18 @@ class DemoService
* @return array
* @throws \Exception
*/
function create_folder($request)
public function create_folder($request)
{
return [
'user_id' => 1,
'id' => Str::uuid(),
'parent_id' => random_int(1000, 9999),
'name' => $request->name,
'type' => 'folder',
'author' => $request->user() ? 'user' : 'visitor',
'items' => '0',
'color' => isset($request->icon['color']) ? $request->icon['color'] : null,
'emoji' => isset($request->icon['emoji']) ? $request->icon['emoji'] : null,
'user_id' => 1,
'id' => Str::uuid(),
'parent_id' => random_int(1000, 9999),
'name' => $request->name,
'type' => 'folder',
'author' => $request->user() ? 'user' : 'visitor',
'items' => '0',
'color' => isset($request->icon['color']) ? $request->icon['color'] : null,
'emoji' => isset($request->icon['emoji']) ? $request->icon['emoji'] : null,
'updated_at' => now()->format('j M Y \a\t H:i'),
'created_at' => now()->format('j M Y \a\t H:i'),
];
@@ -51,17 +41,14 @@ class DemoService
* @param $id
* @return mixed
*/
function rename_item($request, $id)
public function rename_item($request, $id)
{
// Get item
if ($request->type === 'folder') {
$item = Folder::where('id', $id)
->where('user_id', 1)
->first();
} else {
$item = File::where('id', $id)
->where('user_id', 1)
->first();
@@ -73,15 +60,13 @@ class DemoService
$item->color = $request->icon['color'] ?? null;
return $item;
} else {
return [
'id' => $request->id,
'name' => $request->name,
'type' => $request->type,
];
}
return [
'id' => $request->id,
'name' => $request->name,
'type' => $request->type,
];
}
/**
@@ -91,7 +76,7 @@ class DemoService
* @return array
* @throws \Exception
*/
function upload($request)
public function upload($request)
{
// File
$file = $request->file('file');
@@ -101,16 +86,16 @@ class DemoService
$filetype = get_file_type($file->getMimeType());
return [
'id' => Str::uuid(),
'folder_id' => $request->parent_id,
'thumbnail' => 'data:' . $request->file('file')->getMimeType() . ';base64, ' . base64_encode(file_get_contents($request->file('file'))),
'name' => $file->getClientOriginalName(),
'basename' => $filename,
'mimetype' => $file->getClientOriginalExtension(),
'filesize' => Metric::bytes($filesize)->format(),
'type' => $filetype,
'file_url' => 'https://vuefilemanager.hi5ve.digital/assets/vue-file-manager-preview.jpg',
'author' => $request->user() ? 'user' : 'visitor',
'id' => Str::uuid(),
'folder_id' => $request->parent_id,
'thumbnail' => 'data:' . $request->file('file')->getMimeType() . ';base64, ' . base64_encode(file_get_contents($request->file('file'))),
'name' => $file->getClientOriginalName(),
'basename' => $filename,
'mimetype' => $file->getClientOriginalExtension(),
'filesize' => Metric::bytes($filesize)->format(),
'type' => $filetype,
'file_url' => 'https://vuefilemanager.hi5ve.digital/assets/vue-file-manager-preview.jpg',
'author' => $request->user() ? 'user' : 'visitor',
'created_at' => now()->format('j M Y \a\t H:i'),
'updated_at' => now()->format('j M Y \a\t H:i'),
];
@@ -122,8 +107,8 @@ class DemoService
* @param $user
* @return ResponseFactory|\Illuminate\Http\Response
*/
function favourites($user)
public function favourites($user)
{
return $user->favouriteFolders->makeHidden(['pivot']);
}
}
}
+38 -53
View File
@@ -1,24 +1,22 @@
<?php
namespace App\Services;
use App\Models\Folder;
use App\Models\Share;
use App\Models\File as UserFile;
use App\Http\Requests\FileFunctions\RenameItemRequest;
use App\Models\User;
use App\Models\Zip;
use DB;
use App\Models\Zip;
use App\Models\User;
use App\Models\Share;
use App\Models\Folder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use App\Models\File as UserFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use League\Flysystem\FileNotFoundException;
use Madnest\Madzipper\Facades\Madzipper;
use League\Flysystem\FileNotFoundException;
use App\Http\Requests\FileFunctions\RenameItemRequest;
use Symfony\Component\HttpKernel\Exception\HttpException;
class FileManagerService
{
private $helper;
@@ -51,8 +49,7 @@ class FileManagerService
$disk_local = Storage::disk('local');
// Move file to local storage from external storage service
if (!is_storage_driver('local')) {
if (! is_storage_driver('local')) {
foreach ($files as $file) {
try {
$disk_local->put("temp/{$file['basename']}", Storage::get("files/$requested_folder->user_id/{$file['basename']}"));
@@ -70,7 +67,6 @@ class FileManagerService
// Add files to zip
foreach ($files as $file) {
$file_path = is_storage_driver('local')
? $disk_local->path("files/$requested_folder->user_id/{$file['basename']}")
: $disk_local->path("temp/{$file['basename']}");
@@ -84,8 +80,7 @@ class FileManagerService
$zip->close();
// Delete temporary files
if (!is_storage_driver('local')) {
if (! is_storage_driver('local')) {
foreach ($files as $file) {
$disk_local->delete('temp/' . $file['basename']);
}
@@ -93,9 +88,9 @@ class FileManagerService
// Store zip record
return Zip::create([
'user_id' => $shared->user_id ?? Auth::id(),
'user_id' => $shared->user_id ?? Auth::id(),
'shared_token' => $shared->token ?? null,
'basename' => $zip_name,
'basename' => $zip_name,
]);
}
@@ -113,8 +108,7 @@ class FileManagerService
$disk_local = Storage::disk('local');
// Move file to local storage from external storage service
if (!is_storage_driver('local')) {
if (! is_storage_driver('local')) {
$files->each(function ($file) use ($disk_local) {
try {
$disk_local->put("temp/$file->basename", Storage::get("files/$file->user_id/$file->basename"));
@@ -132,7 +126,6 @@ class FileManagerService
// Add files to zip
$files->each(function ($file) use ($zip, $disk_local) {
$file_path = is_storage_driver('local')
? $disk_local->path("files/$file->user_id/$file->basename")
: $disk_local->path("temp/$file->basename");
@@ -144,7 +137,7 @@ class FileManagerService
$zip->close();
// Delete temporary files
if (!is_storage_driver('local')) {
if (! is_storage_driver('local')) {
$files->each(function ($file) use ($disk_local) {
$disk_local->delete("temp/$file->basename");
});
@@ -152,9 +145,9 @@ class FileManagerService
// Store zip record
return Zip::create([
'user_id' => $shared->user_id ?? Auth::id(),
'user_id' => $shared->user_id ?? Auth::id(),
'shared_token' => $shared->token ?? null,
'basename' => $zip_name,
'basename' => $zip_name,
]);
}
@@ -169,12 +162,12 @@ class FileManagerService
{
return Folder::create([
'parent_id' => $request->parent_id,
'author' => $shared ? 'visitor' : 'user',
'user_id' => $shared ? $shared->user_id : Auth::id(),
'name' => $request->name,
'color' => $request->color ?? null,
'emoji' => $request->emoji ?? null,
]);;
'author' => $shared ? 'visitor' : 'user',
'user_id' => $shared ? $shared->user_id : Auth::id(),
'name' => $request->name,
'color' => $request->color ?? null,
'emoji' => $request->emoji ?? null,
]);
}
/**
@@ -196,7 +189,7 @@ class FileManagerService
// Rename item
$item->update([
'name' => $request->name
'name' => $request->name,
]);
// Return updated item
@@ -215,7 +208,6 @@ class FileManagerService
{
// Delete folder
if ($item['type'] === 'folder') {
// Get folder
$folder = Folder::withTrashed()
->with('folders')
@@ -237,15 +229,13 @@ class FileManagerService
->delete();
// Soft delete items
if (!$item['force_delete']) {
if (! $item['force_delete']) {
// Soft delete folder record
$folder->delete();
}
// Force delete children files
if ($item['force_delete']) {
// Get children folder ids
$child_folders = filter_folders_ids($folder->trashed_folders, 'id');
@@ -256,7 +246,6 @@ class FileManagerService
// Remove all children files
foreach ($files as $file) {
// Delete file
Storage::delete("/files/$file->user_id/$file->basename");
@@ -278,7 +267,6 @@ class FileManagerService
// Delete item
if ($item['type'] !== 'folder') {
// Get file
$file = UserFile::withTrashed()
->find($id);
@@ -295,7 +283,6 @@ class FileManagerService
// Force delete file
if ($item['force_delete']) {
// Delete file
Storage::delete("/files/$file->user_id/$file->basename");
@@ -311,8 +298,7 @@ class FileManagerService
}
// Soft delete file
if (!$item['force_delete']) {
if (! $item['force_delete']) {
// Soft delete file
$file->delete();
}
@@ -328,10 +314,8 @@ class FileManagerService
public function move($request, $to_id)
{
foreach ($request->items as $item) {
// Move folder
if ($item['type'] === 'folder') {
Folder::find($item['id'])
->update(['parent_id' => $to_id]);
}
@@ -375,11 +359,12 @@ class FileManagerService
$limit = get_setting('upload_limit');
// File size handling
if ($limit && $file_size > format_bytes($limit)) abort(413);
if ($limit && $file_size > format_bytes($limit)) {
abort(413);
}
// If last then process file
if ($request->boolean('is_last')) {
$metadata = get_image_meta_data($file);
$disk_local = Storage::disk('local');
@@ -402,7 +387,7 @@ class FileManagerService
$disk_local->move("chunks/$temp_filename", "files/$user_id/$disk_file_name");
// Move files to external storage
if (!is_storage_driver(['local'])) {
if (! is_storage_driver(['local'])) {
$this->helper->move_file_to_external_storage($disk_file_name, $user_id);
}
@@ -412,16 +397,16 @@ class FileManagerService
// Return new file
return UserFile::create([
'mimetype' => get_file_type_from_mimetype($file_mimetype),
'type' => get_file_type($file_mimetype),
'mimetype' => get_file_type_from_mimetype($file_mimetype),
'type' => get_file_type($file_mimetype),
'folder_id' => $request->folder_id,
'metadata' => $metadata,
'name' => $user_file_name,
'basename' => $disk_file_name,
'author' => $shared ? 'visitor' : 'user',
'metadata' => $metadata,
'name' => $user_file_name,
'basename' => $disk_file_name,
'author' => $shared ? 'visitor' : 'user',
'thumbnail' => $thumbnail,
'filesize' => $file_size,
'user_id' => $user_id,
'filesize' => $file_size,
'user_id' => $user_id,
]);
}
}
@@ -461,4 +446,4 @@ class FileManagerService
]);
}
}
}
}
+31 -38
View File
@@ -1,16 +1,15 @@
<?php
namespace App\Services;
use App\Models\File;
use App\Models\Folder;
use App\Models\Share;
use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use DB;
use App\Models\File;
use App\Models\Share;
use App\Models\Folder;
use Illuminate\Support\Arr;
use Aws\S3\MultipartUploader;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Aws\Exception\MultipartUploadException;
use Intervention\Image\ImageManagerStatic as Image;
use Symfony\Component\HttpKernel\Exception\HttpException;
@@ -43,7 +42,7 @@ class HelperService
/**
* Check access to requested directory
*
* @param integer|array $requested_id
* @param int|array $requested_id
* @param string $shared Shared record detail
*/
public function check_item_access($requested_id, $shared)
@@ -60,14 +59,16 @@ class HelperService
// Check user access
if (is_array($requested_id)) {
foreach ($requested_id as $id) {
if (!in_array($id, $accessible_folder_ids))
if (! in_array($id, $accessible_folder_ids)) {
abort(403);
}
}
}
if (!is_array($requested_id)) {
if (!in_array($requested_id, $accessible_folder_ids))
if (! is_array($requested_id)) {
if (! in_array($requested_id, $accessible_folder_ids)) {
abort(403);
}
}
}
@@ -106,7 +107,6 @@ class HelperService
// Check if user can upload
if (get_setting('storage_limitation') && $user_storage_used >= 100) {
// Delete file
Storage::disk('local')
->delete("chunks/$temp_filename");
@@ -123,7 +123,7 @@ class HelperService
* @param string $file
* @param string $user_id
*/
function move_file_to_external_storage($file, $user_id): void
public function move_file_to_external_storage($file, $user_id): void
{
$disk_local = Storage::disk('local');
@@ -132,7 +132,6 @@ class HelperService
// If file is bigger than 5.2MB then run multipart upload
if ($filesize > 5242880) {
// Get driver
$driver = \Storage::getDriver();
@@ -146,16 +145,13 @@ class HelperService
// TODO: replace local files with temp folder
$uploader = new MultipartUploader($client, config('filesystems.disks.local.root') . "/files/$user_id/$file", [
'bucket' => $adapter->getBucket(),
'key' => "/files/$user_id/$file"
'key' => "/files/$user_id/$file",
]);
try {
// Upload content
$uploader->upload();
} catch (MultipartUploadException $e) {
// Write error log
Log::error($e->getMessage());
@@ -164,12 +160,10 @@ class HelperService
throw new HttpException(409, $e->getMessage());
}
} else {
// Stream file object to s3
// TODO: replace local files with temp folder
Storage::putFileAs("files/$user_id", config('filesystems.disks.local.root') . "/files/$user_id/$file", $file, "private");
Storage::putFileAs("files/$user_id", config('filesystems.disks.local.root') . "/files/$user_id/$file", $file, 'private');
}
// Delete file after upload
@@ -184,11 +178,10 @@ class HelperService
* @param string $user_id
* @return string|null
*/
function create_image_thumbnail($file_path, $filename, $user_id)
public function create_image_thumbnail($file_path, $filename, $user_id)
{
// Create thumbnail from image
if (in_array(Storage::disk('local')->mimeType($file_path), ['image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/webp'])) {
// Get thumbnail name
$thumbnail = "thumbnail-$filename";
@@ -207,7 +200,6 @@ class HelperService
// Return thumbnail as svg file
if (Storage::disk('local')->mimeType($file_path) === 'image/svg+xml') {
$thumbnail = $filename;
}
@@ -221,13 +213,13 @@ class HelperService
* @param $user_id
* @return mixed
*/
function download_file($file, $user_id)
public function download_file($file, $user_id)
{
// Get file path
$path = "files/$user_id/$file->basename";
// Check if file exist
if (!Storage::exists($path)) {
if (! Storage::exists($path)) {
abort(404);
}
@@ -236,11 +228,11 @@ class HelperService
return response()
->download(Storage::path($path), $pretty_name, [
"Accept-Ranges" => "bytes",
"Content-Type" => Storage::mimeType($path),
"Content-Length" => Storage::size($path),
"Content-Range" => "bytes 0-600/" . Storage::size($path),
"Content-Disposition" => "attachment; filename=$pretty_name",
'Accept-Ranges' => 'bytes',
'Content-Type' => Storage::mimeType($path),
'Content-Length' => Storage::size($path),
'Content-Range' => 'bytes 0-600/' . Storage::size($path),
'Content-Disposition' => "attachment; filename=$pretty_name",
]);
}
@@ -251,13 +243,15 @@ class HelperService
* @param $user_id
* @return mixed
*/
function download_thumbnail_file($file, $user_id)
public function download_thumbnail_file($file, $user_id)
{
// Get file path
$path = "/files/$user_id/{$file->getRawOriginal('thumbnail')}";
// Check if file exist
if (!Storage::exists($path)) abort(404);
if (! Storage::exists($path)) {
abort(404);
}
// Return image thumbnail
return Storage::download($path, $file->getRawOriginal('thumbnail'));
@@ -270,7 +264,7 @@ class HelperService
* @param $shared
* @return array
*/
function get_items_under_shared_by_folder_id($id, $shared): array
public function get_items_under_shared_by_folder_id($id, $shared): array
{
$folders = Folder::where('user_id', $shared->user_id)
->where('parent_id', $id)
@@ -288,13 +282,12 @@ class HelperService
/**
* @param Share $shared
*/
function check_protected_share_record(Share $shared): void
public function check_protected_share_record(Share $shared): void
{
if ($shared->is_protected) {
$abort_message = "Sorry, you don't have permission";
if (!request()->hasCookie('share_session')) {
if (! request()->hasCookie('share_session')) {
abort(403, $abort_message);
}
@@ -309,9 +302,9 @@ class HelperService
}
// Check if share record was authenticated previously via ShareController@authenticate
if (!$share_session->authenticated) {
if (! $share_session->authenticated) {
abort(403, $abort_message);
}
}
}
}
}
+20 -24
View File
@@ -1,12 +1,9 @@
<?php
namespace App\Services;
use DB;
use App\Models\Language;
use App\Models\LanguageTranslation;
use DB;
class LanguageService
{
@@ -14,26 +11,26 @@ class LanguageService
* @param $license
* @param $locale
*/
function create_default_language_translations($license, $locale)
public function create_default_language_translations($license, $locale)
{
$translations = [
'extended' => collect([
config("language-translations.extended"),
config("language-translations.regular"),
config("custom-language-translations")
config('language-translations.extended'),
config('language-translations.regular'),
config('custom-language-translations'),
])->collapse(),
'regular' => collect([
config("language-translations.regular"),
config("custom-language-translations")
'regular' => collect([
config('language-translations.regular'),
config('custom-language-translations'),
])->collapse(),
];
$translations = $translations[strtolower($license)]
->map(function ($value, $key) use ($locale) {
return [
'lang' => $locale,
'lang' => $locale,
'value' => $value,
'key' => $key,
'key' => $key,
];
})->toArray();
@@ -45,7 +42,7 @@ class LanguageService
* Find newly added translations in default language
* translations file and insert it into database
*/
function upgrade_language_translations()
public function upgrade_language_translations()
{
// Get all app locales
$locales = Language::all()
@@ -57,13 +54,13 @@ class LanguageService
$default_translations = [
'extended' => collect([
config("language-translations.extended"),
config("language-translations.regular"),
config("custom-language-translations")
config('language-translations.extended'),
config('language-translations.regular'),
config('custom-language-translations'),
])->collapse(),
'regular' => collect([
config("language-translations.regular"),
config("custom-language-translations")
'regular' => collect([
config('language-translations.regular'),
config('custom-language-translations'),
])->collapse(),
];
@@ -75,13 +72,12 @@ class LanguageService
// Store new translations for every language
$locales->each(function ($locale) use ($newbies) {
$translations = $newbies
->map(function ($value, $key) use ($locale) {
return [
'lang' => $locale,
'lang' => $locale,
'value' => $value,
'key' => $key,
'key' => $key,
];
})->toArray();
@@ -93,4 +89,4 @@ class LanguageService
cache()->forget("language-translations-$locale");
});
}
}
}
+4 -11
View File
@@ -1,12 +1,9 @@
<?php
namespace App\Services;
use App\Models\Share;
use App\Models\Zip;
use Carbon\Carbon;
use App\Models\Zip;
use App\Models\Share;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
@@ -20,7 +17,6 @@ class SchedulerService
Zip::where('created_at', '<=', now()->subDay()->toDateTimeString())
->get()
->each(function ($zip) {
// Delete zip file
\Storage::disk('local')->delete("zip/$zip->basename");
@@ -37,7 +33,6 @@ class SchedulerService
Share::whereNotNull('expire_in')
->get()
->each(function ($share) {
// Get dates
$created_at = Carbon::parse($share->created_at);
@@ -58,11 +53,10 @@ class SchedulerService
// Get all files from storage
$files = collect([
//$local_disk->allFiles('files'),
$local_disk->allFiles('chunks')
$local_disk->allFiles('chunks'),
])->collapse();
$files->each(function ($file) use ($local_disk) {
// Get the file's last modification time.
$last_modified = $local_disk
->lastModified($file);
@@ -73,7 +67,6 @@ class SchedulerService
// Delete if file is in local storage more than 24 hours
if ($diff >= 24) {
Log::info("Failed file or chunk $file deleted.");
// Delete file from local storage
@@ -81,4 +74,4 @@ class SchedulerService
}
});
}
}
}
+5 -7
View File
@@ -1,10 +1,9 @@
<?php
namespace App\Services;
use App\Models\Language;
use App\Models\Page;
use App\Models\Setting;
use App\Models\Language;
use Illuminate\Support\Facades\Storage;
class SetupService
@@ -16,7 +15,6 @@ class SetupService
{
collect(['avatars', 'chunks', 'system', 'files', 'temp', 'zip'])
->each(function ($directory) {
// Create directory for local driver
Storage::disk('local')
->makeDirectory($directory);
@@ -58,13 +56,13 @@ class SetupService
public function seed_default_language()
{
Language::create([
'name' => 'English',
'locale' => 'en'
'name' => 'English',
'locale' => 'en',
]);
Setting::create([
'name' => 'language',
'name' => 'language',
'value' => 'en',
]);
}
}
}
+45 -64
View File
@@ -1,16 +1,14 @@
<?php
namespace App\Services;
use Stripe;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Laravel\Cashier\Cashier;
use Illuminate\Support\Facades\Cache;
use Laravel\Cashier\Exceptions\IncompletePayment;
use Laravel\Cashier\Exceptions\PaymentActionRequired;
use Stripe;
use Symfony\Component\HttpKernel\Exception\HttpException;
class StripeService
@@ -61,18 +59,19 @@ class StripeService
$rates_public = [];
foreach ($this->getTaxRates() as $rate) {
// Continue when is not active
if (!$rate['active']) continue;
if (! $rate['active']) {
continue;
}
// Calculate tax
$tax = $amount * ($rate['percentage'] / 100);
array_push($rates_public, [
'id' => $rate['id'],
'active' => $rate['active'],
'country' => $rate['country'],
'percentage' => $rate['percentage'],
'id' => $rate['id'],
'active' => $rate['active'],
'country' => $rate['country'],
'percentage' => $rate['percentage'],
'plan_price_formatted' => Cashier::formatAmount(round($amount + $tax)),
]);
}
@@ -90,8 +89,7 @@ class StripeService
public function getOrSetDefaultPaymentMethod($request, $user)
{
// Check payment method
if (!$request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
if (! $request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
// Get default payment
return $user->defaultPaymentMethod()->paymentMethod;
}
@@ -99,23 +97,18 @@ class StripeService
// Clear cached payment methods
cache_forget_many([
'payment-methods-user-' . $user->id,
'default-payment-methods-user-' . $user->id
'default-payment-methods-user-' . $user->id,
]);
if ($request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
// Set new payment
return $user->addPaymentMethod($request->input('payment.meta.pm'))->paymentMethod;
} else if ($request->has('payment.meta.pm') && !$user->hasDefaultPaymentMethod()) {
} elseif ($request->has('payment.meta.pm') && ! $user->hasDefaultPaymentMethod()) {
// Set new payment
return $user->updateDefaultPaymentMethod($request->input('payment.meta.pm'))->paymentMethod;
} else {
throw new HttpException(400, 'Something went wrong.');
}
throw new HttpException(400, 'Something went wrong.');
}
/**
@@ -130,7 +123,7 @@ class StripeService
// Clear cached payment methods
cache_forget_many([
'payment-methods-user-' . $user->id,
'default-payment-methods-user-' . $user->id
'default-payment-methods-user-' . $user->id,
]);
// Set new payment method
@@ -153,33 +146,25 @@ class StripeService
public function createOrReplaceSubscription($request, $user)
{
try {
// Get payment method
$paymentMethod = $this->getOrSetDefaultPaymentMethod($request, $user);
// Check if user have subscription
if ($user->subscribed('main')) {
// Change subscription plan
$user->subscription('main')->skipTrial()->swap($request->input('plan.data.id'));
} else {
// Create subscription
$user->newSubscription('main', $request->input('plan.data.id'))->create($paymentMethod);
}
} catch (IncompletePayment $exception) {
if ($exception instanceof PaymentActionRequired) {
$cashier_route = route('cashier.payment', [$exception->payment->id, 'redirect' => url('/settings/subscription')]);
throw new HttpException(402, $cashier_route);
} else {
throw new HttpException(400, $exception->getMessage());
}
throw new HttpException(400, $exception->getMessage());
}
}
@@ -191,18 +176,18 @@ class StripeService
public function updateCustomerDetails($user)
{
$user->updateStripeCustomer([
'name' => $user->settings->name,
'phone' => $user->settings->phone_number,
'name' => $user->settings->name,
'phone' => $user->settings->phone_number,
'address' => [
'line1' => $user->settings->address,
'city' => $user->settings->city,
'country' => $user->settings->country,
'line1' => $user->settings->address,
'city' => $user->settings->city,
'country' => $user->settings->country,
'postal_code' => $user->settings->postal_code,
'state' => $user->settings->state,
'state' => $user->settings->state,
],
'preferred_locales' => [
$user->settings->country, 'en'
]
$user->settings->country, 'en',
],
]);
}
@@ -220,14 +205,13 @@ class StripeService
$plans = [];
foreach ($stripe_plans['data'] as $plan) {
// Get stripe product
$product = $this->stripe->products()->find($plan['product']);
// Push data to $plan container
if ($product['active'] && isset($product['metadata']['capacity'])) {
array_push($plans, [
'plan' => $plan,
'plan' => $plan,
'product' => $product,
]);
}
@@ -250,16 +234,14 @@ class StripeService
$plans = [];
foreach ($stripe_plans['data'] as $plan) {
if ($plan['active']) {
// Get stripe product
$product = $this->stripe->products()->find($plan['product']);
// Push data to $plan container
if ($product['active'] && isset($product['metadata']['capacity'])) {
array_push($plans, [
'plan' => $plan,
'plan' => $plan,
'product' => $product,
]);
}
@@ -282,12 +264,11 @@ class StripeService
}
return Cache::rememberForever("plan-$id", function () use ($id) {
$plan = $this->stripe->plans()->find($id);
$product = $this->stripe->products()->find($plan['product']);
return [
'plan' => $plan,
'plan' => $plan,
'product' => $product,
];
});
@@ -303,34 +284,34 @@ class StripeService
{
if ($data instanceof Request) {
$plan = [
'name' => $data->input('attributes.name'),
'name' => $data->input('attributes.name'),
'description' => $data->input('attributes.description'),
'price' => $data->input('attributes.price'),
'capacity' => $data->input('attributes.capacity'),
'price' => $data->input('attributes.price'),
'capacity' => $data->input('attributes.capacity'),
];
} else {
$plan = [
'name' => $data['attributes']['name'],
'name' => $data['attributes']['name'],
'description' => $data['attributes']['description'],
'price' => $data['attributes']['price'],
'capacity' => $data['attributes']['capacity'],
'price' => $data['attributes']['price'],
'capacity' => $data['attributes']['capacity'],
];
}
$product = $this->stripe->products()->create([
'name' => $plan['name'],
'name' => $plan['name'],
'description' => $plan['description'],
'metadata' => [
'capacity' => $plan['capacity']
]
'metadata' => [
'capacity' => $plan['capacity'],
],
]);
$plan = $this->stripe->plans()->create([
'id' => Str::slug($plan['name']),
'amount' => $plan['price'],
'id' => Str::slug($plan['name']),
'amount' => $plan['price'],
'currency' => config('cashier.currency'),
'interval' => 'month',
'product' => $product['id'],
'product' => $product['id'],
]);
return compact('plan', 'product');
@@ -351,13 +332,14 @@ class StripeService
// Update product
if (in_array($request->name, $product_colls)) {
if ($request->name === 'capacity') {
$this->stripe->products()->update($plan['product'], ['metadata' => ['capacity' => $request->value]]);
}
if ($request->name === 'name') {
$this->stripe->products()->update($plan['product'], ['name' => $request->value]);
}
if ($request->name === 'description') {
$this->stripe->products()->update($plan['product'], ['description' => $request->value]);
}
@@ -365,7 +347,6 @@ class StripeService
// Update plan
if (in_array($request->name, $plan_colls)) {
if ($request->name === 'is_active') {
$this->stripe->plans()->update($id, ['active' => $request->value]);
}
@@ -422,7 +403,7 @@ class StripeService
->stripe
->invoices()
->all([
'limit' => 20
'limit' => 20,
]);
}
}
}