diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 96701be..328eccf 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_name/:package_name/discussions/new?category=q-a + url: https://github.com/Enan/pathao-courier/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_name/:package_name/discussions/new?category=ideas + url: https://github.com/Enan/pathao-courier/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_name/:package_name/security/policy + url: https://github.com/Enan/pathao-courier/security/policy about: Learn how to notify us for sensitive bugs diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 30c8a49..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,12 +0,0 @@ -# Please see the documentation for all configuration options: -# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates - -version: 2 -updates: - - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" - labels: - - "dependencies" \ No newline at end of file diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml deleted file mode 100644 index ca2197d..0000000 --- a/.github/workflows/dependabot-auto-merge.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: dependabot-auto-merge -on: pull_request_target - -permissions: - pull-requests: write - contents: write - -jobs: - dependabot: - runs-on: ubuntu-latest - if: ${{ github.actor == 'dependabot[bot]' }} - steps: - - - name: Dependabot metadata - id: metadata - uses: dependabot/fetch-metadata@v1.6.0 - with: - github-token: "${{ secrets.GITHUB_TOKEN }}" - - - name: Auto-merge Dependabot PRs for semver-minor updates - if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}} - run: gh pr merge --auto --merge "$PR_URL" - env: - PR_URL: ${{github.event.pull_request.html_url}} - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - - - name: Auto-merge Dependabot PRs for semver-patch updates - if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} - run: gh pr merge --auto --merge "$PR_URL" - env: - PR_URL: ${{github.event.pull_request.html_url}} - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/fix-php-code-style-issues.yml b/.github/workflows/fix-php-code-style-issues.yml deleted file mode 100644 index 28816d3..0000000 --- a/.github/workflows/fix-php-code-style-issues.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Fix PHP code style issues - -on: - push: - paths: - - '**.php' - -permissions: - contents: write - -jobs: - php-code-styling: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - ref: ${{ github.head_ref }} - - - name: Fix PHP code style issues - uses: aglipanci/laravel-pint-action@2.3.0 - - - name: Commit changes - uses: stefanzweifel/git-auto-commit-action@v5 - with: - commit_message: Fix styling diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..4f1a0e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `pathao-courier` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..91df91b 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) Enan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 375da96..d453f13 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,72 @@ -# :package_description - -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) - ---- -This repo can be used to scaffold a Laravel package. Follow these steps to get started: - -1. Press the "Use this template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Have fun creating your package. -4. If you need help creating a package, consider picking up our Laravel Package Training video course. ---- - -This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. +# A complete Laravel Package for Pathao Courier -## Support us - -[](https://spatie.be/github-ad-click/:package_name) +[![Latest Version on Packagist](https://img.shields.io/packagist/v/enan/pathao-courier.svg?style=flat-square)](https://packagist.org/packages/enan/pathao-courier) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/enan/pathao-courier/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/enan/pathao-courier/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/enan/pathao-courier/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/enan/pathao-courier/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/enan/pathao-courier.svg?style=flat-square)](https://packagist.org/packages/enan/pathao-courier) -We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). +This is a laravel package for [Merchant Pathao Courier](https://merchant.pathao.com/) to create order. Now this package is supporting only with one store. Creating new store and create new order with them will be in newer version. -We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). +## Support us ## Installation You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require enan/pathao-courier ``` You can publish and run the migrations with: ```bash -php artisan vendor:publish --tag=":package_slug-migrations" +php artisan vendor:publish --tag="pathao-courier-migrations" php artisan migrate ``` You can publish the config file with: ```bash -php artisan vendor:publish --tag=":package_slug-config" +php artisan vendor:publish --tag="pathao-courier-config" ``` This is the contents of the published config file: ```php return [ + 'pathao_base_url' => 'https://api-hermes.pathao.com/', + 'pathao_client_id' => env('PATHAO_CLIENT_ID', ''), + 'pathao_client_secret' => env('PATHAO_CLIENT_SECRET', ''), + 'pathao_store_id' => env('PATHAO_STORE_ID', ''), + 'pathao_store_name' => env('PATHAO_STORE_NAME', ''), ]; ``` -Optionally, you can publish the views using + + +Set the below value in your **.env** file + +## .env + +``` +PATHAO_CLIENT_ID= +PATHAO_CLIENT_SECRET= +PATHAO_STORE_ID= +PATHAO_STORE_NAME= ``` ## Usage ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +$pathaoCourier = new Enan\PathaoCourier(); +echo $pathaoCourier->echoPhrase('Hello, Enan!'); ``` -## Testing + ## Credits -- [:author_name](https://github.com/:author_username) -- [All Contributors](../../contributors) +- [Moammer Farshid Enan](https://github.com/Enan) +- [All Contributors](../../contributors) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. + +## Check me on + +- [Portfolio](https://moammer-enan.com/) +- [Facebook](https://www.facebook.com/moammerfarshidenan) +- [GitHub](https://github.com/enuenan) +- [LinkedIn](https://www.linkedin.com/in/moammer-farshid/) diff --git a/composer.json b/composer.json index c0aa6da..097fc17 100644 --- a/composer.json +++ b/composer.json @@ -1,23 +1,23 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "enan/pathao-courier", + "description": "A complete Laravel Package for Pathao Courier", "keywords": [ - ":vendor_name", + "Enan", "laravel", - ":package_slug" + "pathao-courier" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/enan/pathao-courier", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Moammer Farshid Enan", + "email": "emoammerfershid@gmail.com", "role": "Developer" } ], "require": { "php": "^8.1", - "spatie/laravel-package-tools": "^1.14.0", + "guzzlehttp/guzzle": "^7.8", "illuminate/contracts": "^10.0" }, "require-dev": { @@ -30,24 +30,23 @@ "pestphp/pest-plugin-laravel": "^2.0", "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-phpunit": "^1.0", - "spatie/laravel-ray": "^1.26" + "phpstan/phpstan-phpunit": "^1.0" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "Enan\\PathaoCourier\\": "src/", + "Enan\\PathaoCourier\\Database\\Factories\\": "database/factories/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/", + "Enan\\PathaoCourier\\Tests\\": "tests/", "Workbench\\App\\": "workbench/app/" } }, "scripts": { "post-autoload-dump": "@composer run prepare", - "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", + "clear": "@php vendor/bin/testbench package:purge-pathao-courier --ansi", "prepare": "@php vendor/bin/testbench package:discover --ansi", "build": [ "@composer run prepare", @@ -73,10 +72,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "Enan\\PathaoCourier\\PathaoCourierServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "PathaoCourier": "Enan\\PathaoCourier\\Facades\\PathaoCourier" } } }, diff --git a/config/pathao-courier.php b/config/pathao-courier.php new file mode 100644 index 0000000..3fd4781 --- /dev/null +++ b/config/pathao-courier.php @@ -0,0 +1,74 @@ + 'https://api-hermes.pathao.com/', + + + /* + |-------------------------------------------------------------------------- + | Pathao Client Id + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + + 'pathao_client_id' => env('PATHAO_CLIENT_ID', ''), + + + /* + |-------------------------------------------------------------------------- + | Pathao Client Secret + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + + 'pathao_client_secret' => env('PATHAO_CLIENT_SECRET', ''), + + + /* + |-------------------------------------------------------------------------- + | Pathao Store Id + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + + 'pathao_store_id' => env('PATHAO_STORE_ID', ''), + + + /* + |-------------------------------------------------------------------------- + | Pathao Store Name + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + + 'pathao_store_name' => env('PATHAO_STORE_NAME', ''), +]; diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e74186..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - $version) { - if (in_array($name, $names, true)) { - unset($data['require-dev'][$name]); - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_composer_script($scriptName) -{ - $data = json_decode(file_get_contents(__DIR__.'/composer.json'), true); - - foreach ($data['scripts'] as $name => $script) { - if ($scriptName === $name) { - unset($data['scripts'][$name]); - break; - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_readme_paragraphs(string $file): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function safeUnlink(string $filename) -{ - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string -{ - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array -{ - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i '.basename(__FILE__).' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array -{ - return explode(PHP_EOL, run('grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com" --exclude-dir=vendor ./* ./.github/* | grep -v '.basename(__FILE__))); -} - -function getGitHubApiEndpoint(string $endpoint): ?stdClass -{ - try { - $curl = curl_init("https://api.github.com/{$endpoint}"); - curl_setopt_array($curl, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTPGET => true, - CURLOPT_HTTPHEADER => [ - 'User-Agent: spatie-configure-script/1.0', - ], - ]); - - $response = curl_exec($curl); - $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - curl_close($curl); - - if ($statusCode === 200) { - return json_decode($response); - } - } catch (Exception $e) { - // ignore - } - - return null; -} - -function searchCommitsForGitHubUsername(): string -{ - $authorName = strtolower(trim(shell_exec('git config user.name'))); - - $committersRaw = shell_exec("git log --author='@users.noreply.github.com' --pretty='%an:%ae' --reverse"); - $committersLines = explode("\n", $committersRaw); - $committers = array_filter(array_map(function ($line) use ($authorName) { - $line = trim($line); - [$name, $email] = explode(':', $line) + [null, null]; - - return [ - 'name' => $name, - 'email' => $email, - 'isMatch' => strtolower($name) === $authorName && ! str_contains($name, '[bot]'), - ]; - }, $committersLines), fn ($item) => $item['isMatch']); - - if (empty($committers)) { - return ''; - } - - $firstCommitter = reset($committers); - - return explode('@', $firstCommitter['email'])[0] ?? ''; -} - -function guessGitHubUsernameUsingCli() -{ - try { - if (preg_match('/ogged in to github\.com as ([a-zA-Z-_]+).+/', shell_exec('gh auth status -h github.com 2>&1'), $matches)) { - return $matches[1]; - } - } catch (Exception $e) { - // ignore - } - - return ''; -} - -function guessGitHubUsername(): string -{ - $username = searchCommitsForGitHubUsername(); - if (! empty($username)) { - return $username; - } - - $username = guessGitHubUsernameUsingCli(); - if (! empty($username)) { - return $username; - } - - // fall back to using the username from the git remote - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - return $remoteUrlParts[1] ?? ''; -} - -function guessGitHubVendorInfo($authorName, $username): array -{ - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - $response = getGitHubApiEndpoint("orgs/{$remoteUrlParts[1]}"); - - if ($response === null) { - return [$authorName, $username]; - } - - return [$response->name ?? $authorName, $response->login ?? $username]; -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); -$authorUsername = ask('Author username', guessGitHubUsername()); - -$guessGitHubVendorInfo = guessGitHubVendorInfo($authorName, $authorUsername); - -$vendorName = ask('Vendor name', $guessGitHubVendorInfo[0]); -$vendorUsername = ask('Vendor username', $guessGitHubVendorInfo[1] ?? slugify($vendorName)); -$vendorSlug = slugify($vendorUsername); - -$vendorNamespace = str_replace('-', '', ucwords($vendorName)); -$vendorNamespace = ask('Vendor namespace', $vendorNamespace); - -$currentDirectory = getcwd(); -$folderName = basename($currentDirectory); - -$packageName = ask('Package name', $folderName); -$packageSlug = slugify($packageName); -$packageSlugWithoutPrefix = remove_prefix('laravel-', $packageSlug); - -$className = title_case($packageName); -$className = ask('Class name', $className); -$variableName = lcfirst($className); -$description = ask('Package description', "This is my package {$packageSlug}"); - -$usePhpStan = confirm('Enable PhpStan?', true); -$useLaravelPint = confirm('Enable Laravel Pint?', true); -$useDependabot = confirm('Enable Dependabot?', true); -$useLaravelRay = confirm('Use Ray for debugging?', true); -$useUpdateChangelogWorkflow = confirm('Use automatic changelog updater workflow?', true); - -writeln('------'); -writeln("Author : {$authorName} ({$authorUsername}, {$authorEmail})"); -writeln("Vendor : {$vendorName} ({$vendorSlug})"); -writeln("Package : {$packageSlug} <{$description}>"); -writeln("Namespace : {$vendorNamespace}\\{$className}"); -writeln("Class name : {$className}"); -writeln('---'); -writeln('Packages & Utilities'); -writeln('Use Laravel/Pint : '.($useLaravelPint ? 'yes' : 'no')); -writeln('Use Larastan/PhpStan : '.($usePhpStan ? 'yes' : 'no')); -writeln('Use Dependabot : '.($useDependabot ? 'yes' : 'no')); -writeln('Use Ray App : '.($useLaravelRay ? 'yes' : 'no')); -writeln('Use Auto-Changelog : '.($useUpdateChangelogWorkflow ? 'yes' : 'no')); -writeln('------'); - -writeln('This script will replace the above values in all relevant files in the project directory.'); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replace_in_file($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => title_snake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/'.$className.'.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/'.$className.'ServiceProvider.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/'.$className.'.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/'.$className.'Command.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_'.title_snake($packageSlugWithoutPrefix).'_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/'.$packageSlugWithoutPrefix.'.php')), - str_contains($file, 'README.md') => remove_readme_paragraphs($file), - default => [], - }; -} - -if (! $useLaravelPint) { - safeUnlink(__DIR__.'/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__.'/pint.json'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__.'/phpstan.neon.dist'); - safeUnlink(__DIR__.'/phpstan-baseline.neon'); - safeUnlink(__DIR__.'/.github/workflows/phpstan.yml'); - - remove_composer_deps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'nunomaduro/larastan', - ]); - - remove_composer_script('phpstan'); -} - -if (! $useDependabot) { - safeUnlink(__DIR__.'/.github/dependabot.yml'); - safeUnlink(__DIR__.'/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - remove_composer_deps(['spatie/laravel-ray']); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__.'/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install` and run tests?') && run('composer install && composer test'); - -confirm('Let this script delete itself?', true) && unlink(__FILE__); diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php deleted file mode 100644 index c51604f..0000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,19 +0,0 @@ -id(); + $table->string('client_id'); + $table->string('client_secret'); + $table->string('username')->comment('username/email'); + $table->string('password'); + $table->string('store_id'); + $table->string('store_name'); + $table->text('token'); + $table->text('refresh_token'); + $table->string('expires_in'); + $table->timestamps(); + }); + } +}; \ No newline at end of file diff --git a/database/migrations/create_skeleton_table.php.stub b/database/migrations/create_skeleton_table.php.stub deleted file mode 100644 index 2efdce9..0000000 --- a/database/migrations/create_skeleton_table.php.stub +++ /dev/null @@ -1,19 +0,0 @@ -id(); - - // add fields - - $table->timestamps(); - }); - } -}; diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e953c0e..557b134 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/src/Commands/PathaoCourierCommand.php b/src/Commands/PathaoCourierCommand.php new file mode 100644 index 0000000..cbe4031 --- /dev/null +++ b/src/Commands/PathaoCourierCommand.php @@ -0,0 +1,187 @@ +signature = $package->shortName() . ':install'; + + $this->description = 'Install ' . $package->name; + + $this->package = $package; + + parent::__construct(); + } + + public function handle() + { + if ($this->startWith) { + ($this->startWith)($this); + } + + foreach ($this->publishes as $tag) { + $name = str_replace('-', ' ', $tag); + $this->comment("Publishing {$name}..."); + + $this->callSilently("vendor:publish", [ + '--tag' => "{$this->package->shortName()}-{$tag}", + ]); + } + + if ($this->askToRunMigrations) { + if ($this->confirm('Would you like to run the migrations now?')) { + $this->comment('Running migrations...'); + + $this->call('migrate'); + } + } + + if ($this->copyServiceProviderInApp) { + $this->comment('Publishing service provider...'); + + $this->copyServiceProviderInApp(); + } + + if ($this->starRepo) { + if ($this->confirm('Would you like to star our repo on GitHub?')) { + $repoUrl = "https://github.com/{$this->starRepo}"; + + if (PHP_OS_FAMILY == 'Darwin') { + exec("open {$repoUrl}"); + } + if (PHP_OS_FAMILY == 'Windows') { + exec("start {$repoUrl}"); + } + if (PHP_OS_FAMILY == 'Linux') { + exec("xdg-open {$repoUrl}"); + } + } + } + + $this->info("{$this->package->shortName()} has been installed!"); + + if ($this->endWith) { + ($this->endWith)($this); + } + } + + public function publish(string ...$tag): self + { + $this->publishes = array_merge($this->publishes, $tag); + + return $this; + } + + public function publishConfigFile(): self + { + return $this->publish('config'); + } + + public function publishAssets(): self + { + return $this->publish('assets'); + } + + public function publishInertiaComponents(): self + { + return $this->publish('inertia-components'); + } + + public function publishMigrations(): self + { + return $this->publish('migrations'); + } + + public function askToRunMigrations(): self + { + $this->askToRunMigrations = true; + + return $this; + } + + public function copyAndRegisterServiceProviderInApp(): self + { + $this->copyServiceProviderInApp = true; + + return $this; + } + + public function askToStarRepoOnGitHub($vendorSlashRepoName): self + { + $this->starRepo = $vendorSlashRepoName; + + return $this; + } + + public function startWith($callable): self + { + $this->startWith = $callable; + + return $this; + } + + public function endWith($callable): self + { + $this->endWith = $callable; + + return $this; + } + + protected function copyServiceProviderInApp(): self + { + $providerName = $this->package->publishableProviderName; + + if (!$providerName) { + return $this; + } + + $this->callSilent('vendor:publish', ['--tag' => $this->package->shortName() . '-provider']); + + $namespace = Str::replaceLast('\\', '', $this->laravel->getNamespace()); + + $appConfig = file_get_contents(config_path('app.php')); + + $class = '\\Providers\\' . $providerName . '::class'; + + if (Str::contains($appConfig, $namespace . $class)) { + return $this; + } + + file_put_contents(config_path('app.php'), str_replace( + "{$namespace}\\Providers\\BroadcastServiceProvider::class,", + "{$namespace}\\Providers\\BroadcastServiceProvider::class," . PHP_EOL . " {$namespace}{$class},", + $appConfig + )); + + file_put_contents(app_path('Providers/' . $providerName . '.php'), str_replace( + "namespace App\Providers;", + "namespace {$namespace}\Providers;", + file_get_contents(app_path('Providers/' . $providerName . '.php')) + )); + + return $this; + } +} diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 3e5f628..0000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Facades/PathaoCourier.php b/src/Facades/PathaoCourier.php new file mode 100644 index 0000000..773765a --- /dev/null +++ b/src/Facades/PathaoCourier.php @@ -0,0 +1,16 @@ +user()->store) { + $checkAccessTokenIsValid = $this->checkAccessTokenIsValid(); + // If access token is not valid request for a new token. + if (!$checkAccessTokenIsValid) { + $this->requestAccesstoken(); + } + } + + $this->client = new Client([ + 'base_uri' => $this->base_url, + ]); + } + + protected function setHeaders(bool $auth = false) + { + $headers = [ + "accept" => "application/json", + "content-type" => 'application/json', + ]; + + if ($auth) { + $headers["authorization"] = "Bearer " . auth()->user()->store->pathao->token; + }; + + return $headers; + } + + public function getAccessToken(array $cred) + { + $url = "aladdin/api/v1/issue-token"; + $data = $this->Pathao_API_Response(false, $url, 'post', $cred); + + return $data; + } + + public function Pathao_API_Response(bool $auth = false, string $api, string $method, ?array $data = []) + { + try { + $response = $this->client->{$method}( + $api, + [ + 'headers' => $this->setHeaders($auth), + 'body' => ($method == 'post') ? json_encode($data) : null + ] + ); + + $statusCode = $response->getStatusCode(); + + $responseData = json_decode($response->getBody()); + $data = [ + 'code' => $statusCode, + 'status' => 'success', + 'data' => $responseData, + ]; + } catch (ClientException $e) { + $statusCode = $e->getResponse()->getStatusCode(); + $responseBody = $e->getResponse()->getBody()->getContents(); + + $errorData = json_decode($responseBody); + Log::error("API Error: Status Code $statusCode - Response: $responseBody"); + + $data = [ + 'code' => $statusCode, + 'status' => 'failed', + 'message' => $errorData->message, + ]; + } + + return (object)$data; + } + + public function checkAccessTokenIsValid(): bool + { + $currentTimestamp = time(); + $expirationTime = auth()->user()->store->expires_in; + + // Compare the expiration time with the current time + return $expirationTime <= $currentTimestamp; + } + + public function requestAccesstoken() + { + $cred = [ + "client_id" => $this->client_id, + "client_secret" => $this->client_secret, + "refresh_token" => $this->refresh_token, + "grant_type" => $this->grant_type + ]; + $response = $this->getAccessToken($cred); + + if ($response->code == 200) { + return auth()->user()->store->pathao->update([ + 'token' => $response->data->access_token, + 'refresh_token' => $response->data->refresh_token, + 'expires_in' => time() + $response->data->expires_in + ]); + } else { + return $response->data; + } + } +} diff --git a/src/PathaoCourier.php b/src/PathaoCourier.php new file mode 100644 index 0000000..b28fa16 --- /dev/null +++ b/src/PathaoCourier.php @@ -0,0 +1,108 @@ +Pathao_API_Response(true, $url, 'get'); + + return $data; + } + + public function getCities() + { + $url = "aladdin/api/v1/countries/1/city-list"; + $data = $this->Pathao_API_Response(true, $url, 'get'); + + return $data; + } + + public function getZones(int $city_id) + { + $url = "aladdin/api/v1/cities/" . $city_id . "/zone-list"; + $data = $this->Pathao_API_Response(true, $url, 'get'); + + return $data; + } + + public function getAreas(int $zone_id) + { + $url = "aladdin/api/v1/zones/" . $zone_id . "/area-list"; + $data = $this->Pathao_API_Response(true, $url, 'get'); + + return $data; + } + + public function createOrder(array $data) + { + $validator = Validator::make($data, [ + 'store_id' => ['required', 'numeric'], // Find in store list, + 'merchant_order_id' => ['required', 'numeric'], // Unique order id + 'recipient_name' => ['required', 'string'], // Customer name + 'recipient_phone' => ['required', 'string'], // Customer phone + 'recipient_address' => ['required', 'string'], // Customer address + 'recipient_city' => ['required', 'numeric'], // Find in city method + 'recipient_zone' => ['required', 'numeric'], // Find in zone method + 'recipient_area' => ['required', 'numeric'], // Find in Area method + 'delivery_type' => [ + 'required', + 'in:' . parent::DELIVERY_TYPE_NORMAL . ',' . parent::DELIVERY_TYPE_DEMAND + ], // 48 for normal delivery or 12 for on demand delivery + 'item_type' => [ + 'required', + 'in:' . parent::ITEM_TYPE_DOCUMENT . ',' . parent::ITEM_TYPE_PARCEL + ], // 1 for document, 2 FOR PERCEL + 'special_instruction' => ['nullable', 'string'], + 'item_quantity' => ['nullable', 'numeric'], // item quantity + 'item_weight' => ['nullable', 'numeric'], // parcel weight + 'amount_to_collect' => ['required', 'numeric'], // amount to collect + 'item_description' => ['nullable', 'string'] // product details + ]); + + $url = "aladdin/api/v1/orders"; + + $body = [ + "store_id" => $data['store_id'], + "merchant_order_id" => $data['merchant_order_id'], + "sender_name" => $data['recipient_name'], + "sender_phone" => $data['recipient_name'], + "recipient_name" => $data['recipient_name'], + "recipient_phone" => $data['recipient_phone'], + "recipient_address" => $data['recipient_address'], + "recipient_city" => $data['recipient_city'], + "recipient_zone" => $data['recipient_zone'], + "recipient_area" => $data['recipient_area'], + "delivery_type" => $data['delivery_type'], + "item_type" => $data['item_type'], + "special_instruction" => $data['special_instruction'], + "item_quantity" => $data['item_quantity'], + "item_weight" => $data['item_weight'], + "amount_to_collect" => $data['amount_to_collect'], + "item_description" => $data['item_description'], + ]; + + $data = $this->Pathao_API_Response(true, $url, 'post', $body); + + return $data; + } + + public function viewOrder(Model $order) + { + $consignment_id = $order->pathaoOrder?->consignment_id; + if ($consignment_id) { + $url = "aladdin/api/v1/orders/" . $consignment_id; + + $data = $this->Pathao_API_Response(true, $url, 'get'); + + return $data; + } + } +} diff --git a/src/PathaoCourierServiceProvider.php b/src/PathaoCourierServiceProvider.php new file mode 100644 index 0000000..1d52cba --- /dev/null +++ b/src/PathaoCourierServiceProvider.php @@ -0,0 +1,35 @@ +mergeConfigFrom( + __DIR__ . '/../config/pathao-courier.php', + 'courier' + ); + } + + /** + * Bootstrap any package services. + */ + public function boot(): void + { + $this->publishes([ + __DIR__ . '/../config/pathao-courier.php' => config_path('pathao-courier.php') + ], 'pathao-courier-config'); + $this->publishes([ + __DIR__ . '/../database' => database_path('migrations'), + ], 'migrations'); + } +} diff --git a/src/PathaoDataDTO.php b/src/PathaoDataDTO.php new file mode 100644 index 0000000..a467a91 --- /dev/null +++ b/src/PathaoDataDTO.php @@ -0,0 +1,19 @@ +name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_skeleton_table') - ->hasCommand(SkeletonCommand::class); - } -} diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..b9f02b1 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..5b9b22f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' + fn (string $modelName) => 'Enan\\PathaoCourier\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + PathaoCourierServiceProvider::class, ]; } @@ -29,7 +29,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_pathao-courier_table.php.stub'; $migration->up(); */ }