diff --git a/README.md b/README.md
index 1778bf74..728f1dc4 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,6 @@
-![Inventory Banner]
-(https://github.com/stevebauman/inventory/blob/master/inventory-banner.jpg)
+# Inventory
-[](https://travis-ci.org/stevebauman/inventory)
+[](https://travis-ci.org/stevebauman/inventory)
[](https://scrutinizer-ci.com/g/stevebauman/inventory/?branch=master)
[](https://insight.sensiolabs.com/projects/69e0abf0-cd74-4d4d-b40c-e943c4a7eea9)
[](https://packagist.org/packages/stevebauman/inventory)
diff --git a/composer.json b/composer.json
index 217e0451..0320274e 100644
--- a/composer.json
+++ b/composer.json
@@ -11,16 +11,15 @@
"license": "MIT",
"require": {
"php": ">=5.4.0",
- "illuminate/database": "4.* | 5.*",
- "illuminate/support": "4.* | 5.*",
- "baum/baum": "1.0.* | 1.1.*"
+ "illuminate/database": "5.*",
+ "illuminate/support": "5.*",
+ "baum/baum": "1.1.*"
},
"require-dev": {
- "phpunit/phpunit": "4.*",
- "mockery/mockery": "0.9.*"
+ "orchestra/testbench": "3.1.*"
},
"archive": {
- "exclude": ["/tests"]
+ "exclude": ["/tests"]
},
"autoload": {
"psr-4": {
@@ -30,7 +29,7 @@
"autoload-dev":
{
"psr-4": {
- "Stevebauman\\Inventory\\Tests\\": "tests/"
+ "Stevebauman\\Inventory\\Tests\\": "tests/"
}
},
"minimum-stability": "stable"
diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md
index dfb66ac8..724a5f29 100644
--- a/docs/INSTALLATION.md
+++ b/docs/INSTALLATION.md
@@ -1,10 +1,13 @@
## Installation
+> **Note**: If you're looking to use Inventory with MSSQL, you will need to modify the published migrations to suit. By default,
+multiple cascade delete paths are present on foreign keys, and you'll need to modify and / or remove these for compatibility.
+
### Installation (Laravel 4)
Add inventory to your `composer.json` file:
- "stevebauman/inventory" : "1.6.*"
+ "stevebauman/inventory" : "1.7.*"
Now perform a `composer update` on your project's source.
@@ -32,7 +35,7 @@ Be sure to publish the configuration if you'd like to customize inventory:
Add inventory to your `composer.json` file:
- "stevebauman/inventory" : "1.6.*"
+ "stevebauman/inventory" : "1.7.*"
Now perform a `composer update` on your project's source.
@@ -117,6 +120,8 @@ Category:
class Category extends Node
{
+ use CategoryTrait;
+
protected $table = 'categories';
protected $scoped = ['belongs_to'];
@@ -137,7 +142,7 @@ Supplier:
protected $table = 'suppliers';
- public function items()
+ public function items()
{
return $this->belongsToMany('Inventory', 'inventory_suppliers', 'supplier_id')->withTimestamps();
}
@@ -145,6 +150,7 @@ Supplier:
Inventory:
+ use Stevebauman\Inventory\Traits\AssemblyTrait;
use Stevebauman\Inventory\Traits\InventoryTrait;
use Stevebauman\Inventory\Traits\InventoryVariantTrait;
@@ -152,8 +158,9 @@ Inventory:
{
use InventoryTrait;
use InventoryVariantTrait;
+ use AssemblyTrait;
- protected $table = 'inventory';
+ protected $table = 'inventories';
public function category()
{
@@ -179,6 +186,12 @@ Inventory:
{
return $this->belongsToMany('Supplier', 'inventory_suppliers', 'inventory_id')->withTimestamps();
}
+
+ public function assemblies()
+ {
+ return $this->belongsToMany($this, 'inventory_assemblies', 'inventory_id', 'part_id')
+ ->withPivot(['quantity'])->withTimestamps();
+ }
}
InventorySku:
diff --git a/inventory-banner.jpg b/inventory-banner.jpg
deleted file mode 100644
index 027e09ff..00000000
Binary files a/inventory-banner.jpg and /dev/null differ
diff --git a/src/Commands/InstallCommand.php b/src/Commands/InstallCommand.php
deleted file mode 100644
index 1676d595..00000000
--- a/src/Commands/InstallCommand.php
+++ /dev/null
@@ -1,43 +0,0 @@
-info('Checking Database Schema');
-
- $this->call('inventory:check-schema');
-
- $this->info('Running migrations');
-
- $this->call('inventory:run-migrations');
-
- $this->info('Inventory has been successfully installed');
- }
-}
diff --git a/src/Commands/RunMigrationsCommand.php b/src/Commands/RunMigrationsCommand.php
deleted file mode 100644
index 1877c5fa..00000000
--- a/src/Commands/RunMigrationsCommand.php
+++ /dev/null
@@ -1,35 +0,0 @@
-call('migrate', [
- '--path' => 'vendor/stevebauman/inventory/src/migrations',
- ]);
- }
-}
diff --git a/src/Commands/SchemaCheckCommand.php b/src/Commands/SchemaCheckCommand.php
deleted file mode 100644
index 930ed6f4..00000000
--- a/src/Commands/SchemaCheckCommand.php
+++ /dev/null
@@ -1,129 +0,0 @@
- 'Sentry, Sentinel or Laravel',
- ];
-
- /**
- * Holds the reserved database tables that
- * cannot exist before installation.
- *
- * @var array
- */
- protected $reserved = [
- 'metrics',
- 'locations',
- 'categories',
- 'suppliers',
- 'inventory',
- 'inventory_skus',
- 'inventory_stocks',
- 'inventory_stock_movements',
- 'inventory_suppliers',
- 'inventory_transactions',
- 'inventory_transaction_histories',
- 'inventory_assemblies',
- ];
-
- /**
- * Executes the console command.
- *
- * @throws DatabaseTableReservedException
- * @throws DependencyNotFoundException
- */
- public function fire()
- {
- if ($this->checkDependencies()) {
- $this->info('Schema dependencies are all good!');
- }
-
- if ($this->checkReserved()) {
- $this->info('Schema reserved tables are all good!');
- }
- }
-
- /**
- * Checks the current database for dependencies.
- *
- * @throws DependencyNotFoundException
- *
- * @return bool
- */
- private function checkDependencies()
- {
- foreach ($this->dependencies as $table => $suppliedBy) {
- if (!$this->tableExists($table)) {
- $message = sprintf('Table: %s does not exist, it is supplied by %s', $table, $suppliedBy);
-
- throw new DependencyNotFoundException($message);
- }
- }
-
- return true;
- }
-
- /**
- * Checks the current database for reserved tables.
- *
- * @throws DatabaseTableReservedException
- *
- * @return bool
- */
- private function checkReserved()
- {
- foreach ($this->reserved as $table) {
- if ($this->tableExists($table)) {
- $message = sprintf('Table: %s already exists. This table is reserved. Please remove the database table to continue', $table);
-
- throw new DatabaseTableReservedException($message);
- }
- }
-
- return true;
- }
-
- /**
- * Returns true / false if the current
- * database table exists.
- *
- * @param string $table
- *
- * @return bool
- */
- private function tableExists($table)
- {
- return Schema::hasTable($table);
- }
-}
diff --git a/src/config/.gitkeep b/src/Config/.gitkeep
similarity index 100%
rename from src/config/.gitkeep
rename to src/Config/.gitkeep
diff --git a/src/Config/config.php b/src/Config/config.php
new file mode 100644
index 00000000..56e6d3f5
--- /dev/null
+++ b/src/Config/config.php
@@ -0,0 +1,99 @@
+ false,
+
+ /*
+ |--------------------------------------------------------------------------
+ | Allow Duplicate Movements
+ |--------------------------------------------------------------------------
+ |
+ | Allows inventory stock movements to have the same before and after quantity.
+ |
+ */
+
+ 'allow_duplicate_movements' => true,
+
+ /*
+ |--------------------------------------------------------------------------
+ | Rollback Cost
+ |--------------------------------------------------------------------------
+ |
+ | For example, if the movement's cost that is being rolled
+ | back is 500, the rolled back movement will be -500.
+ |
+ */
+
+ 'rollback_cost' => true,
+
+ /*
+ |--------------------------------------------------------------------------
+ | Skus Enabled
+ |--------------------------------------------------------------------------
+ |
+ | Enables SKUs to be automatically generated on item creation.
+ |
+ */
+
+ 'skus_enabled' => true,
+
+ /*
+ |--------------------------------------------------------------------------
+ | Sku Prefix Length
+ |--------------------------------------------------------------------------
+ |
+ | The sku prefix length, not including the code for example:
+ |
+ | An item with a category named 'Sauce', the sku prefix generated will be: SAU
+ |
+ */
+
+ 'sku_prefix_length' => 3,
+
+ /*
+ |--------------------------------------------------------------------------
+ | Sku Code Length
+ |--------------------------------------------------------------------------
+ |
+ | The sku code length, not including prefix for example:
+ |
+ | An item with an ID of 1 (one) the sku code will be: 000001
+ |
+ */
+
+ 'sku_code_length' => 6,
+
+ /*
+ * The sku separator for use in separating the prefix from the code.
+ *
+ * For example, if a hyphen (-) is inserted in the string below, a possible
+ * SKU might be 'DRI-00001'
+ *
+ * @var string
+ */
+
+ /*
+ |--------------------------------------------------------------------------
+ | Sku Separator
+ |--------------------------------------------------------------------------
+ |
+ | The sku separator for use in separating the prefix from the code.
+ |
+ | For example, if a hyphen (-) is inserted in the string
+ | below, a possible SKU might be 'DRI-00001'
+ |
+ */
+
+ 'sku_separator' => '',
+
+];
diff --git a/src/Exceptions/InvalidItemException.php b/src/Exceptions/InvalidItemException.php
deleted file mode 100644
index 165af04d..00000000
--- a/src/Exceptions/InvalidItemException.php
+++ /dev/null
@@ -1,10 +0,0 @@
-id;
+ }
+ } else if (Auth::check()) {
+ return Auth::user()->getAuthIdentifier();
+ }
+
+ // Couldn't get the current logged in users ID, throw exception
+ $message = Lang::get('inventory::exceptions.NoUserLoggedInException');
+
+ throw new NoUserLoggedInException($message);
+ }
+}
diff --git a/src/InventoryServiceProvider.php b/src/InventoryServiceProvider.php
index 1c4ed924..69a5d28b 100644
--- a/src/InventoryServiceProvider.php
+++ b/src/InventoryServiceProvider.php
@@ -4,9 +4,6 @@
use Illuminate\Support\ServiceProvider;
-/**
- * Class InventoryServiceProvider.
- */
class InventoryServiceProvider extends ServiceProvider
{
/**
@@ -14,120 +11,29 @@ class InventoryServiceProvider extends ServiceProvider
*
* @var string
*/
- const VERSION = '1.7.5';
+ const VERSION = '1.8.0';
/**
- * Stores the package configuration separator
- * for Laravel 5 compatibility.
- *
- * @var string
- */
- public static $packageConfigSeparator = '::';
-
- /**
- * The laravel version number. This is
- * used for the install commands.
- *
- * @var int
- */
- public static $laravelVersion = 4;
-
- /**
- * Indicates if loading of the provider is deferred.
- *
- * @var bool
- */
- protected $defer = false;
-
- /**
- * Boot the service provider.
- */
- public function boot()
- {
- /*
- * If the package method exists, we're using Laravel 4, if not, we're on 5
- */
- if (method_exists($this, 'package')) {
- $this->package('stevebauman/inventory', 'stevebauman/inventory', __DIR__.'/..');
- } else {
- /*
- * Set the proper configuration separator since
- * retrieving configuration values in packages
- * changed from '::' to '.'
- */
- $this::$packageConfigSeparator = '.';
-
- /*
- * Set the local inventory laravel version for easy checking
- */
- $this::$laravelVersion = 5;
-
- /*
- * Load the inventory translations from the inventory lang folder
- */
- $this->loadTranslationsFrom(__DIR__.'/lang', 'inventory');
-
- /*
- * Assign the configuration as publishable, and tag it as 'config'
- */
- $this->publishes([
- __DIR__.'/config/config.php' => config_path('inventory.php'),
- ], 'config');
-
- /*
- * Assign the migrations as publishable, and tag it as 'migrations'
- */
- $this->publishes([
- __DIR__.'/migrations/' => base_path('database/migrations'),
- ], 'migrations');
- }
- }
-
- /**
- * Register the service provider.
+ * {@inheritdoc}
*/
public function register()
{
- /*
- * Bind the install command
- */
- $this->app->bind('inventory:install', function () {
- return new Commands\InstallCommand();
- });
-
- /*
- * Bind the check-schema command
- */
- $this->app->bind('inventory:check-schema', function () {
- return new Commands\SchemaCheckCommand();
- });
-
- /*
- * Bind the run migrations command
- */
- $this->app->bind('inventory:run-migrations', function () {
- return new Commands\RunMigrationsCommand();
- });
-
- /*
- * Register the commands
- */
- $this->commands([
- 'inventory:install',
- 'inventory:check-schema',
- 'inventory:run-migrations',
- ]);
-
- /*
- * Include the helpers file
- */
- include __DIR__.'/helpers.php';
+ // Load the inventory translations from the inventory lang folder
+ $this->loadTranslationsFrom(__DIR__.'/Lang', 'inventory');
+
+ // Assign the configuration as publishable, and tag it as 'config'
+ $this->publishes([
+ __DIR__.'/Config/config.php' => config_path('inventory.php'),
+ ], 'config');
+
+ // Assign the migrations as publishable, and tag it as 'migrations'
+ $this->publishes([
+ __DIR__.'/Migrations/' => base_path('database/migrations'),
+ ], 'migrations');
}
/**
- * Get the services provided by the provider.
- *
- * @return array
+ * {@inheritdoc}
*/
public function provides()
{
diff --git a/src/lang/en/exceptions.php b/src/Lang/en/exceptions.php
similarity index 82%
rename from src/lang/en/exceptions.php
rename to src/Lang/en/exceptions.php
index 3d3ba03b..18b20179 100644
--- a/src/lang/en/exceptions.php
+++ b/src/Lang/en/exceptions.php
@@ -1,14 +1,7 @@
'Location :location is invalid',
-
'InvalidMovementException' => 'Movement :movement is invalid',
'InvalidSupplierException' => 'Supplier :supplier is invalid',
diff --git a/src/lang/en/reasons.php b/src/Lang/en/reasons.php
similarity index 94%
rename from src/lang/en/reasons.php
rename to src/Lang/en/reasons.php
index 4f790716..6b2fb464 100644
--- a/src/lang/en/reasons.php
+++ b/src/Lang/en/reasons.php
@@ -1,10 +1,5 @@
'First Item Record; Stock Increase',
@@ -41,4 +36,5 @@
'cancelled' => 'Cancellation occurred on Transaction ID :id on :date',
],
+
];
diff --git a/src/migrations/.gitkeep b/src/Migrations/.gitkeep
similarity index 100%
rename from src/migrations/.gitkeep
rename to src/Migrations/.gitkeep
diff --git a/src/migrations/2014_07_31_123201_create_metrics_table.php b/src/Migrations/2014_07_31_123201_create_metrics_table.php
similarity index 100%
rename from src/migrations/2014_07_31_123201_create_metrics_table.php
rename to src/Migrations/2014_07_31_123201_create_metrics_table.php
diff --git a/src/migrations/2014_07_31_123204_create_categories_table.php b/src/Migrations/2014_07_31_123204_create_categories_table.php
similarity index 100%
rename from src/migrations/2014_07_31_123204_create_categories_table.php
rename to src/Migrations/2014_07_31_123204_create_categories_table.php
diff --git a/src/migrations/2014_07_31_123204_create_locations_table.php b/src/Migrations/2014_07_31_123204_create_locations_table.php
similarity index 100%
rename from src/migrations/2014_07_31_123204_create_locations_table.php
rename to src/Migrations/2014_07_31_123204_create_locations_table.php
diff --git a/src/migrations/2014_07_31_123213_create_inventory_tables.php b/src/Migrations/2014_07_31_123213_create_inventory_tables.php
similarity index 98%
rename from src/migrations/2014_07_31_123213_create_inventory_tables.php
rename to src/Migrations/2014_07_31_123213_create_inventory_tables.php
index 769dfc45..8126e279 100644
--- a/src/migrations/2014_07_31_123213_create_inventory_tables.php
+++ b/src/Migrations/2014_07_31_123213_create_inventory_tables.php
@@ -17,7 +17,7 @@ public function up()
$table->integer('category_id')->unsigned()->nullable();
$table->integer('user_id')->unsigned()->nullable();
- $table->integer('metric_id')->unsigned();
+ $table->integer('metric_id')->unsigned()->nullable();
$table->string('name');
$table->text('description')->nullable();
diff --git a/src/migrations/2015_03_02_143457_create_inventory_sku_table.php b/src/Migrations/2015_03_02_143457_create_inventory_sku_table.php
similarity index 100%
rename from src/migrations/2015_03_02_143457_create_inventory_sku_table.php
rename to src/Migrations/2015_03_02_143457_create_inventory_sku_table.php
diff --git a/src/migrations/2015_03_06_135351_create_inventory_supplier_tables.php b/src/Migrations/2015_03_06_135351_create_inventory_supplier_tables.php
similarity index 100%
rename from src/migrations/2015_03_06_135351_create_inventory_supplier_tables.php
rename to src/Migrations/2015_03_06_135351_create_inventory_supplier_tables.php
diff --git a/src/migrations/2015_03_09_122729_create_inventory_transaction_tables.php b/src/Migrations/2015_03_09_122729_create_inventory_transaction_tables.php
similarity index 100%
rename from src/migrations/2015_03_09_122729_create_inventory_transaction_tables.php
rename to src/Migrations/2015_03_09_122729_create_inventory_transaction_tables.php
diff --git a/src/migrations/2015_05_05_100032_create_inventory_variants_table.php b/src/Migrations/2015_05_05_100032_create_inventory_variants_table.php
similarity index 100%
rename from src/migrations/2015_05_05_100032_create_inventory_variants_table.php
rename to src/Migrations/2015_05_05_100032_create_inventory_variants_table.php
diff --git a/src/migrations/2015_05_08_115310_modify_inventory_table_for_assemblies.php b/src/Migrations/2015_05_08_115310_modify_inventory_table_for_assemblies.php
similarity index 100%
rename from src/migrations/2015_05_08_115310_modify_inventory_table_for_assemblies.php
rename to src/Migrations/2015_05_08_115310_modify_inventory_table_for_assemblies.php
diff --git a/src/migrations/2015_05_08_115523_create_inventory_assemblies_table.php b/src/Migrations/2015_05_08_115523_create_inventory_assemblies_table.php
similarity index 100%
rename from src/migrations/2015_05_08_115523_create_inventory_assemblies_table.php
rename to src/Migrations/2015_05_08_115523_create_inventory_assemblies_table.php
diff --git a/src/Models/BaseModel.php b/src/Models/BaseModel.php
index 0d0761e7..43fe346c 100644
--- a/src/Models/BaseModel.php
+++ b/src/Models/BaseModel.php
@@ -4,9 +4,7 @@
use Illuminate\Database\Eloquent\Model as Eloquent;
-/**
- * Class BaseModel.
- */
-class BaseModel extends Eloquent
+class Model extends Eloquent
{
+ //
}
diff --git a/src/Models/Category.php b/src/Models/Category.php
index 138907d8..5848fd64 100644
--- a/src/Models/Category.php
+++ b/src/Models/Category.php
@@ -5,19 +5,15 @@
use Stevebauman\Inventory\Traits\CategoryTrait;
use Baum\Node;
-/**
- * Class Category.
- */
class Category extends Node
{
use CategoryTrait;
- protected $table = 'categories';
-
- protected $fillable = [
- 'name',
- ];
-
+ /**
+ * The scoped category attrbiutes.
+ *
+ * @var array
+ */
protected $scoped = ['belongs_to'];
/**
diff --git a/src/Models/Inventory.php b/src/Models/Inventory.php
index a98599ef..c2dd6750 100644
--- a/src/Models/Inventory.php
+++ b/src/Models/Inventory.php
@@ -6,25 +6,19 @@
use Stevebauman\Inventory\Traits\InventoryVariantTrait;
use Stevebauman\Inventory\Traits\InventoryTrait;
-/**
- * Class Inventory.
- */
-class Inventory extends BaseModel
+class Inventory extends Model
{
use InventoryTrait;
use InventoryVariantTrait;
use AssemblyTrait;
+ /**
+ * The inventories table.
+ *
+ * @var string
+ */
protected $table = 'inventories';
- protected $fillable = [
- 'user_id',
- 'category_id',
- 'metric_id',
- 'name',
- 'description',
- ];
-
/**
* The hasOne category relationship.
*
@@ -32,7 +26,7 @@ class Inventory extends BaseModel
*/
public function category()
{
- return $this->hasOne('Stevebauman\Inventory\Models\Category', 'id', 'category_id');
+ return $this->hasOne(Category::class);
}
/**
@@ -42,7 +36,7 @@ public function category()
*/
public function metric()
{
- return $this->hasOne('Stevebauman\Inventory\Models\Metric', 'id', 'metric_id');
+ return $this->hasOne(Metric::class);
}
/**
@@ -52,7 +46,7 @@ public function metric()
*/
public function sku()
{
- return $this->hasOne('Stevebauman\Inventory\Models\InventorySku', 'inventory_id', 'id');
+ return $this->hasOne(InventorySku::class, 'inventory_id', 'id');
}
/**
@@ -62,7 +56,7 @@ public function sku()
*/
public function stocks()
{
- return $this->hasMany('Stevebauman\Inventory\Models\InventoryStock', 'inventory_id', 'id');
+ return $this->hasMany(InventoryStock::class, 'inventory_id', 'id');
}
/**
@@ -72,7 +66,7 @@ public function stocks()
*/
public function suppliers()
{
- return $this->belongsToMany('Stevebauman\Inventory\Models\Supplier', 'inventory_suppliers', 'inventory_id')->withTimestamps();
+ return $this->belongsToMany(Supplier::class, 'inventory_suppliers', 'inventory_id')->withTimestamps();
}
/**
diff --git a/src/Models/InventorySku.php b/src/Models/InventorySku.php
index 08001d3d..f8b30a0d 100644
--- a/src/Models/InventorySku.php
+++ b/src/Models/InventorySku.php
@@ -4,20 +4,10 @@
use Stevebauman\Inventory\Traits\InventorySkuTrait;
-/**
- * Class InventorySku.
- */
-class InventorySku extends BaseModel
+class InventorySku extends Model
{
use InventorySkuTrait;
- protected $table = 'inventory_skus';
-
- protected $fillable = [
- 'inventory_id',
- 'code',
- ];
-
/**
* The belongsTo item trait.
*
@@ -25,6 +15,6 @@ class InventorySku extends BaseModel
*/
public function item()
{
- return $this->belongsTo('Stevebauman\Inventory\Models\Inventory', 'inventory_id', 'id');
+ return $this->belongsTo(Inventory::class, 'inventory_id', 'id');
}
}
diff --git a/src/Models/InventoryStock.php b/src/Models/InventoryStock.php
index 48b8f4ae..a0e3b7b1 100644
--- a/src/Models/InventoryStock.php
+++ b/src/Models/InventoryStock.php
@@ -4,24 +4,10 @@
use Stevebauman\Inventory\Traits\InventoryStockTrait;
-/**
- * Class InventoryStock.
- */
-class InventoryStock extends BaseModel
+class InventoryStock extends Model
{
use InventoryStockTrait;
- protected $table = 'inventory_stocks';
-
- protected $fillable = [
- 'inventory_id',
- 'location_id',
- 'quantity',
- 'aisle',
- 'row',
- 'bin',
- ];
-
/**
* The belongsTo inventory item relationship.
*
@@ -29,7 +15,7 @@ class InventoryStock extends BaseModel
*/
public function item()
{
- return $this->belongsTo('Stevebauman\Inventory\Models\Inventory', 'inventory_id', 'id');
+ return $this->belongsTo(Inventory::class, 'inventory_id', 'id');
}
/**
@@ -39,7 +25,7 @@ public function item()
*/
public function movements()
{
- return $this->hasMany('Stevebauman\Inventory\Models\InventoryStockMovement', 'stock_id', 'id');
+ return $this->hasMany(InventoryStockMovement::class, 'stock_id', 'id');
}
/**
@@ -49,7 +35,7 @@ public function movements()
*/
public function transactions()
{
- return $this->hasMany('Stevebauman\Inventory\Models\InventoryTransaction', 'stock_id', 'id');
+ return $this->hasMany(InventoryTransaction::class, 'stock_id', 'id');
}
/**
@@ -59,6 +45,6 @@ public function transactions()
*/
public function location()
{
- return $this->hasOne('Stevebauman\Inventory\Models\Location', 'id', 'location_id');
+ return $this->hasOne(Location::class);
}
}
diff --git a/src/Models/InventoryStockMovement.php b/src/Models/InventoryStockMovement.php
index 9d1fcb6c..7520f1f7 100644
--- a/src/Models/InventoryStockMovement.php
+++ b/src/Models/InventoryStockMovement.php
@@ -4,24 +4,10 @@
use Stevebauman\Inventory\Traits\InventoryStockMovementTrait;
-/**
- * Class InventoryStockMovement.
- */
-class InventoryStockMovement extends BaseModel
+class InventoryStockMovement extends Model
{
use InventoryStockMovementTrait;
- protected $table = 'inventory_stock_movements';
-
- protected $fillable = [
- 'stock_id',
- 'user_id',
- 'before',
- 'after',
- 'cost',
- 'reason',
- ];
-
/**
* The belongsTo stock relationship.
*
@@ -29,6 +15,6 @@ class InventoryStockMovement extends BaseModel
*/
public function stock()
{
- return $this->belongsTo('Stevebauman\Inventory\Models\InventoryStock', 'stock_id', 'id');
+ return $this->belongsTo(InventoryStock::class);
}
}
diff --git a/src/Models/InventoryTransaction.php b/src/Models/InventoryTransaction.php
index 1e9c03c2..db1f44fd 100644
--- a/src/Models/InventoryTransaction.php
+++ b/src/Models/InventoryTransaction.php
@@ -5,23 +5,10 @@
use Stevebauman\Inventory\Traits\InventoryTransactionTrait;
use Stevebauman\Inventory\Interfaces\StateableInterface;
-/**
- * Class InventoryTransaction.
- */
-class InventoryTransaction extends BaseModel implements StateableInterface
+class InventoryTransaction extends Model implements StateableInterface
{
use InventoryTransactionTrait;
- protected $table = 'inventory_transactions';
-
- protected $fillable = [
- 'user_id',
- 'stock_id',
- 'name',
- 'state',
- 'quantity',
- ];
-
/**
* The belongsTo stock relationship.
*
@@ -29,7 +16,7 @@ class InventoryTransaction extends BaseModel implements StateableInterface
*/
public function stock()
{
- return $this->belongsTo('Stevebauman\Inventory\Models\InventoryStock', 'stock_id', 'id');
+ return $this->belongsTo(InventoryStock::class, 'stock_id', 'id');
}
/**
@@ -39,6 +26,6 @@ public function stock()
*/
public function histories()
{
- return $this->hasMany('Stevebauman\Inventory\Models\InventoryTransactionHistory', 'transaction_id', 'id');
+ return $this->hasMany(InventoryTransactionHistory::class, 'transaction_id', 'id');
}
}
diff --git a/src/Models/InventoryTransactionHistory.php b/src/Models/InventoryTransactionHistory.php
index d90e1674..0bc2c45a 100644
--- a/src/Models/InventoryTransactionHistory.php
+++ b/src/Models/InventoryTransactionHistory.php
@@ -4,24 +4,10 @@
use Stevebauman\Inventory\Traits\InventoryTransactionHistoryTrait;
-/**
- * Class InventoryTransactionPeriod.
- */
-class InventoryTransactionHistory extends BaseModel
+class InventoryTransactionHistory extends Model
{
use InventoryTransactionHistoryTrait;
- protected $table = 'inventory_transaction_histories';
-
- protected $fillable = [
- 'user_id',
- 'transaction_id',
- 'state_before',
- 'state_after',
- 'quantity_before',
- 'quantity_after',
- ];
-
/**
* The belongsTo transaction relationship.
*
@@ -29,6 +15,6 @@ class InventoryTransactionHistory extends BaseModel
*/
public function transaction()
{
- return $this->belongsTo('Stevebauman\Inventory\Models\InventoryTransaction', 'transaction_id', 'id');
+ return $this->belongsTo(InventoryTransaction::class);
}
}
diff --git a/src/Models/Location.php b/src/Models/Location.php
index bace1c3c..cd550894 100644
--- a/src/Models/Location.php
+++ b/src/Models/Location.php
@@ -4,17 +4,13 @@
use Baum\Node;
-/**
- * Class Location.
- */
class Location extends Node
{
- protected $table = 'locations';
-
- protected $fillable = [
- 'name',
- ];
-
+ /**
+ * The scoped location attributes.
+ *
+ * @var array
+ */
protected $scoped = ['belongs_to'];
/**
@@ -24,6 +20,6 @@ class Location extends Node
*/
public function stocks()
{
- return $this->hasMany('Stevebauman\Inventory\Models\InventoryStock', 'location_id', 'id');
+ return $this->hasMany(InventoryStock::class, 'location_id', 'id');
}
}
diff --git a/src/Models/Metric.php b/src/Models/Metric.php
index 88645786..21e96d45 100644
--- a/src/Models/Metric.php
+++ b/src/Models/Metric.php
@@ -2,13 +2,8 @@
namespace Stevebauman\Inventory\Models;
-/**
- * Class Metric.
- */
-class Metric extends BaseModel
+class Metric extends Model
{
- protected $table = 'metrics';
-
/**
* The hasMany inventory items relationship.
*
@@ -16,6 +11,6 @@ class Metric extends BaseModel
*/
public function items()
{
- return $this->hasMany('Stevebauman\Inventory\Models\Inventory', 'metric_id', 'id');
+ return $this->hasMany(Inventory::class, 'metric_id', 'id');
}
}
diff --git a/src/Models/Supplier.php b/src/Models/Supplier.php
index 32da24d5..3331f589 100644
--- a/src/Models/Supplier.php
+++ b/src/Models/Supplier.php
@@ -4,27 +4,10 @@
use Stevebauman\Inventory\Traits\SupplierTrait;
-class Supplier extends BaseModel
+class Supplier extends Model
{
use SupplierTrait;
- protected $table = 'suppliers';
-
- protected $fillable = [
- 'name',
- 'address',
- 'postal_code',
- 'zip_code',
- 'region',
- 'city',
- 'country',
- 'contact_title',
- 'contact_name',
- 'contact_phone',
- 'contact_fax',
- 'contact_email',
- ];
-
/**
* The belongsToMany items relationship.
*
@@ -32,6 +15,6 @@ class Supplier extends BaseModel
*/
public function items()
{
- return $this->belongsToMany('Stevebauman\Inventory\Models\Inventory', 'inventory_suppliers', 'supplier_id')->withTimestamps();
+ return $this->belongsToMany(Inventory::class, 'inventory_suppliers', 'supplier_id')->withTimestamps();
}
}
diff --git a/src/Traits/AssemblyTrait.php b/src/Traits/AssemblyTrait.php
index 6cf9a402..cb34d6f6 100644
--- a/src/Traits/AssemblyTrait.php
+++ b/src/Traits/AssemblyTrait.php
@@ -7,9 +7,6 @@
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Model;
-/**
- * Class AssemblyTrait.
- */
trait AssemblyTrait
{
/**
@@ -43,7 +40,7 @@ public function assembliesRecursive()
*/
public function makeAssembly()
{
- $this->is_assembly = true;
+ $this->setAttribute('is_assembly', true);
return $this->save();
}
@@ -103,10 +100,8 @@ public function getAssemblyItems($recursive = true)
if (!$results) {
$results = $this->assembliesRecursive;
- /*
- * Cache forever since adding / removing assembly
- * items will automatically clear this cache
- */
+ // Cache forever since adding / removing assembly
+ // items will automatically clear this cache.
Cache::forever($this->getAssemblyCacheKey(), $results);
}
@@ -137,12 +132,12 @@ public function getAssemblyItemsList($recursive = true, $depth = 0)
foreach ($items as $item) {
$list[$level] = [
- 'id' => $item->getKey(),
- 'name' => $item->name,
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- 'quantity' => $item->pivot->quantity,
- 'depth' => $depth,
+ 'id' => $item->getKey(),
+ 'name' => $item->name,
+ 'metric_id' => $item->metric_id,
+ 'category_id' => $item->category_id,
+ 'quantity' => $item->pivot->quantity,
+ 'depth' => $depth,
];
if ($item->is_assembly && $recursive) {
@@ -169,11 +164,11 @@ public function getAssemblyItemsList($recursive = true, $depth = 0)
public function addAssemblyItem(Model $part, $quantity = 1, array $extra = [])
{
if ($this->isValidQuantity($quantity)) {
- if (!$this->is_assembly) {
+ if (!$this->getAttribute('is_assembly')) {
$this->makeAssembly();
}
- if ($part->is_assembly) {
+ if ($part->getAttribute('is_assembly')) {
$this->validatePart($part);
}
@@ -354,7 +349,7 @@ public function scopeAssembly(Builder $query)
*
* @throws InvalidPartException
*/
- private function validatePart(Model $part)
+ protected function validatePart(Model $part)
{
if ((int) $part->getKey() === (int) $this->getKey()) {
$message = 'An item cannot be an assembly of itself.';
@@ -379,9 +374,9 @@ private function validatePart(Model $part)
*
* @throws InvalidPartException
*/
- private function validatePartAgainstList($value, $key)
+ protected function validatePartAgainstList($value, $key)
{
- if ($key === $this->getKeyName()) {
+ if ((string) $key === (string) $this->getKeyName()) {
if ((int) $value === (int) $this->getKey()) {
$message = 'The inserted part exists inside the assembly tree. An item cannot be an assembly of itself.';
@@ -395,7 +390,7 @@ private function validatePartAgainstList($value, $key)
*
* @return string
*/
- private function getAssemblyCacheKey()
+ protected function getAssemblyCacheKey()
{
return $this->assemblyCacheKey.$this->getKey();
}
diff --git a/src/Traits/CategoryTrait.php b/src/Traits/CategoryTrait.php
index aca72868..252babdf 100644
--- a/src/Traits/CategoryTrait.php
+++ b/src/Traits/CategoryTrait.php
@@ -2,9 +2,6 @@
namespace Stevebauman\Inventory\Traits;
-/**
- * Trait CategoryTrait.
- */
trait CategoryTrait
{
/**
diff --git a/src/Traits/CommonMethodsTrait.php b/src/Traits/CommonMethodsTrait.php
new file mode 100644
index 00000000..3b6dd5db
--- /dev/null
+++ b/src/Traits/CommonMethodsTrait.php
@@ -0,0 +1,139 @@
+isPositive($quantity)) {
+ return true;
+ }
+
+ $message = Lang::get('inventory::exceptions.InvalidQuantityException', [
+ 'quantity' => $quantity,
+ ]);
+
+ throw new InvalidQuantityException($message);
+ }
+
+ /**
+ * Alias for firing events easily that implement this trait.
+ *
+ * @param string $name
+ * @param array $args
+ *
+ * @return mixed
+ */
+ protected function fireEvent($name, $args = [])
+ {
+ return Event::fire((string) $name, (array) $args);
+ }
+
+ /**
+ * Alias for beginning a database transaction.
+ *
+ * @return mixed
+ */
+ protected function dbStartTransaction()
+ {
+ return DB::beginTransaction();
+ }
+
+ /**
+ * Alias for committing a database transaction.
+ *
+ * @return mixed
+ */
+ protected function dbCommitTransaction()
+ {
+ return DB::commit();
+ }
+
+ /**
+ * Alias for rolling back a transaction.
+ *
+ * @return mixed
+ */
+ protected function dbRollbackTransaction()
+ {
+ return DB::rollback();
+ }
+
+ /**
+ * Returns true/false if the number specified is numeric.
+ *
+ * @param int|float|string $number
+ *
+ * @return bool
+ */
+ protected function isNumeric($number)
+ {
+ return (is_numeric($number) ? true : false);
+ }
+
+ /**
+ * Returns true or false if the number inserted is positive.
+ *
+ * @param int|float|string $number
+ *
+ * @return bool
+ */
+ protected function isPositive($number)
+ {
+ if ($this->isNumeric($number)) {
+ return ($number >= 0 ? true : false);
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns true/false if the specified model is a subclass
+ * of the Eloquent Model.
+ *
+ * @param mixed $model
+ *
+ * @return bool
+ */
+ protected function isModel($model)
+ {
+ return $model instanceof Model;
+ }
+}
diff --git a/src/Traits/DatabaseTransactionTrait.php b/src/Traits/DatabaseTransactionTrait.php
deleted file mode 100644
index 0b290971..00000000
--- a/src/Traits/DatabaseTransactionTrait.php
+++ /dev/null
@@ -1,55 +0,0 @@
-user_id = static::getCurrentUserId();
+ $record->setAttribute('user_id', Helper::getCurrentUserId());
});
}
@@ -40,8 +38,6 @@ public static function bootInventoryStockMovementTrait()
*/
public function rollback($recursive = false)
{
- $stock = $this->stock;
-
- return $stock->rollback($this, $recursive);
+ return $this->stock->rollback($this, $recursive);
}
}
diff --git a/src/Traits/InventoryStockTrait.php b/src/Traits/InventoryStockTrait.php
index 7dcc63bc..423e78bc 100644
--- a/src/Traits/InventoryStockTrait.php
+++ b/src/Traits/InventoryStockTrait.php
@@ -2,46 +2,17 @@
namespace Stevebauman\Inventory\Traits;
-use Stevebauman\Inventory\InventoryServiceProvider;
use Stevebauman\Inventory\Exceptions\NotEnoughStockException;
use Stevebauman\Inventory\Exceptions\InvalidMovementException;
use Stevebauman\Inventory\Exceptions\InvalidQuantityException;
+use Stevebauman\Inventory\Helper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
-/**
- * Trait InventoryStockTrait.
- */
trait InventoryStockTrait
{
- /*
- * Used for easily grabbing a specified location
- */
- use LocationTrait;
-
- /*
- * Verification helper functions
- */
- use VerifyTrait;
-
- /*
- * Set's the models constructor method to automatically assign the
- * user_id's attribute to the current logged in user
- */
- use UserIdentificationTrait;
-
- /*
- * Helpers for starting database transactions
- */
- use DatabaseTransactionTrait;
-
- /**
- * Stores the quantity before an update.
- *
- * @var int|float|string
- */
- private $beforeQuantity = 0;
+ use CommonMethodsTrait;
/**
* Stores the reason for updating / creating a stock.
@@ -57,6 +28,13 @@ trait InventoryStockTrait
*/
public $cost = 0;
+ /**
+ * Stores the quantity before an update.
+ *
+ * @var int|float|string
+ */
+ protected $beforeQuantity = 0;
+
/**
* The hasOne location relationship.
*
@@ -86,18 +64,16 @@ abstract public function movements();
abstract public function transactions();
/**
- * Overrides the models boot function to set the user ID automatically
- * to every new record.
+ * Overrides the models boot function to set
+ * the user ID automatically to every new record.
*/
public static function bootInventoryStockTrait()
{
static::creating(function (Model $model) {
- $model->user_id = $model->getCurrentUserId();
+ $model->setAttribute('user_id', Helper::getCurrentUserId());
- /*
- * Check if a reason has been set, if not
- * let's retrieve the default first entry reason
- */
+ // Check if a reason has been set, if not let's
+ // retrieve the default first entry reason.
if (!$model->reason) {
$model->reason = Lang::get('inventory::reasons.first_record');
}
@@ -108,15 +84,12 @@ public static function bootInventoryStockTrait()
});
static::updating(function (Model $model) {
- /*
- * Retrieve the original quantity before it was updated,
- * so we can create generate an update with it
- */
+ // Retrieve the original quantity before it was updated,
+ // so we can create generate an update with it.
$model->beforeQuantity = $model->getOriginal('quantity');
- /*
- * Check if a reason has been set, if not let's retrieve the default change reason
- */
+ // Check if a reason has been set, if not let's
+ // retrieve the default change reason.
if (!$model->reason) {
$model->reason = Lang::get('inventory::reasons.change');
}
@@ -128,27 +101,23 @@ public static function bootInventoryStockTrait()
}
/**
- * Generates a stock movement on the creation of a stock.
+ * Generates a stock movement after a stock is created.
+ *
+ * @return void
*/
public function postCreate()
{
- /*
- * Only create a first record movement if one isn't created already
- */
- if (!$this->getLastMovement()) {
- /*
- * Generate the movement
- */
- $this->generateStockMovement(0, $this->quantity, $this->reason, $this->cost);
- }
+ $this->generateStockMovement(0, $this->getAttribute('quantity'), $this->reason, $this->cost);
}
/**
* Generates a stock movement after a stock is updated.
+ *
+ * @return void
*/
public function postUpdate()
{
- $this->generateStockMovement($this->beforeQuantity, $this->quantity, $this->reason, $this->cost);
+ $this->generateStockMovement($this->beforeQuantity, $this->getAttribute('quantity'), $this->reason, $this->cost);
}
/**
@@ -199,9 +168,7 @@ public function remove($quantity, $reason = '', $cost = 0)
*/
public function take($quantity, $reason = '', $cost = 0)
{
- if ($this->isValidQuantity($quantity) && $this->hasEnoughStock($quantity)) {
- return $this->processTakeOperation($quantity, $reason, $cost);
- }
+ return $this->processTakeOperation($quantity, $reason, $cost);
}
/**
@@ -231,22 +198,18 @@ public function add($quantity, $reason = '', $cost = 0)
*/
public function put($quantity, $reason = '', $cost = 0)
{
- if ($this->isValidQuantity($quantity)) {
- return $this->processPutOperation($quantity, $reason, $cost);
- }
+ return $this->processPutOperation($quantity, $reason, $cost);
}
/**
* Moves a stock to the specified location.
*
- * @param $location
+ * @param Model $location
*
* @return bool
*/
- public function moveTo($location)
+ public function moveTo(Model $location)
{
- $location = $this->getLocation($location);
-
return $this->processMoveOperation($location);
}
@@ -303,17 +266,15 @@ public function rollbackMovement($movement, $recursive = false)
*/
public function hasEnoughStock($quantity = 0)
{
- /*
- * Using double equals for validation of complete value only, not variable type. For example:
- * '20' (string) equals 20 (int)
- */
- if ($this->quantity == $quantity || $this->quantity > $quantity) {
+ $available = $this->getAttribute('quantity');
+
+ if ((float) $available === (float) $quantity || $available > $quantity) {
return true;
}
$message = Lang::get('inventory::exceptions.NotEnoughStockException', [
'quantity' => $quantity,
- 'available' => $this->quantity,
+ 'available' => $available,
]);
throw new NotEnoughStockException($message);
@@ -322,7 +283,7 @@ public function hasEnoughStock($quantity = 0)
/**
* Returns the last movement on the current stock record.
*
- * @return mixed
+ * @return bool|Model
*/
public function getLastMovement()
{
@@ -339,7 +300,7 @@ public function getLastMovement()
* Returns a movement depending on the specified argument. If an object is supplied, it is checked if it
* is an instance of an eloquent model. If a numeric value is entered, it is retrieved by it's ID.
*
- * @param mixed $movement
+ * @param int|string|Model $movement
*
* @throws InvalidMovementException
*
@@ -366,18 +327,15 @@ public function getMovement($movement)
*
* @param string $name
*
- * @return \Illuminate\Database\Eloquent\Model
+ * @return Model
*/
public function newTransaction($name = '')
{
- $transaction = $this->transactions()->getRelated();
+ $transaction = $this->transactions()->getRelated()->newInstance();
- /*
- * Set the transaction attributes so they don't
- * need to be set manually
- */
- $transaction->stock_id = $this->getKey();
- $transaction->name = $name;
+ // Set the transaction attributes so they don't need to be set manually
+ $transaction->setAttribute('stock_id', $this->getKey());
+ $transaction->setAttribute('name', $name);
return $transaction;
}
@@ -387,9 +345,9 @@ public function newTransaction($name = '')
*
* @param int|string $id
*
- * @return mixed
+ * @return null|Model
*/
- private function getMovementById($id)
+ protected function getMovementById($id)
{
return $this->movements()->find($id);
}
@@ -403,14 +361,16 @@ private function getMovementById($id)
*
* @return $this
*/
- private function processUpdateQuantityOperation($quantity, $reason = '', $cost = 0)
+ protected function processUpdateQuantityOperation($quantity, $reason = '', $cost = 0)
{
- if ($quantity > $this->quantity) {
- $putting = $quantity - $this->quantity;
+ $current = $this->getAttribute('quantity');
+
+ if ($quantity > $current) {
+ $putting = $quantity - $current;
return $this->put($putting, $reason, $cost);
} else {
- $taking = $this->quantity - $quantity;
+ $taking = $current - $quantity;
return $this->take($taking, $reason, $cost);
}
@@ -425,39 +385,43 @@ private function processUpdateQuantityOperation($quantity, $reason = '', $cost =
*
* @return $this|bool
*/
- private function processTakeOperation($taking, $reason = '', $cost = 0)
+ protected function processTakeOperation($taking, $reason = '', $cost = 0)
{
- $left = $this->quantity - $taking;
+ if($this->isValidQuantity($taking) && $this->hasEnoughStock($taking)) {
+ $available = $this->getAttribute('quantity');
- /*
- * If the updated total and the beginning total are the same, we'll check if
- * duplicate movements are allowed. We'll return the current record if
- * they aren't.
- */
- if ($left == $this->quantity && !$this->allowDuplicateMovementsEnabled()) {
- return $this;
- }
+ $left = (float) $available - (float) $taking;
- $this->quantity = $left;
+ /*
+ * If the updated total and the beginning total are the same, we'll check if
+ * duplicate movements are allowed. We'll return the current record if
+ * they aren't.
+ */
+ if ((float) $left === (float) $available && !$this->allowDuplicateMovementsEnabled()) {
+ return $this;
+ }
- $this->setReason($reason);
+ $this->setAttribute('quantity', $left);
- $this->setCost($cost);
+ $this->setReason($reason);
- $this->dbStartTransaction();
+ $this->setCost($cost);
- try {
- if ($this->save()) {
- $this->dbCommitTransaction();
+ $this->dbStartTransaction();
- $this->fireEvent('inventory.stock.taken', [
- 'stock' => $this,
- ]);
+ try {
+ if ($this->save()) {
+ $this->dbCommitTransaction();
- return $this;
+ $this->fireEvent('inventory.stock.taken', [
+ 'stock' => $this,
+ ]);
+
+ return $this;
+ }
+ } catch (\Exception $e) {
+ $this->dbRollbackTransaction();
}
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
}
return false;
@@ -472,40 +436,40 @@ private function processTakeOperation($taking, $reason = '', $cost = 0)
*
* @return $this|bool
*/
- private function processPutOperation($putting, $reason = '', $cost = 0)
+ protected function processPutOperation($putting, $reason = '', $cost = 0)
{
- $before = $this->quantity;
+ if($this->isValidQuantity($putting)) {
+ $current = $this->getAttribute('quantity');
- $total = $putting + $before;
+ $total = (float) $putting + (float) $current;
- /*
- * If the updated total and the beginning total are the same,
- * we'll check if duplicate movements are allowed
- */
- if ($total == $this->quantity && !$this->allowDuplicateMovementsEnabled()) {
- return $this;
- }
+ // If the updated total and the beginning total are the same,
+ // we'll check if duplicate movements are allowed.
+ if ((float) $total === (float) $current && !$this->allowDuplicateMovementsEnabled()) {
+ return $this;
+ }
- $this->quantity = $total;
+ $this->quantity = $total;
- $this->setReason($reason);
+ $this->setReason($reason);
- $this->setCost($cost);
+ $this->setCost($cost);
- $this->dbStartTransaction();
+ $this->dbStartTransaction();
- try {
- if ($this->save()) {
- $this->dbCommitTransaction();
+ try {
+ if ($this->save()) {
+ $this->dbCommitTransaction();
- $this->fireEvent('inventory.stock.added', [
- 'stock' => $this,
- ]);
+ $this->fireEvent('inventory.stock.added', [
+ 'stock' => $this,
+ ]);
- return $this;
+ return $this;
+ }
+ } catch (\Exception $e) {
+ $this->dbRollbackTransaction();
}
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
}
return false;
@@ -519,9 +483,9 @@ private function processPutOperation($putting, $reason = '', $cost = 0)
*
* @return bool
*/
- private function processMoveOperation(Model $location)
+ protected function processMoveOperation(Model $location)
{
- $this->location_id = $location->getKey();
+ $this->setAttribute('location_id', $location->getKey());
$this->dbStartTransaction();
@@ -550,13 +514,13 @@ private function processMoveOperation(Model $location)
*
* @return $this|bool
*/
- private function processRollbackOperation(Model $movement, $recursive = false)
+ protected function processRollbackOperation(Model $movement, $recursive = false)
{
if ($recursive) {
return $this->processRecursiveRollbackOperation($movement);
}
- $this->quantity = $movement->before;
+ $this->setAttribute('quantity', $movement->getAttribute('before'));
$reason = Lang::get('inventory::reasons.rollback', [
'id' => $movement->getOriginal('id'),
@@ -566,7 +530,7 @@ private function processRollbackOperation(Model $movement, $recursive = false)
$this->setReason($reason);
if ($this->rollbackCostEnabled()) {
- $this->setCost($movement->cost);
+ $this->setCost($movement->getAttribute('cost'));
$this->reverseCost();
}
@@ -597,7 +561,7 @@ private function processRollbackOperation(Model $movement, $recursive = false)
*
* @return array
*/
- private function processRecursiveRollbackOperation(Model $movement)
+ protected function processRecursiveRollbackOperation(Model $movement)
{
/*
* Retrieve movements that were created after
@@ -628,19 +592,23 @@ private function processRecursiveRollbackOperation(Model $movement)
* @param string $reason
* @param int|float|string $cost
*
- * @return \Illuminate\Database\Eloquent\Model
+ * @return bool|Model
*/
- private function generateStockMovement($before, $after, $reason = '', $cost = 0)
+ protected function generateStockMovement($before, $after, $reason = '', $cost = 0)
{
- $insert = [
- 'stock_id' => $this->getKey(),
- 'before' => $before,
- 'after' => $after,
- 'reason' => $reason,
- 'cost' => $cost,
- ];
-
- return $this->movements()->create($insert);
+ $movement = $this->movements()->getRelated()->newInstance();
+
+ $movement->setAttribute('stock_id', $this->getKey());
+ $movement->setAttribute('before', $before);
+ $movement->setAttribute('after', $after);
+ $movement->setAttribute('reason', $reason);
+ $movement->setAttribute('cost', $cost);
+
+ if($movement->save()) {
+ return $movement;
+ }
+
+ return false;
}
/**
@@ -648,20 +616,22 @@ private function generateStockMovement($before, $after, $reason = '', $cost = 0)
*
* @param int|float|string $cost
*/
- private function setCost($cost = 0)
+ protected function setCost($cost = 0)
{
- $this->cost = $cost;
+ $this->cost = (float) $cost;
}
/**
* Reverses the cost of a movement.
*/
- private function reverseCost()
+ protected function reverseCost()
{
- if ($this->isPositive($this->cost)) {
- $this->setCost(-abs($this->cost));
+ $cost = $this->getAttribute('cost');
+
+ if ($this->isPositive($cost)) {
+ $this->setCost(-abs($cost));
} else {
- $this->setCost(abs($this->cost));
+ $this->setCost(abs($cost));
}
}
@@ -670,7 +640,7 @@ private function reverseCost()
*
* @param string $reason
*/
- private function setReason($reason = '')
+ protected function setReason($reason = '')
{
$this->reason = $reason;
}
@@ -682,9 +652,9 @@ private function setReason($reason = '')
*
* @return bool
*/
- private function allowDuplicateMovementsEnabled()
+ protected function allowDuplicateMovementsEnabled()
{
- return Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'allow_duplicate_movements');
+ return Config::get('inventory.allow_duplicate_movements');
}
/**
@@ -694,8 +664,8 @@ private function allowDuplicateMovementsEnabled()
*
* @return bool
*/
- private function rollbackCostEnabled()
+ protected function rollbackCostEnabled()
{
- return Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'rollback_cost');
+ return Config::get('inventory.rollback_cost');
}
}
diff --git a/src/Traits/InventoryTrait.php b/src/Traits/InventoryTrait.php
index 87a57b90..ba6190b3 100644
--- a/src/Traits/InventoryTrait.php
+++ b/src/Traits/InventoryTrait.php
@@ -2,40 +2,17 @@
namespace Stevebauman\Inventory\Traits;
-use Illuminate\Database\Eloquent\Model;
-use Stevebauman\Inventory\Exceptions\InvalidSupplierException;
use Stevebauman\Inventory\Exceptions\SkuAlreadyExistsException;
use Stevebauman\Inventory\Exceptions\StockNotFoundException;
use Stevebauman\Inventory\Exceptions\StockAlreadyExistsException;
-use Stevebauman\Inventory\InventoryServiceProvider;
+use Stevebauman\Inventory\Helper;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
-/**
- * Trait InventoryTrait.
- */
trait InventoryTrait
{
- /*
- * Location helper functions
- */
- use LocationTrait;
-
- /*
- * Verification helper functions
- */
- use VerifyTrait;
-
- /*
- * Set's the models constructor method to automatically assign the
- * user_id's attribute to the current logged in user
- */
- use UserIdentificationTrait;
-
- /*
- * Helpers for starting database transactions
- */
- use DatabaseTransactionTrait;
+ use CommonMethodsTrait;
/**
* The hasOne category relationship.
@@ -83,7 +60,7 @@ public static function bootInventoryTrait()
* is being created
*/
static::creating(function (Model $record) {
- $record->user_id = static::getCurrentUserId();
+ $record->setAttribute('user_id', Helper::getCurrentUserId());
});
/*
@@ -222,28 +199,23 @@ public function isInStock()
* Creates a stock record to the current inventory item.
*
* @param int|float|string $quantity
- * @param $location
+ * @param Model $location
* @param string $reason
* @param int|float|string $cost
- * @param null $aisle
- * @param null $row
- * @param null $bin
+ * @param string $aisle
+ * @param string $row
+ * @param string $bin
*
* @throws StockAlreadyExistsException
* @throws StockNotFoundException
- * @throws \Stevebauman\Inventory\Exceptions\InvalidLocationException
* @throws \Stevebauman\Inventory\Exceptions\NoUserLoggedInException
*
* @return Model
*/
- public function createStockOnLocation($quantity, $location, $reason = '', $cost = 0, $aisle = null, $row = null, $bin = null)
+ public function createStockOnLocation($quantity, Model $location, $reason = '', $cost = 0, $aisle = null, $row = null, $bin = null)
{
- $location = $this->getLocation($location);
-
try {
- /*
- * We want to make sure stock doesn't exist on the specified location already
- */
+ // We want to make sure stock doesn't exist on the specified location already
if ($this->getStockFromLocation($location)) {
$message = Lang::get('inventory::exceptions.StockAlreadyExistsException', [
'location' => $location->name,
@@ -252,28 +224,19 @@ public function createStockOnLocation($quantity, $location, $reason = '', $cost
throw new StockAlreadyExistsException($message);
}
} catch (StockNotFoundException $e) {
- /*
- * A stock record wasn't found on this location, we'll create one
- */
- $insert = [
- 'inventory_id' => $this->getKey(),
- 'location_id' => $location->getKey(),
- 'quantity' => 0,
- 'aisle' => $aisle,
- 'row' => $row,
- 'bin' => $bin,
- ];
-
- /*
- * We'll perform a create so a 'first' movement is generated
- */
- $stock = $this->stocks()->create($insert);
-
- /*
- * Now we'll 'put' the inserted quantity onto the generated stock
- * and return the results
- */
- return $stock->put($quantity, $reason, $cost);
+ // A stock record wasn't found on this location, we'll create one.
+ $stock = $this->stocks()->getRelated()->newInstance();
+
+ $stock->setAttribute('inventory_id', $this->getKey());
+ $stock->setAttribute('location_id', $location->getKey());
+ $stock->setAttribute('quantity', 0);
+ $stock->setAttribute('aisle', $aisle);
+ $stock->setAttribute('row', $row);
+ $stock->setAttribute('bin', $bin);
+
+ if($stock->save()) {
+ return $stock->put($quantity, $reason, $cost);
+ }
}
return false;
@@ -283,17 +246,14 @@ public function createStockOnLocation($quantity, $location, $reason = '', $cost
* Instantiates a new stock on the specified
* location on the current item.
*
- * @param $location
+ * @param Model $location
*
* @throws StockAlreadyExistsException
- * @throws \Stevebauman\Inventory\Exceptions\InvalidLocationException
*
* @return \Illuminate\Database\Eloquent\Model
*/
- public function newStockOnLocation($location)
+ public function newStockOnLocation(Model $location)
{
- $location = $this->getLocation($location);
-
try {
/*
* We want to make sure stock doesn't exist on the specified location already
@@ -306,17 +266,12 @@ public function newStockOnLocation($location)
throw new StockAlreadyExistsException($message);
}
} catch (StockNotFoundException $e) {
- /*
- * Create a new stock model instance
- */
- $stock = $this->stocks()->getRelated();
+ // Create a new stock model instance
+ $stock = $this->stocks()->getRelated()->newInstance();
- /*
- * Assign the known attributes
- * so devs don't have to
- */
- $stock->inventory_id = $this->getKey();
- $stock->location_id = $location->getKey();
+ // Assign the known attributes so devs don't have to
+ $stock->setAttribute('inventory_id', $this->getKey());
+ $stock->setAttribute('location_id', $location->getKey());
return $stock;
}
@@ -326,27 +281,19 @@ public function newStockOnLocation($location)
* Takes the specified amount ($quantity) of stock from specified stock location.
*
* @param int|float|string $quantity
- * @param $location
+ * @param Model $location
* @param string $reason
*
* @throws StockNotFoundException
*
* @return array
*/
- public function takeFromLocation($quantity, $location, $reason = '')
+ public function takeFromLocation($quantity, Model $location, $reason = '')
{
- /*
- * If the specified location is an array, we must be taking from
- * multiple locations
- */
- if (is_array($location)) {
- return $this->takeFromManyLocations($quantity, $location, $reason);
- } else {
- $stock = $this->getStockFromLocation($location);
+ $stock = $this->getStockFromLocation($location);
- if ($stock->take($quantity, $reason)) {
- return $this;
- }
+ if ($stock && $stock->take($quantity, $reason)) {
+ return $this;
}
return false;
@@ -405,10 +352,10 @@ public function removeFromManyLocations($quantity, $locations = [], $reason = ''
}
/**
- * Puts the specified amount ($quantity) of stock into the specified stock location(s).
+ * Puts the specified amount ($quantity) of stock into the specified stock location.
*
* @param int|float|string $quantity
- * @param $location
+ * @param Model $location
* @param string $reason
* @param int|float|string $cost
*
@@ -416,16 +363,12 @@ public function removeFromManyLocations($quantity, $locations = [], $reason = ''
*
* @return array
*/
- public function putToLocation($quantity, $location, $reason = '', $cost = 0)
+ public function putToLocation($quantity, Model $location, $reason = '', $cost = 0)
{
- if (is_array($location)) {
- return $this->putToManyLocations($quantity, $location);
- } else {
- $stock = $this->getStockFromLocation($location);
+ $stock = $this->getStockFromLocation($location);
- if ($stock->put($quantity, $reason, $cost)) {
- return $this;
- }
+ if ($stock && $stock->put($quantity, $reason, $cost)) {
+ return $this;
}
return false;
@@ -466,7 +409,7 @@ public function putToManyLocations($quantity, $locations = [], $reason = '', $co
*
* @return array
*/
- public function addToLocation($quantity, $location, $reason = '', $cost = 0)
+ public function addToLocation($quantity, Model $location, $reason = '', $cost = 0)
{
return $this->putToLocation($quantity, $location, $reason, $cost);
}
@@ -489,46 +432,38 @@ public function addToManyLocations($quantity, $locations = [], $reason = '', $co
/**
* Moves a stock from one location to another.
*
- * @param $fromLocation
- * @param $toLocation
+ * @param Model $fromLocation
+ * @param Model $toLocation
*
* @throws StockNotFoundException
*
* @return mixed
*/
- public function moveStock($fromLocation, $toLocation)
+ public function moveStock(Model $fromLocation, Model $toLocation)
{
$stock = $this->getStockFromLocation($fromLocation);
- $toLocation = $this->getLocation($toLocation);
-
return $stock->moveTo($toLocation);
}
/**
* Retrieves an inventory stock from a given location.
*
- * @param $location
+ * @param Model $location
*
- * @throws \Stevebauman\Inventory\Exceptions\InvalidLocationException
* @throws StockNotFoundException
*
* @return mixed
*/
- public function getStockFromLocation($location)
+ public function getStockFromLocation(Model $location)
{
- $location = $this->getLocation($location);
-
- $stock = $this->stocks()
- ->where('inventory_id', $this->getKey())
- ->where('location_id', $location->getKey())
- ->first();
+ $stock = $this->stocks()->where('location_id', $location->getKey())->first();
if ($stock) {
return $stock;
} else {
$message = Lang::get('inventory::exceptions.StockNotFoundException', [
- 'location' => $location->name,
+ 'location' => $location->getAttribute('name'),
]);
throw new StockNotFoundException($message);
@@ -543,7 +478,7 @@ public function getStockFromLocation($location)
public function getSku()
{
if ($this->hasSku()) {
- return $this->sku->code;
+ return $this->sku->getAttribute('code');
}
return;
@@ -570,67 +505,45 @@ public function getSkuCodeAttribute()
*/
public function generateSku()
{
- /*
- * Make sure sku generation is enabled and the item has a category, if not we'll return false.
- */
+ // Make sure sku generation is enabled and the item has a category, if not we'll return false.
if (!$this->skusEnabled() || !$this->hasCategory()) {
return false;
}
- /*
- * If the item already has an SKU, we'll return it
- */
+ // If the item already has an SKU, we'll return it
if ($this->hasSku()) {
return $this->sku;
}
- /*
- * Get the set SKU code length from the configuration file
- */
- $codeLength = Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'sku_code_length');
+ // Get the set SKU code length from the configuration file
+ $codeLength = Config::get('inventory.sku_code_length');
- /*
- * Get the set SKU prefix length from the configuration file
- */
- $prefixLength = Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'sku_prefix_length');
+ // Get the set SKU prefix length from the configuration file
+ $prefixLength = Config::get('inventory.sku_prefix_length');
- /*
- * Get the set SKU separator
- */
- $skuSeparator = Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'sku_separator');
+ // Get the set SKU separator
+ $skuSeparator = Config::get('inventory.sku_separator');
- /*
- * Make sure we trim empty spaces in the separator if it's a string, otherwise we'll
- * set it to NULL
- */
+ // Make sure we trim empty spaces in the separator if
+ // it's a string, otherwise we'll set it to NULL
$skuSeparator = (is_string($skuSeparator) ? trim($skuSeparator) : null);
- /*
- * Trim the category name to remove blank spaces, then
- * grab the first 3 letters of the string, and uppercase them
- */
- $prefix = strtoupper(substr(trim($this->category->name), 0, intval($prefixLength)));
+ // Trim the category name to remove blank spaces, then grab
+ // the first 3 letters of the string, and uppercase them
+ $prefix = strtoupper(substr(trim($this->category->getAttribute('name')), 0, intval($prefixLength)));
- /*
- * We'll make sure the prefix length is greater than zero before we try and
- * generate an SKU
- */
+ // We'll make sure the prefix length is greater
+ // than zero before we try and generate an SKU
if (strlen($prefix) > 0) {
- /*
- * Create the numerical code by the items ID
- * to accompany the prefix and pad left zeros
- */
+ // Create the numerical code by the items ID to
+ // accompany the prefix and pad left zeros
$code = str_pad($this->getKey(), $codeLength, '0', STR_PAD_LEFT);
- /*
- * Process the generation
- */
+ // Return and process the generation
return $this->processSkuGeneration($this->getKey(), $prefix.$skuSeparator.$code);
}
- /*
- * Always return false on generation failure
- */
+ // Always return false on generation failure
return false;
}
@@ -647,37 +560,25 @@ public function regenerateSku()
$sku = $this->sku()->first();
if ($sku) {
- /*
- * Capture current SKU
- */
+ // Capture current SKU
$previousSku = $sku;
- /*
- * Delete current SKU
- */
+ // Delete current SKU
$sku->delete();
- /*
- * Try to generate a new SKU
- */
+ // Try to generate a new SKU
$newSku = $this->generateSku();
- /*
- * New sku generation successful, return it
- */
+ // New sku generation successful, return it
if ($newSku) {
return $newSku;
}
- /*
- * Failed generating a new sku, we'll restore the old one
- */
+ // Failed generating a new sku, we'll restore the old one
return $this->processSkuGeneration($this->getKey(), $previousSku->code);
}
- /*
- * Always generate an SKU if one doesn't exist
- */
+ // Always generate an SKU if one doesn't exist
return $this->generateSku();
}
@@ -696,31 +597,22 @@ public function regenerateSku()
*/
public function createSku($code, $overwrite = false)
{
- /*
- * Get the current SKU record
- */
+ // Get the current SKU record
$sku = $this->sku()->first();
if ($sku) {
- /*
- * The dev doesn't want the SKU overridden,
- * we'll thrown an exception
- */
+ // The dev doesn't want the SKU overridden, we'll thrown an exception
if (!$overwrite) {
$message = Lang::get('inventory::exceptions.SkuAlreadyExistsException');
throw new SkuAlreadyExistsException($message);
}
- /*
- * Overwrite is true, lets update the current SKU
- */
+ // Overwrite is true, lets update the current SKU
return $this->updateSku($code, $sku);
}
- /*
- * No SKU exists, lets create one
- */
+ // No SKU exists, lets create one
return $this->processSkuGeneration($this->getKey(), $code);
}
@@ -735,9 +627,7 @@ public function createSku($code, $overwrite = false)
*/
public function updateSku($code, $sku = null)
{
- /*
- * Get the current SKU record if one isn't supplied
- */
+ // Get the current SKU record if one isn't supplied
if (!$sku) {
$sku = $this->sku()->first();
}
@@ -753,112 +643,6 @@ public function updateSku($code, $sku = null)
return $this->processSkuUpdate($sku, $code);
}
- /**
- * Adds all of the specified suppliers inside
- * the array to the current inventory item.
- *
- * @param array $suppliers
- *
- * @return bool
- */
- public function addSuppliers($suppliers = [])
- {
- foreach ($suppliers as $supplier) {
- $this->addSupplier($supplier);
- }
-
- return true;
- }
-
- /**
- * Removes all suppliers from the current item.
- *
- * @return bool
- */
- public function removeAllSuppliers()
- {
- $suppliers = $this->suppliers()->get();
-
- foreach ($suppliers as $supplier) {
- $this->removeSupplier($supplier);
- }
-
- return true;
- }
-
- /**
- * Removes all of the specified suppliers inside
- * the array from the current inventory item.
- *
- * @param array $suppliers
- *
- * @return bool
- */
- public function removeSuppliers($suppliers = [])
- {
- foreach ($suppliers as $supplier) {
- $this->removeSupplier($supplier);
- }
-
- return true;
- }
-
- /**
- * Adds the specified supplier to the current inventory item.
- *
- * @param $supplier
- *
- * @throws InvalidSupplierException
- *
- * @return bool
- */
- public function addSupplier($supplier)
- {
- $supplier = $this->getSupplier($supplier);
-
- return $this->processSupplierAttach($supplier);
- }
-
- /**
- * Removes the specified supplier from the current inventory item.
- *
- * @param $supplier
- *
- * @throws InvalidSupplierException
- *
- * @return bool
- */
- public function removeSupplier($supplier)
- {
- $supplier = $this->getSupplier($supplier);
-
- return $this->processSupplierDetach($supplier);
- }
-
- /**
- * Retrieves a supplier from the specified variable.
- *
- * @param $supplier
- *
- * @throws InvalidSupplierException
- *
- * @return mixed
- */
- public function getSupplier($supplier)
- {
- if ($this->isNumeric($supplier)) {
- return $this->getSupplierById($supplier);
- } elseif ($this->isModel($supplier)) {
- return $supplier;
- } else {
- $message = Lang::get('inventory::exceptions.InvalidSupplierException', [
- 'supplier' => $supplier,
- ]);
-
- throw new InvalidSupplierException($message);
- }
- }
-
/**
* Processes an SKU generation covered by database transactions.
*
@@ -867,26 +651,25 @@ public function getSupplier($supplier)
*
* @return bool|mixed
*/
- private function processSkuGeneration($inventoryId, $code)
+ protected function processSkuGeneration($inventoryId, $code)
{
$this->dbStartTransaction();
try {
- $insert = [
- 'inventory_id' => $inventoryId,
- 'code' => $code,
- ];
+ $sku = $this->sku()->getRelated()->newInstance();
- $record = $this->sku()->create($insert);
+ $sku->setAttribute('inventory_id', $inventoryId);
+ $sku->setAttribute('code', $code);
- if ($record) {
+ if ($sku->save()) {
$this->dbCommitTransaction();
$this->fireEvent('inventory.sku.generated', [
'item' => $this,
+ 'sku' => $sku,
]);
- return $record;
+ return $sku;
}
} catch (\Exception $e) {
$this->dbRollbackTransaction();
@@ -904,7 +687,7 @@ private function processSkuGeneration($inventoryId, $code)
*
* @return mixed|bool
*/
- private function processSkuUpdate(Model $sku, $code)
+ protected function processSkuUpdate(Model $sku, $code)
{
$this->dbStartTransaction();
@@ -921,84 +704,14 @@ private function processSkuUpdate(Model $sku, $code)
return false;
}
- /**
- * Processes attaching a supplier to an inventory item.
- *
- * @param Model $supplier
- *
- * @return bool
- */
- private function processSupplierAttach(Model $supplier)
- {
- $this->dbStartTransaction();
-
- try {
- $this->suppliers()->attach($supplier);
-
- $this->dbCommitTransaction();
-
- $this->fireEvent('inventory.supplier.attached', [
- 'item' => $this,
- 'supplier' => $supplier,
- ]);
-
- return true;
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
- }
-
- return false;
- }
-
- /**
- * Processes detaching a supplier.
- *
- * @param Model $supplier
- *
- * @return bool
- */
- private function processSupplierDetach(Model $supplier)
- {
- $this->dbStartTransaction();
-
- try {
- $this->suppliers()->detach($supplier);
-
- $this->dbCommitTransaction();
-
- $this->fireEvent('inventory.supplier.detached', [
- 'item' => $this,
- 'supplier' => $supplier,
- ]);
-
- return true;
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
- }
-
- return false;
- }
-
- /**
- * Returns a supplier by the specified ID.
- *
- * @param int|string $id
- *
- * @return mixed
- */
- private function getSupplierById($id)
- {
- return $this->suppliers()->find($id);
- }
-
/**
* Returns the configuration option for the
* enablement of automatic SKU generation.
*
* @return mixed
*/
- private function skusEnabled()
+ protected function skusEnabled()
{
- return Config::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'skus_enabled', false);
+ return Config::get('inventory.skus_enabled', false);
}
}
diff --git a/src/Traits/InventoryTransactionHistoryTrait.php b/src/Traits/InventoryTransactionHistoryTrait.php
index 71fdbc4c..45dc5c91 100644
--- a/src/Traits/InventoryTransactionHistoryTrait.php
+++ b/src/Traits/InventoryTransactionHistoryTrait.php
@@ -2,25 +2,20 @@
namespace Stevebauman\Inventory\Traits;
+use Stevebauman\Inventory\Helper;
use Illuminate\Database\Eloquent\Model;
-/**
- * Trait InventoryTransactionHistoryTrait.
- */
trait InventoryTransactionHistoryTrait
{
- /*
- * Provides user identification to the model
- */
- use UserIdentificationTrait;
-
/**
* Make sure we try and assign the current user if enabled.
+ *
+ * @return void
*/
public static function bootInventoryTransactionHistoryTrait()
{
static::creating(function (Model $model) {
- $model->user_id = static::getCurrentUserId();
+ $model->setAttribute('user_id', Helper::getCurrentUserId());
});
}
diff --git a/src/Traits/InventoryTransactionTrait.php b/src/Traits/InventoryTransactionTrait.php
index a6cb3719..03014fa3 100644
--- a/src/Traits/InventoryTransactionTrait.php
+++ b/src/Traits/InventoryTransactionTrait.php
@@ -7,28 +7,13 @@
use Stevebauman\Inventory\Exceptions\StockNotFoundException;
use Stevebauman\Inventory\Exceptions\InvalidTransactionStateException;
use Stevebauman\Inventory\InventoryServiceProvider;
+use Stevebauman\Inventory\Helper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Lang;
-/**
- * Trait InventoryTransactionTrait.
- */
trait InventoryTransactionTrait
{
- /*
- * Provides user identification
- */
- use UserIdentificationTrait;
-
- /*
- * Provides database transactions
- */
- use DatabaseTransactionTrait;
-
- /*
- * Provides some verification methods
- */
- use VerifyTrait;
+ use CommonMethodsTrait;
/**
* Stores the state before an update.
@@ -47,11 +32,13 @@ trait InventoryTransactionTrait
/**
* Overrides the models boot function to generate a new transaction history
* record when it is created and updated.
+ *
+ * @return void
*/
public static function bootInventoryTransactionTrait()
{
static::creating(function (Model $model) {
- $model->user_id = static::getCurrentUserId();
+ $model->setAttribute('user_id', Helper::getCurrentUserId());
if (!$model->beforeState) {
$model->beforeState = $model::STATE_OPENED;
@@ -95,13 +82,7 @@ public static function getByState($state)
*/
public function postCreate()
{
- /*
- * Make sure the transaction does not already have a history record
- * before creating one
- */
- if (!$this->getLastHistoryRecord()) {
- $this->generateTransactionHistory($this->beforeState, $this->state, 0, $this->quantity);
- }
+ $this->generateTransactionHistory($this->beforeState, $this->getAttribute('state'), 0, $this->getAttribute('quantity'));
}
/**
@@ -109,7 +90,7 @@ public function postCreate()
*/
public function postUpdate()
{
- $this->generateTransactionHistory($this->beforeState, $this->state, $this->beforeQuantity, $this->quantity);
+ $this->generateTransactionHistory($this->beforeState, $this->getAttribute('state'), $this->beforeQuantity, $this->getAttribute('quantity'));
}
/**
@@ -122,7 +103,7 @@ abstract public function stock();
/**
* The hasMany histories relationship.
*
- * @return mixed
+ * @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
abstract public function histories();
@@ -134,7 +115,7 @@ abstract public function histories();
*/
public function isCheckout()
{
- return ($this->state === $this::STATE_COMMERCE_CHECKOUT ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_COMMERCE_CHECKOUT ? true : false);
}
/**
@@ -145,7 +126,7 @@ public function isCheckout()
*/
public function isReservation()
{
- return ($this->state === $this::STATE_COMMERCE_RESERVED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_COMMERCE_RESERVED ? true : false);
}
/**
@@ -156,7 +137,7 @@ public function isReservation()
*/
public function isBackOrder()
{
- return ($this->state === $this::STATE_COMMERCE_BACK_ORDERED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_COMMERCE_BACK_ORDERED ? true : false);
}
/**
@@ -167,7 +148,7 @@ public function isBackOrder()
*/
public function isReturn()
{
- return ($this->state === $this::STATE_COMMERCE_RETURNED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_COMMERCE_RETURNED ? true : false);
}
/**
@@ -178,7 +159,7 @@ public function isReturn()
*/
public function isSold()
{
- return ($this->state === $this::STATE_COMMERCE_SOLD ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_COMMERCE_SOLD ? true : false);
}
/**
@@ -189,7 +170,7 @@ public function isSold()
*/
public function isCancelled()
{
- return ($this->state === $this::STATE_CANCELLED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_CANCELLED ? true : false);
}
/**
@@ -200,7 +181,7 @@ public function isCancelled()
*/
public function isOrder()
{
- return ($this->state === $this::STATE_ORDERED_PENDING ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_ORDERED_PENDING ? true : false);
}
/**
@@ -211,7 +192,7 @@ public function isOrder()
*/
public function isOrderReceived()
{
- return ($this->state === $this::STATE_ORDERED_RECEIVED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_ORDERED_RECEIVED ? true : false);
}
/**
@@ -222,7 +203,7 @@ public function isOrderReceived()
*/
public function isOnHold()
{
- return ($this->state === $this::STATE_INVENTORY_ON_HOLD ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_INVENTORY_ON_HOLD ? true : false);
}
/**
@@ -233,7 +214,7 @@ public function isOnHold()
*/
public function isReleased()
{
- return ($this->state === $this::STATE_INVENTORY_RELEASED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_INVENTORY_RELEASED ? true : false);
}
/**
@@ -244,7 +225,7 @@ public function isReleased()
*/
public function isRemoved()
{
- return ($this->state === $this::STATE_INVENTORY_REMOVED ? true : false);
+ return ($this->getAttribute('state') === $this::STATE_INVENTORY_REMOVED ? true : false);
}
/**
@@ -264,8 +245,8 @@ public function isRemoved()
public function checkout($quantity = 0, $reason = '', $cost = 0)
{
/*
- * Only allow a transaction that has a previous state of null, opened and reserved
- * to use the checkout function
+ * Only allow a transaction that has a previous state of
+ * null, opened and reserved to use the checkout function
*/
$this->validatePreviousState([
null,
@@ -277,11 +258,10 @@ public function checkout($quantity = 0, $reason = '', $cost = 0)
return $this->checkoutFromReserved();
}
- $this->quantity = $quantity;
-
- $this->state = $this::STATE_COMMERCE_CHECKOUT;
+ $this->setAttribute('quantity', $quantity);
+ $this->setAttribute('state', $this::STATE_COMMERCE_CHECKOUT);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('checkout');
}
@@ -329,7 +309,7 @@ public function sold($quantity = 0, $reason = '', $cost = 0)
/*
* Mark the current state sold
*/
- $this->state = $this::STATE_COMMERCE_SOLD;
+ $this->setAttribute('state', $this::STATE_COMMERCE_SOLD);
return $this->processSave('inventory.transaction.sold');
}
@@ -348,22 +328,17 @@ public function sold($quantity = 0, $reason = '', $cost = 0)
*/
public function soldAmount($quantity, $reason = '', $cost = 0)
{
- /*
- * Only allow a previous state of null or opened
- */
+ // Only allow a previous state of null or opened
$this->validatePreviousState([
null,
$this::STATE_OPENED,
], $this::STATE_COMMERCE_SOLD);
- /*
- * Mark the current state sold
- */
- $this->state = $this::STATE_COMMERCE_SOLD;
-
- $this->quantity = $quantity;
+ // Mark the current state sold
+ $this->setAttribute('state', $this::STATE_COMMERCE_SOLD);
+ $this->setAttribute('quantity', $quantity);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('sold-amount');
}
@@ -416,12 +391,9 @@ public function returned($quantity = 0, $reason = '', $cost = 0)
*/
public function returnedPartial($quantity, $reason = '', $cost = 0)
{
- /*
- * If the inserted quantity is equal to or greater than
- * the quantity inside the transaction,
- * they must be returning all of the stock
- */
- if ($quantity == $this->quantity || $quantity > $this->quantity) {
+ $current = $this->getAttribute('quantity');
+
+ if ((float) $quantity === (float) $current || $quantity > $current) {
return $this->returnedAll($reason, $cost);
}
@@ -436,24 +408,18 @@ public function returnedPartial($quantity, $reason = '', $cost = 0)
$this::STATE_COMMERCE_RETURNED_PARTIAL,
], $this::STATE_COMMERCE_RETURNED_PARTIAL);
- /*
- * Retrieve the previous state for returning the transaction
- * to it's original state
- */
- $previousState = $this->state;
+ // Retrieve the previous state for returning the transaction to it's original state
+ $previousState = $this->getAttribute('state');
- /*
- * Set a new state so a history record is created
- */
- $this->state = $this::STATE_COMMERCE_RETURNED_PARTIAL;
+ // Set a new state so a history record is created
+ $this->setAttribute('state', $this::STATE_COMMERCE_RETURNED_PARTIAL);
- /*
- * Set the new left-over quantity from removing
- * the amount returned
- */
- $this->quantity = $this->quantity - $quantity;
+ // Set the new left-over quantity from removing the amount returned
+ $left = (float) $current - (float) $quantity;
- if (!$reason) {
+ $this->setAttribute('quantity', $left);
+
+ if (empty($reason)) {
$reason = $this->getTransactionReason('returned-partial');
}
@@ -488,24 +454,22 @@ public function returnedAll($reason = '', $cost = 0)
$this::STATE_COMMERCE_RETURNED_PARTIAL,
], $this::STATE_COMMERCE_RETURNED);
- /*
- * Set the state to returned
- */
- $this->state = $this::STATE_COMMERCE_RETURNED;
+ // Set the state to returned
+ $this->setAttribute('state', $this::STATE_COMMERCE_RETURNED);
- $originalQuantity = $this->quantity;
+ $current = $this->getAttribute('quantity');
/*
* Set the quantity to zero because we are
* returning all of the stock
*/
- $this->quantity = 0;
+ $this->setAttribute('quantity', 0);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('returned');
}
- return $this->processStockPutAndSave($originalQuantity, 'inventory.transaction.removed', $reason, $cost);
+ return $this->processStockPutAndSave($current, 'inventory.transaction.removed', $reason, $cost);
}
/**
@@ -541,11 +505,10 @@ public function reserved($quantity = 0, $backOrder = false, $reason = '', $cost
return $this->reservedFromCheckout();
}
- $this->state = $this::STATE_COMMERCE_RESERVED;
+ $this->setAttribute('quantity', $quantity);
+ $this->setAttribute('state', $this::STATE_COMMERCE_RESERVED);
- $this->quantity = $quantity;
-
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('reserved');
}
@@ -584,9 +547,8 @@ public function backOrder($quantity)
$this::STATE_OPENED,
], $this::STATE_COMMERCE_BACK_ORDERED);
- $this->state = $this::STATE_COMMERCE_BACK_ORDERED;
-
- $this->quantity = $quantity;
+ $this->setAttribute('state', $this::STATE_COMMERCE_BACK_ORDERED);
+ $this->setAttribute('quantity', $quantity);
return $this->processSave('inventory.transaction.back-order');
}
@@ -613,14 +575,14 @@ public function fillBackOrder($reason = '', $cost = 0)
$this::STATE_COMMERCE_BACK_ORDERED,
], $this::STATE_COMMERCE_BACK_ORDER_FILLED);
- $this->state = $this::STATE_COMMERCE_BACK_ORDER_FILLED;
+ $this->setAttribute('state', $this::STATE_COMMERCE_BACK_ORDER_FILLED);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('back-order-filled');
}
try {
- return $this->processStockTakeAndSave($this->quantity, 'inventory.transaction.back-order.filled', $reason, $cost);
+ return $this->processStockTakeAndSave($this->getAttribute('quantity'), 'inventory.transaction.back-order.filled', $reason, $cost);
} catch (NotEnoughStockException $e) {
}
@@ -649,9 +611,8 @@ public function ordered($quantity)
$this::STATE_ORDERED_RECEIVED_PARTIAL,
], $this::STATE_ORDERED_PENDING);
- $this->quantity = $quantity;
-
- $this->state = $this::STATE_ORDERED_PENDING;
+ $this->setAttribute('quantity', $quantity);
+ $this->setAttribute('state', $this::STATE_ORDERED_PENDING);
return $this->processSave('inventory.transaction.ordered');
}
@@ -698,13 +659,13 @@ public function receivedAll($reason = '', $cost = 0)
$this::STATE_ORDERED_PENDING,
], $this::STATE_ORDERED_RECEIVED);
- $received = $this->quantity;
+ $received = $this->getAttribute('quantity');
- $this->quantity = 0;
+ $this->setAttribute('quantity', 0);
- $this->state = $this::STATE_ORDERED_RECEIVED;
+ $this->setAttribute('state', $this::STATE_ORDERED_RECEIVED);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('received');
}
@@ -732,30 +693,27 @@ public function receivedAll($reason = '', $cost = 0)
*/
public function receivedPartial($quantity, $reason = '', $cost = 0)
{
- if ($quantity == $this->quantity || $quantity > $this->quantity) {
+ $current = $this->getAttribute('quantity');
+
+ if ((float) $quantity === (float) $current || $quantity > $current) {
return $this->receivedAll($reason, $cost);
}
- /*
- * Only allow the previous state of ordered
- */
+ // Only allow the previous state of ordered
$this->validatePreviousState([
$this::STATE_ORDERED_PENDING,
], $this::STATE_ORDERED_RECEIVED_PARTIAL);
- /*
- * Get the left over amount of quantity still to
- * be received
- */
- $left = $this->quantity - $quantity;
+ // Get the left over amount of quantity still to be received
+ $left = (float) $current - (float) $quantity;
- $this->quantity = $left;
+ $this->setAttribute('quantity', $left);
- $previousState = $this->state;
+ $previousState = $this->getAttribute('state');
- $this->state = $this::STATE_ORDERED_RECEIVED_PARTIAL;
+ $this->setAttribute('state', $this::STATE_ORDERED_RECEIVED_PARTIAL);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('received-partial');
}
@@ -786,11 +744,11 @@ public function hold($quantity, $reason = '', $cost = 0)
$this::STATE_OPENED,
], $this::STATE_INVENTORY_ON_HOLD);
- $this->quantity = $quantity;
+ $this->setAttribute('quantity', $quantity);
- $this->state = $this::STATE_INVENTORY_ON_HOLD;
+ $this->setAttribute('state', $this::STATE_INVENTORY_ON_HOLD);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('hold');
}
@@ -841,13 +799,13 @@ public function releaseAll($reason = '', $cost = 0)
$this::STATE_INVENTORY_ON_HOLD,
], $this::STATE_INVENTORY_RELEASED);
- $released = $this->quantity;
+ $released = $this->getAttribute('quantity');
- $this->quantity = 0;
+ $this->setAttribute('quantity', 0);
- $this->state = $this::STATE_INVENTORY_RELEASED;
+ $this->setAttribute('state', $this::STATE_INVENTORY_RELEASED);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('released');
}
@@ -870,7 +828,9 @@ public function releaseAll($reason = '', $cost = 0)
*/
public function releasePartial($quantity, $reason = '', $cost = 0)
{
- if ($quantity == $this->quantity || $quantity > $this->quantity) {
+ $current = $this->getAttribute('quantity');
+
+ if ((float) $quantity === (float) $current || $quantity > $current) {
return $this->releaseAll($reason, $cost);
}
@@ -878,13 +838,15 @@ public function releasePartial($quantity, $reason = '', $cost = 0)
$this::STATE_INVENTORY_ON_HOLD,
], $this::STATE_INVENTORY_RELEASED);
- $this->quantity = $this->quantity - $quantity;
+ $left = (float) $current - (float) $quantity;
+
+ $this->setAttribute('quantity', $left);
- $previousState = $this->state;
+ $previousState = $this->getAttribute('state');
- $this->state = $this::STATE_INVENTORY_RELEASED_PARTIAL;
+ $this->setAttribute('state', $this::STATE_INVENTORY_RELEASED_PARTIAL);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('released-partial');
}
@@ -941,9 +903,8 @@ public function removeAll()
$this::STATE_INVENTORY_ON_HOLD,
], $this::STATE_INVENTORY_REMOVED);
- $this->state = $this::STATE_INVENTORY_REMOVED;
-
- $this->quantity = 0;
+ $this->setAttribute('quantity', 0);
+ $this->setAttribute('state', $this::STATE_INVENTORY_REMOVED);
return $this->processSave('inventory.transaction.removed');
}
@@ -973,7 +934,9 @@ public function removePartial($quantity, $reason = '', $cost = 0)
* a transaction for removing a quantity from the current stock
*/
if ($this->isOnHold()) {
- if ($quantity == $this->quantity || $quantity > $this->quantity) {
+ $current = $this->getAttribute('quantity');
+
+ if ((float) $quantity === (float) $current || $quantity > $current) {
return $this->removeAll();
}
@@ -981,11 +944,13 @@ public function removePartial($quantity, $reason = '', $cost = 0)
$this::STATE_INVENTORY_ON_HOLD,
], $this::STATE_INVENTORY_REMOVED_PARTIAL);
- $this->quantity = $this->quantity - $quantity;
+ $left = (float) $current - (float) $quantity;
+
+ $this->setAttribute('quantity', $left);
- $previousState = $this->state;
+ $previousState = $this->getAttribute('state');
- $this->state = $this::STATE_INVENTORY_REMOVED_PARTIAL;
+ $this->setAttribute('state', $this::STATE_INVENTORY_REMOVED_PARTIAL);
if ($this->processSave('inventory.transaction.removed.partial')) {
return $this->returnToPreviousState($previousState);
@@ -1000,11 +965,11 @@ public function removePartial($quantity, $reason = '', $cost = 0)
$this::STATE_OPENED,
], $this::STATE_INVENTORY_REMOVED);
- $this->state = $this::STATE_INVENTORY_REMOVED;
+ $this->setAttribute('state', $this::STATE_INVENTORY_REMOVED);
- $this->quantity = $quantity;
+ $this->setAttribute('quantity', (float) $quantity);
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('removed');
}
@@ -1042,15 +1007,15 @@ public function cancel($reason = '', $cost = 0)
$this::STATE_INVENTORY_ON_HOLD,
], $this::STATE_CANCELLED);
- $beforeQuantity = $this->quantity;
- $beforeState = $this->state;
+ $beforeQuantity = $this->getAttribute('quantity');
+ $beforeState = $this->getAttribute('state');
- $this->quantity = 0;
- $this->state = $this::STATE_CANCELLED;
+ $this->setAttribute('quantity', 0);
+ $this->setAttribute('state', $this::STATE_CANCELLED);
$event = 'inventory.transaction.cancelled';
- if (!$reason) {
+ if (empty($reason)) {
$reason = $this->getTransactionReason('cancelled');
}
@@ -1137,7 +1102,7 @@ public function getLastHistoryRecord()
public function setQuantityAttribute($quantity)
{
if (!$this->isPositive($quantity)) {
- $message = Lang::get('inventory'.InventoryServiceProvider::$packageConfigSeparator.'exceptions.InvalidQuantityException');
+ $message = Lang::get('inventory::exceptions.InvalidQuantityException');
throw new InvalidQuantityException($message);
}
@@ -1168,9 +1133,9 @@ public function setStateAttribute($state)
*
* @return $this|bool
*/
- private function returnToPreviousState($previousState)
+ protected function returnToPreviousState($previousState)
{
- $this->state = $previousState;
+ $this->setAttribute('state', $previousState);
return $this->processSave();
}
@@ -1182,9 +1147,9 @@ private function returnToPreviousState($previousState)
*
* @return $this|bool
*/
- private function reservedFromCheckout()
+ protected function reservedFromCheckout()
{
- $this->state = $this::STATE_COMMERCE_RESERVED;
+ $this->setAttribute('state', $this::STATE_COMMERCE_RESERVED);
return $this->processSave('inventory.transaction.reserved');
}
@@ -1195,9 +1160,9 @@ private function reservedFromCheckout()
*
* @return $this|bool
*/
- private function checkoutFromReserved()
+ protected function checkoutFromReserved()
{
- $this->state = $this::STATE_COMMERCE_CHECKOUT;
+ $this->setAttribute('state', $this::STATE_COMMERCE_CHECKOUT);
return $this->processSave('inventory.transaction.checkout');
}
@@ -1213,10 +1178,12 @@ private function checkoutFromReserved()
*
* @return bool
*/
- private function validatePreviousState($allowedStates = [], $toState)
+ protected function validatePreviousState($allowedStates = [], $toState)
{
- if (!in_array($this->state, $allowedStates)) {
- $fromState = (!$this->state ? 'NULL' : $this->state);
+ $state = $this->getAttribute('state');
+
+ if (!in_array($state, $allowedStates)) {
+ $fromState = (!$state ? 'NULL' : $state);
$message = "Transaction state: $fromState cannot be changed to a: $toState state.";
@@ -1236,7 +1203,7 @@ private function validatePreviousState($allowedStates = [], $toState)
*
* @return bool
*/
- private function validateStateIsAvailable($state)
+ protected function validateStateIsAvailable($state)
{
if (!in_array($state, $this->getAvailableStates())) {
$message = "State: $state is an invalid state, and cannot be used.";
@@ -1261,7 +1228,7 @@ private function validateStateIsAvailable($state)
*
* @return $this|bool
*/
- private function processStockPutAndSave($quantity, $event = '', $reason = '', $cost = 0)
+ protected function processStockPutAndSave($quantity, $event = '', $reason = '', $cost = 0)
{
$stock = $this->getStockRecord();
@@ -1297,13 +1264,13 @@ private function processStockPutAndSave($quantity, $event = '', $reason = '', $c
*
* @return $this|bool
*/
- private function processStockTakeAndSave($quantity, $event = '', $reason = '', $cost = 0)
+ protected function processStockTakeAndSave($quantity, $event = '', $reason = '', $cost = 0)
{
$stock = $this->getStockRecord();
$stock->isValidQuantity($quantity);
- $stock->hasEnoughStock($this->quantity);
+ $stock->hasEnoughStock($this->getAttribute('quantity'));
$this->dbStartTransaction();
@@ -1332,7 +1299,7 @@ private function processStockTakeAndSave($quantity, $event = '', $reason = '', $
*
* @return $this|bool
*/
- private function processSave($event = '')
+ protected function processSave($event = '')
{
$this->dbStartTransaction();
@@ -1361,19 +1328,23 @@ private function processSave($event = '')
* @param int|float|string $quantityBefore
* @param int|float|string $quantityAfter
*
- * @return mixed
+ * @return bool|Model
*/
- private function generateTransactionHistory($stateBefore, $stateAfter, $quantityBefore = 0, $quantityAfter = 0)
+ protected function generateTransactionHistory($stateBefore, $stateAfter, $quantityBefore = 0, $quantityAfter = 0)
{
- $insert = [
- 'transaction_id' => $this->getKey(),
- 'state_before' => $stateBefore,
- 'state_after' => $stateAfter,
- 'quantity_before' => $quantityBefore,
- 'quantity_after' => $quantityAfter,
- ];
+ $history = $this->histories()->getRelated()->newInstance();
+
+ $history->setAttribute('transaction_id', $this->getKey());
+ $history->setAttribute('state_before', $stateBefore);
+ $history->setAttribute('state_after', $stateAfter);
+ $history->setAttribute('quantity_before', $quantityBefore);
+ $history->setAttribute('quantity_after', $quantityAfter);
- return $this->histories()->create($insert);
+ if($history->save()) {
+ return $history;
+ }
+
+ return false;
}
/**
@@ -1384,7 +1355,7 @@ private function generateTransactionHistory($stateBefore, $stateAfter, $quantity
*
* @return string
*/
- private function getTransactionReason($key)
+ protected function getTransactionReason($key)
{
$reason = Lang::get('inventory::reasons.transactions.'.$key, ['id' => $this->getKey(), 'date' => date('Y-m-d H:i:s')]);
@@ -1392,7 +1363,7 @@ private function getTransactionReason($key)
* Make sure we set the reason to null if no translation is found
* so the default stock change reason is used
*/
- if (!$reason) {
+ if (empty($reason)) {
$reason = null;
}
@@ -1404,7 +1375,7 @@ private function getTransactionReason($key)
*
* @return array
*/
- private function getAvailableStates()
+ protected function getAvailableStates()
{
return [
self::STATE_COMMERCE_CHECKOUT,
diff --git a/src/Traits/InventoryVariantTrait.php b/src/Traits/InventoryVariantTrait.php
index 162493b6..6af4ca9c 100644
--- a/src/Traits/InventoryVariantTrait.php
+++ b/src/Traits/InventoryVariantTrait.php
@@ -4,9 +4,6 @@
use Illuminate\Database\Eloquent\Model;
-/**
- * Trait InventoryVariantTrait.
- */
trait InventoryVariantTrait
{
/**
@@ -169,6 +166,8 @@ public function newVariant($name = '')
public function createVariant($name = '', $description = '', $categoryId = null, $metricId = null)
{
$variant = $this->newVariant($name);
+
+ $this->dbStartTransaction();
try {
if (!empty($description)) {
@@ -220,7 +219,7 @@ public function makeVariantOf(Model $item)
*
* @return $this|bool
*/
- private function processMakeVariant($itemId)
+ protected function processMakeVariant($itemId)
{
$this->dbStartTransaction();
diff --git a/src/Traits/LocationTrait.php b/src/Traits/LocationTrait.php
deleted file mode 100644
index ba30d713..00000000
--- a/src/Traits/LocationTrait.php
+++ /dev/null
@@ -1,47 +0,0 @@
-isLocation($location)) {
- return $location;
- } else {
- $message = Lang::get('inventory::exceptions.InvalidLocationException', [
- 'location' => $location,
- ]);
-
- throw new InvalidLocationException($message);
- }
- }
-
- /**
- * Returns true or false if the specified location is an instance of a model.
- *
- * @param mixed $object
- *
- * @return bool
- */
- private function isLocation($object)
- {
- return is_subclass_of($object, 'Illuminate\Database\Eloquent\Model');
- }
-}
diff --git a/src/Traits/SupplierTrait.php b/src/Traits/SupplierTrait.php
index f4e70ec8..1c7ee0f6 100644
--- a/src/Traits/SupplierTrait.php
+++ b/src/Traits/SupplierTrait.php
@@ -2,196 +2,12 @@
namespace Stevebauman\Inventory\Traits;
-use Stevebauman\Inventory\Exceptions\InvalidItemException;
-use Illuminate\Support\Facades\Lang;
-
-/**
- * Trait SupplierTrait.
- */
trait SupplierTrait
{
- use DatabaseTransactionTrait;
-
- use VerifyTrait;
-
/**
* The belongsToMany items relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
abstract public function items();
-
- /**
- * Adds all the specified items to the current supplier.
- *
- * @param array $items
- *
- * @return bool
- */
- public function addItems($items = [])
- {
- foreach ($items as $item) {
- $this->addItem($item);
- }
-
- return true;
- }
-
- /**
- * Adds the specified item to the current supplier.
- *
- * @param mixed $item
- *
- * @throws InvalidItemException
- *
- * @return bool
- */
- public function addItem($item)
- {
- $this->getItem($item);
-
- return $this->processItemAttach($item);
- }
-
- /**
- * Removes all items from the current supplier.
- *
- * @return bool
- */
- public function removeAllItems()
- {
- $items = $this->items()->get();
-
- foreach ($items as $item) {
- $this->removeItem($item);
- }
-
- return true;
- }
-
- /**
- * Removes all the specified items from the current supplier.
- *
- * @param array $items
- *
- * @return bool
- */
- public function removeItems($items = [])
- {
- foreach ($items as $item) {
- $this->removeItem($item);
- }
-
- return true;
- }
-
- /**
- * Removes the specified item from the current supplier.
- *
- * @param mixed $item
- *
- * @throws InvalidItemException
- *
- * @return bool
- */
- public function removeItem($item)
- {
- $item = $this->getItem($item);
-
- return $this->processItemDetach($item);
- }
-
- /**
- * Processes attaching the specified item to the current supplier.
- *
- * @param mixed $item
- *
- * @return bool
- */
- private function processItemAttach($item)
- {
- $this->dbStartTransaction();
-
- try {
- $this->items()->attach($item);
-
- $this->dbCommitTransaction();
-
- $this->fireEvent('inventory.supplier.attached', [
- 'item' => $item,
- 'supplier' => $this,
- ]);
-
- return true;
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
- }
-
- return false;
- }
-
- /**
- * Processes detaching the specified item from the current supplier.
- *
- * @param mixed $item
- *
- * @return bool
- */
- private function processItemDetach($item)
- {
- $this->dbStartTransaction();
-
- try {
- $this->items()->detach($item);
-
- $this->dbCommitTransaction();
-
- $this->fireEvent('inventory.supplier.detached', [
- 'item' => $item,
- 'supplier' => $this,
- ]);
-
- return true;
- } catch (\Exception $e) {
- $this->dbRollbackTransaction();
- }
-
- return false;
- }
-
- /**
- * Retrieves the specified item.
- *
- * @param mixed $item
- *
- * @throws InvalidItemException
- *
- * @return mixed
- */
- public function getItem($item)
- {
- if ($this->isNumeric($item)) {
- return $this->getItemById($item);
- } elseif ($this->isModel($item)) {
- return $item;
- } else {
- $message = Lang::get('inventory.exceptions.InvalidItemException', [
- 'item' => $item,
- ]);
-
- throw new InvalidItemException($message);
- }
- }
-
- /**
- * Retrieves an item by the specified ID.
- *
- * @param int|string $id
- *
- * @return mixed
- */
- private function getItemById($id)
- {
- return $this->items()->find($id);
- }
}
diff --git a/src/Traits/UserIdentificationTrait.php b/src/Traits/UserIdentificationTrait.php
deleted file mode 100644
index f265eea1..00000000
--- a/src/Traits/UserIdentificationTrait.php
+++ /dev/null
@@ -1,57 +0,0 @@
-id;
- }
- } elseif (class_exists('Illuminate\Auth') || class_exists('Illuminate\Support\Facades\Auth')) {
- if (\Auth::check()) {
- return \Auth::user()->getAuthIdentifier();
- }
- }
- } catch (\Exception $e) {
- }
-
- /*
- * Couldn't get the current logged in users ID, throw exception
- */
- $message = Lang::get('inventory::exceptions.NoUserLoggedInException');
-
- throw new NoUserLoggedInException($message);
- }
-}
diff --git a/src/Traits/VerifyTrait.php b/src/Traits/VerifyTrait.php
deleted file mode 100644
index b8e07166..00000000
--- a/src/Traits/VerifyTrait.php
+++ /dev/null
@@ -1,76 +0,0 @@
-isPositive($quantity)) {
- return true;
- }
-
- $message = Lang::get('inventory::exceptions.InvalidQuantityException', [
- 'quantity' => $quantity,
- ]);
-
- throw new InvalidQuantityException($message);
- }
-
- /**
- * Returns true/false if the number specified is numeric.
- *
- * @param int|float|string $number
- *
- * @return bool
- */
- private function isNumeric($number)
- {
- return (is_numeric($number) ? true : false);
- }
-
- /**
- * Returns true or false if the number inserted is positive.
- *
- * @param int|float|string $number
- *
- * @return bool
- */
- private function isPositive($number)
- {
- if ($this->isNumeric($number)) {
- return ($number >= 0 ? true : false);
- }
-
- return false;
- }
-
- /**
- * Returns true/false if the specified model is a subclass
- * of the Eloquent Model.
- *
- * @param mixed $model
- *
- * @return bool
- */
- private function isModel($model)
- {
- return is_subclass_of($model, 'Illuminate\Database\Eloquent\Model');
- }
-}
diff --git a/src/config/config.php b/src/config/config.php
deleted file mode 100644
index 219d15c1..00000000
--- a/src/config/config.php
+++ /dev/null
@@ -1,67 +0,0 @@
- false,
-
- /*
- * Allows inventory stock movements to have the same before and after quantity
- *
- * @var bool
- */
- 'allow_duplicate_movements' => true,
-
- /*
- * When set to true, this will reverse the cost in the rolled back movement.
- *
- * For example, if the movement's cost that is being rolled back is 500, the rolled back
- * movement will be -500.
- *
- * @var bool
- */
- 'rollback_cost' => true,
-
- /*
- * Enables SKUs to be automatically generated on item creation
- *
- * @var bool
- */
- 'skus_enabled' => true,
-
- /*
- * The sku prefix length, not including the code for example:
- *
- * An item with a category named 'Sauce', the sku prefix generated will be: SAU
- *
- * @var int
- */
- 'sku_prefix_length' => 3,
-
- /*
- * The sku code length, not including prefix for example:
- *
- * An item with an ID of 1 (one) the sku code will be: 000001
- *
- * @var int
- */
- 'sku_code_length' => 6,
-
- /*
- * The sku separator for use in separating the prefix from the code.
- *
- * For example, if a hyphen (-) is inserted in the string below, a possible
- * SKU might be 'DRI-00001'
- *
- * @var string
- */
- 'sku_separator' => '',
-
-];
diff --git a/src/helpers.php b/src/helpers.php
deleted file mode 100644
index 15bd378d..00000000
--- a/src/helpers.php
+++ /dev/null
@@ -1,35 +0,0 @@
-getAncestorsAndSelf();
-
- foreach ($ancestors as $ancestor) {
- if ($node->equals($ancestor) && $node->isRoot()) {
- $html .= sprintf('%s', $ancestor->name);
- } elseif ($node->equals($ancestor)) {
- $html .= sprintf(' > %s', $ancestor->name);
- } elseif ($ancestor->isRoot()) {
- $html .= sprintf('%s', $ancestor->name);
- } else {
- $html .= sprintf(' > %s', $ancestor->name);
- }
- }
-
- return $html;
- }
-
- return $node;
- }
-}
diff --git a/tests/FunctionalTestCase.php b/tests/FunctionalTestCase.php
index a1d13fc7..f6130dfc 100644
--- a/tests/FunctionalTestCase.php
+++ b/tests/FunctionalTestCase.php
@@ -2,279 +2,34 @@
namespace Stevebauman\Inventory\Tests;
-use Illuminate\Database\Capsule\Manager as DB;
+use Orchestra\Testbench\TestCase;
-abstract class FunctionalTestCase extends \PHPUnit_Framework_TestCase
+abstract class FunctionalTestCase extends TestCase
{
public function setUp()
{
parent::setUp();
- $this->configureDatabase();
- $this->migrateTables();
+ $this->artisan('migrate', [
+ '--database' => 'testbench',
+ '--realpath' => realpath(__DIR__.'/../src/Migrations'),
+ ]);
}
- private function configureDatabase()
+ protected function getEnvironmentSetup($app)
{
- $db = new DB();
-
- $db->addConnection([
- 'driver' => 'sqlite',
+ $app['config']->set('database.default', 'testbench');
+ $app['config']->set('database.connections.testbench', [
+ 'driver' => 'sqlite',
'database' => ':memory:',
- 'charset' => 'utf8',
- 'collation' => 'utf8_unicode_ci',
- 'prefix' => '',
+ 'prefix' => '',
]);
-
- $db->bootEloquent();
-
- $db->setAsGlobal();
}
- private function migrateTables()
+ protected function getPackageProviders()
{
- DB::schema()->create('users', function ($table) {
- $table->increments('id');
- $table->string('name');
- });
-
- DB::schema()->create('metrics', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('user_id')->unsigned()->nullable();
- $table->string('name');
- $table->string('symbol');
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
- });
-
- DB::schema()->create('categories', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('parent_id')->nullable()->index();
- $table->integer('lft')->nullable()->index();
- $table->integer('rgt')->nullable()->index();
- $table->integer('depth')->nullable();
- $table->string('name');
-
- /*
- * This field is for scoping categories, use it if you
- * want to store multiple nested sets on the same table
- */
- $table->string('belongs_to')->nullable();
- });
-
- DB::schema()->create('locations', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('parent_id')->nullable()->index();
- $table->integer('lft')->nullable()->index();
- $table->integer('rgt')->nullable()->index();
- $table->integer('depth')->nullable();
- $table->string('name');
-
- /*
- * This field is for scoping categories, use it if you
- * want to store multiple nested sets on the same table
- */
- $table->string('belongs_to')->nullable();
- });
-
- DB::schema()->create('inventories', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->softDeletes();
- $table->integer('category_id')->unsigned()->nullable();
- $table->integer('user_id')->unsigned()->nullable();
- $table->integer('metric_id')->unsigned();
- $table->string('name');
- $table->text('description')->nullable();
-
- $table->foreign('category_id')->references('id')->on('categories')
- ->onUpdate('restrict')
- ->onDelete('set null');
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
-
- $table->foreign('metric_id')->references('id')->on('metrics')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->create('inventory_stocks', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('user_id')->unsigned()->nullable();
- $table->integer('inventory_id')->unsigned();
- $table->integer('location_id')->unsigned();
- $table->decimal('quantity', 8, 2)->default(0);
- $table->string('aisle')->nullable();
- $table->string('row')->nullable();
- $table->string('bin')->nullable();
-
- /*
- * This allows only one stock to be created
- * on a single location
- */
- $table->unique(['inventory_id', 'location_id']);
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
-
- $table->foreign('inventory_id')->references('id')->on('inventories')
- ->onUpdate('restrict')
- ->onDelete('cascade');
-
- $table->foreign('location_id')->references('id')->on('locations')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->create('inventory_stock_movements', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('stock_id')->unsigned();
- $table->integer('user_id')->unsigned()->nullable();
- $table->decimal('before', 8, 2)->default(0);
- $table->decimal('after', 8, 2)->default(0);
- $table->decimal('cost', 8, 2)->default(0)->nullable();
- $table->string('reason')->nullable();
-
- $table->foreign('stock_id')->references('id')->on('inventory_stocks')
- ->onUpdate('restrict')
- ->onDelete('cascade');
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
- });
-
- DB::schema()->create('inventory_skus', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('inventory_id')->unsigned();
- $table->string('code', 20);
-
- $table->foreign('inventory_id')->references('id')->on('inventories')
- ->onUpdate('restrict')
- ->onDelete('cascade');
-
- /*
- * Make sure each SKU is unique
- */
- $table->unique(['code']);
- });
-
- DB::schema()->create('suppliers', function ($table) {
- $table->increments('id');
- $table->timestamps();
-
- $table->string('name');
- $table->string('address')->nullable();
- $table->string('postal_code')->nullable();
- $table->string('zip_code')->nullable();
- $table->string('region')->nullable();
- $table->string('city')->nullable();
- $table->string('country')->nullable();
- $table->string('contact_title')->nullable();
- $table->string('contact_name')->nullable();
- $table->string('contact_phone')->nullable();
- $table->string('contact_fax')->nullable();
- $table->string('contact_email')->nullable();
- });
-
- DB::schema()->create('inventory_suppliers', function ($table) {
- $table->increments('id');
- $table->timestamps();
-
- $table->integer('inventory_id')->unsigned();
- $table->integer('supplier_id')->unsigned();
-
- $table->foreign('inventory_id')->references('id')->on('inventories')
- ->onUpdate('restrict')
- ->onDelete('cascade');
-
- $table->foreign('supplier_id')->references('id')->on('suppliers')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->create('inventory_transactions', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('user_id')->unsigned()->nullable();
- $table->integer('stock_id')->unsigned();
- $table->string('name')->nullable();
- $table->string('state');
- $table->decimal('quantity', 8, 2)->default(0);
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
-
- $table->foreign('stock_id')->references('id')->on('inventory_stocks')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->create('inventory_transaction_histories', function ($table) {
- $table->increments('id');
- $table->timestamps();
- $table->integer('user_id')->unsigned()->nullable();
- $table->integer('transaction_id')->unsigned();
-
- /*
- * Allows tracking states for each transaction
- */
- $table->string('state_before');
- $table->string('state_after');
-
- /*
- * Allows tracking the quantities of each transaction
- */
- $table->string('quantity_before');
- $table->string('quantity_after');
-
- $table->foreign('user_id')->references('id')->on('users')
- ->onUpdate('restrict')
- ->onDelete('set null');
-
- $table->foreign('transaction_id')->references('id')->on('inventory_transactions')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->table('inventories', function ($table) {
- $table->integer('parent_id')->unsigned()->nullable()->after('id');
-
- $table->foreign('parent_id')->references('id')->on('inventories')
- ->onUpdate('restrict')
- ->onDelete('cascade');
- });
-
- DB::schema()->table('inventories', function ($table) {
- $table->boolean('is_assembly')->default(false);
- });
-
- DB::schema()->create('inventory_assemblies', function ($table) {
-
- $table->increments('id');
- $table->timestamps();
- $table->integer('inventory_id')->unsigned();
- $table->integer('part_id')->unsigned();
- $table->integer('quantity')->nullable();
-
- // Extra column for testing
- $table->string('extra')->nullable();
-
- $table->foreign('inventory_id')->references('id')->on('inventories')->onDelete('cascade');
- $table->foreign('part_id')->references('id')->on('inventories')->onDelete('cascade');
-
- });
+ return [
+ 'Inventory' => 'Stevebauman\Inventory\InventoryServiceProvider',
+ ];
}
}
diff --git a/tests/InventoryAssemblyTest.php b/tests/InventoryAssemblyTest.php
deleted file mode 100644
index 95672180..00000000
--- a/tests/InventoryAssemblyTest.php
+++ /dev/null
@@ -1,581 +0,0 @@
-newInventory();
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $item->makeAssembly();
-
- $this->assertTrue($item->is_assembly);
- }
-
- public function testAddAssemblyItem()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->once()->andReturn(true);
-
- $item->addAssemblyItem($childItem, 10);
-
- $items = $item->assemblies;
-
- $this->assertEquals('Child Item', $items->first()->name);
- $this->assertEquals(10, $items->first()->pivot->quantity);
- }
-
- public function testAddAssemblyItems()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- $childItem2 = $this->newInventory([
- 'name' => 'Child Item 2',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->twice()->andReturn(true);
-
- $item->addAssemblyItems([$childItem, $childItem2], 10);
-
- $items = $item->assemblies;
-
- $this->assertEquals('Child Item', $items->get(0)->name);
- $this->assertEquals(10, $items->get(0)->pivot->quantity);
-
- $this->assertEquals('Child Item 2', $items->get(1)->name);
- $this->assertEquals(10, $items->get(1)->pivot->quantity);
- }
-
- public function testAddSameAssemblyItems()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->twice()->andReturn(true);
-
- $item->addAssemblyItems([$childItem, $childItem]);
-
- Cache::shouldReceive('has')->once()->andReturn(false);
- Cache::shouldReceive('forever')->once()->andReturn(true);
-
- $this->assertEquals(2, $item->getAssemblyItems()->count());
- }
-
- public function testAddAssemblyItemExtraAttributes()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->once()->andReturn(true);
-
- $item->addAssemblyItem($childItem, 10, ['extra' => 'testing']);
-
- /*
- * Tests that the extra array is merged
- * and updated successfully with the quantity
- */
- $this->assertEquals(10, $item->assemblies()->first()->pivot->quantity);
- }
-
- public function testAddInvalidAssemblyItem()
- {
- $item = $this->newInventory();
-
- try {
- $item->addAssemblyItem('invalid item');
-
- $passes = false;
- } catch (\Exception $e) {
- $passes = true;
- }
-
- $this->assertTrue($passes);
- }
-
- public function testAddInvalidQuantityWithAssemblyItem()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Lang::shouldReceive('get')->once()->andReturn('Invalid Quantity');
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $item->addAssemblyItem($childItem, 'invalid quantity');
- }
-
- public function testUpdateAssemblyItem()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->times(3)->andReturn(true);
-
- $item->addAssemblyItem($childItem);
-
- $item->updateAssemblyItem($childItem, 5);
-
- $this->assertEquals(5, $item->assemblies()->first()->pivot->quantity);
-
- $item->updateAssemblyItem($childItem->id, 10);
-
- $this->assertEquals(10, $item->assemblies()->first()->pivot->quantity);
- }
-
- public function testUpdateAssemblyItems()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- $childItem2 = $this->newInventory([
- 'name' => 'Child Item 2',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- Cache::shouldReceive('forget')->times(4)->andReturn(true);
-
- $item->addAssemblyItem($childItem);
- $item->addAssemblyItem($childItem2);
-
- $item->updateAssemblyItems([$childItem, $childItem2], 10);
-
- $items = $item->assemblies()->get();
-
- $this->assertEquals(10, $items->get(0)->pivot->quantity);
- $this->assertEquals(10, $items->get(1)->pivot->quantity);
- }
-
- public function testUpdateInvalidQuantityWithAssemblyItem()
- {
- $item = $this->newInventory();
-
- $childItem = $this->newInventory([
- 'name' => 'Child Item',
- 'metric_id' => $item->metric_id,
- 'category_id' => $item->category_id,
- ]);
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $item->addAssemblyItem($childItem, 'invalid quantity');
- }
-
- public function testUpdateAssemblyItemWhenItemIsNotAnAssembly()
- {
- $item = $this->newInventory();
-
- $this->assertFalse($item->updateAssemblyItem(1, 5));
- }
-
- public function testUpdateAssemblyItemsWhenItemIsNotAnAssembly()
- {
- $item = $this->newInventory();
-
- $this->assertEquals(0, $item->updateAssemblyItems([1, 2], 5));
- }
-
- public function testGetAssemblies()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $tableTop = $this->newInventory([
- 'name' => 'Table Top',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $tableLegs = $this->newInventory([
- 'name' => 'Table Legs',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- Cache::shouldReceive('forget')->twice()->andReturn(true);
-
- $table->addAssemblyItem($tableTop, 1);
- $table->addAssemblyItem($tableLegs, 4);
-
- $items = $table->assemblies;
-
- $this->assertEquals(2, $items->count());
-
- $this->assertEquals('Table Top', $items->get(0)->name);
- $this->assertEquals(1, $items->get(0)->pivot->quantity);
-
- $this->assertEquals('Table Legs', $items->get(1)->name);
- $this->assertEquals(4, $items->get(1)->pivot->quantity);
-
- $this->assertNull($items->get(2));
- }
-
- public function testGetAssembliesRecursive()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $tableTop = $this->newInventory([
- 'name' => 'Table Top',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $tableLegs = $this->newInventory([
- 'name' => 'Table Legs',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $screws = $this->newInventory([
- 'name' => 'Screws',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- Cache::shouldReceive('forget')->times(4)->andReturn(true);
-
- $table->addAssemblyItem($tableTop, 1);
- $table->addAssemblyItem($tableLegs, 4);
-
- $tableTop->addAssemblyItem($screws, 1);
- $tableLegs->addAssemblyItem($screws, 2);
-
- Cache::shouldReceive('has')->once()->andReturn(false);
- Cache::shouldReceive('forever')->once()->andReturn(true);
-
- $items = $table->getAssemblyItems();
-
- $this->assertEquals(2, $items->count());
-
- $this->assertEquals('Table Top', $items->get(0)->name);
- $this->assertEquals(1, $items->get(0)->pivot->quantity);
-
- $this->assertEquals('Table Legs', $items->get(1)->name);
- $this->assertEquals(4, $items->get(1)->pivot->quantity);
-
- // One screw item exists on each model
- $this->assertEquals(1, $items->get(0)->assemblies->count());
- $this->assertEquals(1, $items->get(1)->assemblies->count());
-
- // One screw for table top
- $this->assertEquals('Screws', $items->get(0)->assemblies->get(0)->name);
- $this->assertEquals(1, $items->get(0)->assemblies->get(0)->pivot->quantity);
-
- // Two screws for table legs
- $this->assertEquals('Screws', $items->get(1)->assemblies->get(0)->name);
- $this->assertEquals(2, $items->get(1)->assemblies->get(0)->pivot->quantity);
- }
-
- public function testGetAssemblyItemsCached()
- {
- $item = $this->newInventory();
-
- Cache::shouldReceive('has')->once()->andReturn(true);
- Cache::shouldReceive('get')->once()->andReturn('cached items');
-
- $this->assertEquals('cached items', $item->getAssemblyItems());
- }
-
- public function testRemoveAssemblyItem()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $tableTop = $this->newInventory([
- 'name' => 'Table Top',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- Cache::shouldReceive('forget')->twice()->andReturn(true);
-
- $table->addAssemblyItem($tableTop, 1);
-
- $this->assertTrue($table->removeAssemblyItem($tableTop));
-
- $this->assertNull($table->assemblies->first());
- }
-
- public function testRemoveAssemblyItemWhenItemIsNotAnAssembly()
- {
- $item = $this->newInventory();
-
- $this->assertFalse($item->removeAssemblyItem(1));
- }
-
- public function testRemoveAssemblyItemsWhenItemIsNotAnAssembly()
- {
- $item = $this->newInventory();
-
- $this->assertEquals(0, $item->removeAssemblyItems([1, 2]));
- }
-
- public function testGetAssemblyItemsList()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $tableTop = $this->newInventory([
- 'name' => 'Table Top',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $tableLegs = $this->newInventory([
- 'name' => 'Table Legs',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $screws = $this->newInventory([
- 'name' => 'Screws',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $metal = $this->newInventory([
- 'name' => 'Metal',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $ore = $this->newInventory([
- 'name' => 'Ore',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $flux = $this->newInventory([
- 'name' => 'Flux',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- Cache::shouldReceive('forget')->times(7)->andReturn(true);
-
- $table->addAssemblyItem($tableTop, 1);
- $table->addAssemblyItem($tableLegs, 4);
-
- $tableTop->addAssemblyItem($screws, 1);
- $tableLegs->addAssemblyItem($screws, 2);
-
- $screws->addAssemblyItem($metal, 5);
-
- $metal->addAssemblyItem($ore, 10);
- $metal->addAssemblyItem($flux, 5);
-
- Cache::shouldReceive('has')->once()->andReturn(false);
- Cache::shouldReceive('forever')->once()->andReturn(true);
-
- $list = $table->getAssemblyItemsList();
-
- $this->assertEquals('Table Top', $list[0]['name']);
- $this->assertEquals('Table Legs', $list[1]['name']);
-
- // Validate Table Top / Table Leg Depth
- $this->assertEquals(1, $list[0]['depth']);
- $this->assertEquals(1, $list[1]['depth']);
-
- $this->assertEquals('Screws', $list[0]['parts'][0]['name']);
- $this->assertEquals('Screws', $list[1]['parts'][0]['name']);
-
- // Validate Screw Depth
- $this->assertEquals(2, $list[0]['parts'][0]['depth']);
- $this->assertEquals(2, $list[1]['parts'][0]['depth']);
-
- $this->assertEquals('Metal', $list[0]['parts'][0]['parts'][0]['name']);
- $this->assertEquals('Metal', $list[1]['parts'][0]['parts'][0]['name']);
-
- // Validate Metal Depth
- $this->assertEquals(3, $list[0]['parts'][0]['parts'][0]['depth']);
- $this->assertEquals(3, $list[1]['parts'][0]['parts'][0]['depth']);
-
- $this->assertEquals('Ore', $list[0]['parts'][0]['parts'][0]['parts'][0]['name']);
- $this->assertEquals('Ore', $list[1]['parts'][0]['parts'][0]['parts'][0]['name']);
-
- // Validate Ore Depth
- $this->assertEquals(4, $list[0]['parts'][0]['parts'][0]['parts'][0]['depth']);
- $this->assertEquals(4, $list[1]['parts'][0]['parts'][0]['parts'][0]['depth']);
- }
-
- public function testInvalidPartException()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidPartException');
-
- $table->addAssemblyItem($table);
- }
-
- public function testNestedInvalidPartException()
- {
- $metric = $this->newMetric();
-
- $category = $this->newCategory();
-
- $table = $this->newInventory([
- 'name' => 'Table',
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- ]);
-
- $tableTop = $this->newInventory([
- 'name' => 'Table Top',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $tableLegs = $this->newInventory([
- 'name' => 'Table Legs',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $screws = $this->newInventory([
- 'name' => 'Screws',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- $metal = $this->newInventory([
- 'name' => 'Metal',
- 'metric_id' => $table->metric_id,
- 'category_id' => $table->category_id,
- ]);
-
- Cache::shouldReceive('forget')->times(5)->andReturn(true);
-
- $table->addAssemblyItem($tableTop, 1);
- $table->addAssemblyItem($tableLegs, 4);
-
- $tableTop->addAssemblyItem($screws, 1);
- $tableLegs->addAssemblyItem($screws, 2);
-
- $screws->addAssemblyItem($metal, 5);
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidPartException');
-
- /*
- * Since metal is already apart of screws,
- * adding table as an assembly item of metal
- * would cause an infinite recursive query
- */
- $metal->addAssemblyItem($table);
- }
-
- public function testHasCachedAssemblyItems()
- {
- $item = $this->newInventory();
-
- Cache::shouldReceive('has')->once()->andReturn(false);
-
- $this->assertFalse($item->hasCachedAssemblyItems());
- }
-
- public function testGetCachedAssemblyItems()
- {
- $item = $this->newInventory();
-
- Cache::shouldReceive('has')->once()->andReturn(true);
- Cache::shouldReceive('get')->once()->andReturn('cached items');
-
- $this->assertEquals('cached items', $item->getCachedAssemblyItems());
- }
-
- public function testForgetCachedAssemblyItems()
- {
- $item = $this->newInventory();
-
- Cache::shouldReceive('forget')->once()->andReturn(true);
-
- $this->assertTrue($item->forgetCachedAssemblyItems());
- }
-}
\ No newline at end of file
diff --git a/tests/InventoryCategoryTest.php b/tests/InventoryCategoryTest.php
deleted file mode 100644
index 545c2d16..00000000
--- a/tests/InventoryCategoryTest.php
+++ /dev/null
@@ -1,54 +0,0 @@
-name = 'Test Metric';
- $metric->symbol = 'Test Symbol';
- $metric->save();
-
- $productsCategory = Category::create([
- 'name' => 'Products',
- 'belongs_to' => 'Products'
- ]);
-
- $miscCategory = Category::create([
- 'name' => 'Misc',
- 'belongs_to' => 'Misc',
- ]);
-
- $noItemCategory = Category::create([
- 'name' => 'No Items',
- ]);
-
- $productItem = Inventory::create([
- 'name' => '',
- 'category_id' => $productsCategory->id,
- 'metric_id' => $metric->id,
- ]);
-
- $miscItem = Inventory::create([
- 'name' => 'Item 1',
- 'category_id' => $miscCategory->id,
- 'metric_id' => $metric->id,
- ]);
-
- $miscItem2 = Inventory::create([
- 'name' => 'Item 2',
- 'category_id' => $miscCategory->id,
- 'metric_id' => $metric->id,
- ]);
-
- $this->assertEquals(0, $noItemCategory->inventories()->count());
- $this->assertEquals(1, $productsCategory->inventories()->count());
- $this->assertEquals(2, $miscCategory->inventories()->count());
- }
-}
\ No newline at end of file
diff --git a/tests/InventorySkuTest.php b/tests/InventorySkuTest.php
deleted file mode 100644
index e01e3b34..00000000
--- a/tests/InventorySkuTest.php
+++ /dev/null
@@ -1,307 +0,0 @@
-newInventory();
-
- return $item->generateSku();
- }
-
- public function testInventorySkuGeneration()
- {
- /*
- * SKU generation is enabled
- */
- Config::shouldReceive('get')->once()->andReturn(true);
-
- /*
- * SKU code limit
- */
- Config::shouldReceive('get')->once()->andReturn(6);
-
- /*
- * SKU prefix limit
- */
- Config::shouldReceive('get')->once()->andReturn(3);
-
- /*
- * SKU separator
- */
- Config::shouldReceive('get')->once()->andReturn('');
-
- DB::shouldReceive('beginTransaction')->once()->shouldReceive('commit')->once();
-
- Event::shouldReceive('fire')->once();
-
- $sku = $this->newInventorySku();
-
- $this->assertEquals(1, $sku->inventory_id);
- $this->assertEquals('DRI000001', $sku->code);
- }
-
- public function testInventorySkuGenerationForSmallCategoryName()
- {
- $item = $this->newInventory();
-
- $category = Category::find(1);
-
- $update = [
- 'name' => 'D',
- ];
-
- $category->update($update);
-
- /*
- * SKU generation is enabled
- */
- Config::shouldReceive('get')->once()->andReturn(true);
-
- /*
- * SKU code limit
- */
- Config::shouldReceive('get')->once()->andReturn(6);
-
- /*
- * SKU prefix limit
- */
- Config::shouldReceive('get')->once()->andReturn(3);
-
- /*
- * SKU separator
- */
- Config::shouldReceive('get')->once()->andReturn('');
-
- /*
- * Generate the SKU
- */
- $item->generateSku();
-
- /*
- * Get the sku code
- */
- $sku = $item->sku()->first()->code;
-
- $this->assertEquals('D000001', $sku);
- }
-
- public function testInventorySkuRegeneration()
- {
- $this->newInventorySku();
-
- $item = Inventory::find(1);
-
- /*
- * SKU code limit
- */
- Config::shouldReceive('get')->once()->andReturn(6);
-
- /*
- * SKU prefix limit
- */
- Config::shouldReceive('get')->once()->andReturn(3);
-
- DB::shouldReceive('beginTransaction')->once()->shouldReceive('commit')->once();
-
- $item->regenerateSku();
-
- $sku = InventorySku::first();
-
- $this->assertEquals($sku->id, 2);
- }
-
- public function testInventoryHasSku()
- {
- $this->newInventorySku();
-
- $item = Inventory::find(1);
-
- $this->assertTrue($item->hasSku());
- }
-
- public function testInventoryDoesNotHaveSku()
- {
- $this->newInventorySku();
-
- $sku = InventorySku::first();
- $sku->delete();
-
- $item = Inventory::find(1);
-
- $this->assertFalse($item->hasSku());
- }
-
- public function testInventorySkuGenerationFalse()
- {
- $item = $this->newInventory();
-
- $item->category_id = null;
- $item->save();
-
- $this->assertFalse($item->generateSku());
- }
-
- public function testInventoryGetSku()
- {
- $this->testInventorySkuGeneration();
-
- $item = Inventory::find(1);
-
- $expected = 'DRI000001';
-
- $this->assertEquals($expected, $item->sku->code);
- $this->assertEquals($expected, $item->getSku());
- }
-
- public function testInventoryFindBySku()
- {
- $this->testInventorySkuGeneration();
-
- $item = Inventory::findBySku('DRI000001');
-
- $this->assertEquals('Milk', $item->name);
- }
-
- public function testInventorySkuBlankCategoryName()
- {
- $this->testInventorySkuGeneration();
-
- $category = Category::find(1);
-
- $category->update(['name' => ' ']);
-
- $item = Inventory::find(1);
-
- /*
- * SKU generation is enabled
- */
- Config::shouldReceive('get')->once()->andReturn(true);
-
- /*
- * SKU code limit
- */
- Config::shouldReceive('get')->once()->andReturn(6);
-
- /*
- * SKU prefix limit
- */
- Config::shouldReceive('get')->once()->andReturn(3);
-
- /*
- * SKU separator
- */
- Config::shouldReceive('get')->once()->andReturn('');
-
- $sku = $item->regenerateSku();
-
- /*
- * SKU generation will fail and the previous will be restored
- * with new ID
- */
- $this->assertEquals(2, $sku->id);
- $this->assertEquals('DRI000001', $sku->code);
- }
-
- public function testInventorySkuSeparator()
- {
- $this->testInventorySkuGeneration();
-
- /*
- * SKU generation is enabled
- */
- Config::shouldReceive('get')->once()->andReturn(true);
-
- /*
- * SKU code limit
- */
- Config::shouldReceive('get')->once()->andReturn(6);
-
- /*
- * SKU prefix limit
- */
- Config::shouldReceive('get')->once()->andReturn(3);
-
- /*
- * SKU separator
- */
- Config::shouldReceive('get')->once()->andReturn('-');
-
- $item = Inventory::find(1);
-
- $sku = $item->regenerateSku();
-
- $this->assertEquals(2, $sku->id);
- $this->assertEquals('DRI-000001', $sku->code);
- }
-
- public function testInventorySkuCreateSku()
- {
- $item = $this->newInventory();
-
- $sku = $item->createSku('TESTING');
-
- $this->assertEquals(1, $sku->inventory_id);
- $this->assertEquals('TESTING', $sku->code);
- }
-
- public function testInventorySkuCreateSkuOverwrite()
- {
- $item = $this->newInventory();
-
- $item->createSku('TESTING');
-
- $newSku = $item->createSku('TESTING-RESTORE', true);
-
- $this->assertEquals(1, $newSku->id);
- $this->assertEquals(1, $newSku->inventory_id);
- $this->assertEquals('TESTING-RESTORE', $newSku->code);
- }
-
- public function testsInventorySkuUpdate()
- {
- $item = $this->newInventory();
-
- $item->createSku('TESTING');
-
- $sku = $item->updateSku('TESTING-UPDATE');
-
- $this->assertEquals(1, $sku->id);
- $this->assertEquals(1, $sku->inventory_id);
- $this->assertEquals('TESTING-UPDATE', $sku->code);
- }
-
- public function testInventorySkuUpdateCreate()
- {
- $item = $this->newInventory();
-
- $sku = $item->updateSku('TESTING-UPDATE-CREATE');
-
- $this->assertEquals(1, $sku->id);
- $this->assertEquals(1, $sku->inventory_id);
- $this->assertEquals('TESTING-UPDATE-CREATE', $sku->code);
- }
-
- public function testInventorySkuCreateSkuAlreadyExistsException()
- {
- $this->newInventorySku();
-
- $item = Inventory::find(1);
-
- Lang::shouldReceive('get')->once()->andReturn('Failed');
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\SkuAlreadyExistsException');
-
- $item->createSku('test');
- }
-}
diff --git a/tests/InventoryStockTest.php b/tests/InventoryStockTest.php
deleted file mode 100644
index f83cbd09..00000000
--- a/tests/InventoryStockTest.php
+++ /dev/null
@@ -1,253 +0,0 @@
-newInventory();
-
- $location = $this->newLocation();
-
- $stock = new InventoryStock();
- $stock->inventory_id = $item->id;
- $stock->location_id = $location->id;
- $stock->quantity = 20;
- $stock->cost = '5.20';
- $stock->reason = 'I bought some';
- $stock->save();
-
- return $stock;
- }
-
- public function testInventoryStockCreation()
- {
- $stock = $this->newInventoryStock();
-
- $this->assertEquals(20, $stock->quantity);
- }
-
- public function testStockPut()
- {
- $stock = $this->newInventoryStock();
-
- DB::shouldReceive('beginTransaction')->once()->shouldReceive('commit')->once();
- Event::shouldReceive('fire')->once();
-
- $stock->put(10, 'Added some', 15);
-
- $this->assertEquals(30, $stock->quantity);
- }
-
- public function testStockTake()
- {
- $stock = $this->newInventoryStock();
-
- DB::shouldReceive('beginTransaction')->once()->shouldReceive('commit')->once();
- Event::shouldReceive('fire')->once();
-
- $stock->take(10, 'Removed some', 15);
-
- $this->assertEquals(10, $stock->quantity);
- $this->assertEquals('Removed some', $stock->reason);
- $this->assertEquals(15, $stock->cost);
- }
-
- public function testStockMove()
- {
- $stock = $this->newInventoryStock();
-
- $newLocation = Location::create([
- 'name' => 'New Location',
- ]);
-
- DB::shouldReceive('beginTransaction')->once()->shouldReceive('commit')->once();
- Event::shouldReceive('fire')->once();
-
- $stock->moveTo($newLocation);
-
- $this->assertEquals(2, $stock->location_id);
- }
-
- public function testStockIsValidQuantitySuccess()
- {
- $stock = $this->newInventoryStock();
-
- $this->assertTrue($stock->isValidQuantity(500));
- $this->assertTrue($stock->isValidQuantity(5, 000));
- $this->assertTrue($stock->isValidQuantity('500'));
- $this->assertTrue($stock->isValidQuantity('500.00'));
- $this->assertTrue($stock->isValidQuantity('500.0'));
- $this->assertTrue($stock->isValidQuantity('1.500'));
- $this->assertTrue($stock->isValidQuantity('15000000'));
- }
-
- public function testStockIsValidQuantityFailure()
- {
- $stock = $this->newInventoryStock();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $stock->isValidQuantity('40a');
- $stock->isValidQuantity('5,000');
- $stock->isValidQuantity('5.000.00');
- }
-
- public function testInvalidMovementException()
- {
- $stock = $this->newInventoryStock();
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidMovementException');
-
- $stock->getMovement('testing');
- }
-
- public function testUpdateStockQuantity()
- {
- $stock = $this->newInventoryStock();
-
- $stock->updateQuantity(10);
-
- $this->assertEquals(10, $stock->quantity);
- }
-
- public function testUpdateStockQuantityFailure()
- {
- $stock = $this->newInventoryStock();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $stock->updateQuantity(-100);
- }
-
- public function testNotEnoughStockException()
- {
- $stock = $this->newInventoryStock();
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $stock->take(1000);
- }
-
- public function testStockAlreadyExistsException()
- {
- $this->newInventoryStock();
-
- $location = Location::find(1);
-
- $item = Inventory::find(1);
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\StockAlreadyExistsException');
-
- $item->createStockOnLocation(1, $location);
- }
-
- public function testStockNotFoundException()
- {
- $item = $this->newInventory();
-
- $location = $this->newLocation();
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\StockNotFoundException');
-
- $item->getStockFromLocation($location);
- }
-
- public function testInventoryTakeFromManyLocations()
- {
- $this->newInventoryStock();
-
- $item = Inventory::find(1);
-
- $location = Location::find(1);
-
- $item->takeFromManyLocations(10, [$location]);
-
- $stock = InventoryStock::find(1);
-
- $this->assertEquals(10, $stock->quantity);
- }
-
- public function testInventoryAddToManyLocations()
- {
- $this->newInventoryStock();
-
- $item = Inventory::find(1);
-
- $location = Location::find(1);
-
- $item->addToManyLocations(10, [$location]);
-
- $stock = InventoryStock::find(1);
-
- $this->assertEquals(30, $stock->quantity);
- }
-
- public function testInventoryMoveItemStock()
- {
- $this->newInventoryStock();
-
- $locationFrom = Location::find(1);
-
- $locationTo = new Location();
- $locationTo->name = 'New Location';
- $locationTo->save();
-
- $item = Inventory::find(1);
-
- $item->moveStock($locationFrom, $locationTo);
-
- $stock = InventoryStock::find(1);
-
- $this->assertEquals(2, $stock->location_id);
- }
-
- public function testInventoryGetTotalStock()
- {
- $this->newInventoryStock();
-
- $item = Inventory::find(1);
-
- $this->assertEquals(20, $item->getTotalStock());
- }
-
- public function testInventoryInvalidLocationException()
- {
- $this->newInventoryStock();
-
- $item = Inventory::find(1);
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidLocationException');
-
- $item->getStockFromLocation('testing');
- }
-
- public function testInventoryStockNewTransaction()
- {
- $this->newInventoryStock();
-
- $stock = InventoryStock::find(1);
-
- $transaction = $stock->newTransaction();
-
- $this->assertInstanceOf('Stevebauman\Inventory\Interfaces\StateableInterface', $transaction);
- }
-}
diff --git a/tests/InventorySupplierTest.php b/tests/InventorySupplierTest.php
deleted file mode 100644
index be52538f..00000000
--- a/tests/InventorySupplierTest.php
+++ /dev/null
@@ -1,96 +0,0 @@
- 'Supplier',
- 'address' => '123 Fake St',
- 'postal_code' => '12345',
- 'zip_code' => '12345',
- 'region' => 'ON',
- 'city' => 'Toronto',
- 'country' => 'Canada',
- 'contact_title' => 'Manager',
- 'contact_name' => 'John Doe',
- 'contact_phone' => '555 555 5555',
- 'contact_fax' => '555 555 5555',
- 'contact_email' => 'john.doe@email.com',
- ]);
- }
-
- public function testInventorySupplierAttach()
- {
- $item = $this->newInventory();
-
- $newSupplier = $this->newSupplier();
-
- $item->addSupplier($newSupplier);
-
- $supplier = $item->suppliers()->first();
-
- $this->assertEquals('Supplier', $supplier->name);
- }
-
- public function testInventorySupplierDetach()
- {
- $this->testInventorySupplierAttach();
-
- $item = Inventory::find(1);
-
- $this->assertTrue($item->removeSupplier(1));
- }
-
- public function testInventorySupplierDetachAll()
- {
- $this->testInventorySupplierAttach();
-
- $this->testInventorySupplierAttach();
-
- $item = Inventory::find(1);
-
- $item->removeAllSuppliers();
-
- $this->assertEquals(0, $item->suppliers()->count());
- }
-
- public function testSupplierAttachItem()
- {
- $item = $this->newInventory();
-
- $supplier = $this->newSupplier();
-
- $item->addSupplier($supplier);
-
- $this->assertEquals($supplier->name, $item->suppliers()->first()->name);
- }
-
- public function testSupplierDetachItem()
- {
- $this->testSupplierAttachItem();
-
- $item = Inventory::find(1);
-
- $item->removeSupplier(1);
-
- $this->assertEquals(0, $item->suppliers()->count());
- }
-
- public function testSupplierInvalidSupplierException()
- {
- $this->testSupplierAttachItem();
-
- $item = Inventory::find(1);
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidSupplierException');
-
- $item->addSupplier('testing');
- $item->removeSupplier('testing');
- }
-}
diff --git a/tests/InventoryTest.php b/tests/InventoryTest.php
deleted file mode 100644
index 29490d3f..00000000
--- a/tests/InventoryTest.php
+++ /dev/null
@@ -1,165 +0,0 @@
-newMetric();
-
- $category = $this->newCategory();
-
- if(count($attributes) > 0) {
- return Inventory::create($attributes);
- }
-
- return Inventory::create([
- 'metric_id' => $metric->id,
- 'category_id' => $category->id,
- 'name' => 'Milk',
- 'description' => 'Delicious Milk',
- ]);
- }
-
- /**
- * @return Metric
- */
- protected function newMetric()
- {
- return Metric::create([
- 'name' => 'Litres',
- 'symbol' => 'L',
- ]);
- }
-
- /**
- * @return Location
- */
- protected function newLocation()
- {
- return Location::create([
- 'name' => 'Warehouse',
- 'belongs_to' => '',
- ]);
- }
-
- /**
- * @return Category
- */
- protected function newCategory()
- {
- return Category::create([
- 'name' => 'Drinks',
- ]);
- }
-
- public function testInventoryHasMetric()
- {
- $item = $this->newInventory();
-
- $this->assertTrue($item->hasMetric());
- }
-
- public function testInventoryDoesNotHaveMetric()
- {
- $item = $this->newInventory();
-
- $metric = Metric::find(1);
- $metric->delete();
-
- $this->assertFalse($item->hasMetric());
- }
-
- public function testInventoryCreateStockOnLocation()
- {
- $item = $this->newInventory();
-
- $location = $this->newLocation();
-
- Lang::shouldReceive('get')->once();
-
- $item->createStockOnLocation(10, $location);
-
- $stock = InventoryStock::find(1);
-
- $this->assertEquals(10, $stock->quantity);
- }
-
- public function testInventoryNewStockOnLocation()
- {
- $item = $this->newInventory();
-
- $location = $this->newLocation();
-
- $stock = $item->newStockOnLocation($location);
-
- $this->assertEquals(1, $stock->inventory_id);
- $this->assertEquals(1, $stock->location_id);
- }
-
- public function testInventoryNewStockOnLocationFailure()
- {
- $item = $this->newInventory();
-
- $location = $this->newLocation();
-
- $stock = $item->newStockOnLocation($location);
- $stock->save();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\StockAlreadyExistsException');
-
- $item->newStockOnLocation($location);
- }
-
- public function testInventoryInvalidQuantityException()
- {
- $item = $this->newInventory();
-
- $location = $this->newLocation();
-
- Lang::shouldReceive('get')->once();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $item->createStockOnLocation('invalid quantity', $location);
- }
-
- public function testInventoryHasCategory()
- {
- $item = $this->newInventory();
-
- $this->assertTrue($item->hasCategory());
- }
-
- public function testInventoryDoesNotHaveCategory()
- {
- $this->newInventory();
-
- $item = Inventory::find(1);
- $item->category_id = null;
- $item->save();
-
- $this->assertFalse($item->hasCategory());
- }
-}
diff --git a/tests/InventoryVariantTest.php b/tests/InventoryVariantTest.php
deleted file mode 100644
index 9a93ac17..00000000
--- a/tests/InventoryVariantTest.php
+++ /dev/null
@@ -1,242 +0,0 @@
-newInventory();
-
- $milk = Inventory::find(1);
-
- $chocolateMilk = $milk->newVariant();
-
- $chocolateMilk->name = 'Chocolate Milk';
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $chocolateMilk->save();
-
- $this->assertEquals($chocolateMilk->parent_id, $milk->id);
- $this->assertEquals($chocolateMilk->category_id, $milk->category_id);
- $this->assertEquals($chocolateMilk->metric_id, $milk->metric_id);
- }
-
- public function testCreateVariant()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $name = 'Cherry Coke';
- $description = 'Delicious Cherry Coke';
-
- $cherryCoke = $coke->createVariant($name, $description);
-
- $this->assertTrue($cherryCoke->isVariant());
- $this->assertEquals(1, $cherryCoke->parent_id);
- $this->assertEquals($name, $cherryCoke->name);
- $this->assertEquals($description, $cherryCoke->description);
- $this->assertEquals(1, $cherryCoke->category_id);
- $this->assertEquals(1, $cherryCoke->metric_id);
- }
-
- public function testMakeVariant()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = Inventory::create([
- 'name' => 'Cherry Coke',
- 'description' => 'Delicious Cherry Coke',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $cherryCoke->makeVariantOf($coke);
-
- $this->assertEquals($cherryCoke->parent_id, $coke->id);
- }
-
- public function testIsVariant()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = $coke->createVariant('Cherry Coke');
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $cherryCoke->makeVariantOf($coke);
-
- $this->assertFalse($coke->isVariant());
- $this->assertTrue($cherryCoke->isVariant());
- }
-
- public function testGetVariants()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = $coke->createVariant('Cherry Coke');
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $cherryCoke->makeVariantOf($coke);
-
- $variants = $coke->getVariants();
-
- $this->assertInstanceOf('Illuminate\Support\Collection', $variants);
- $this->assertEquals(1, $variants->count());
- }
-
- public function testGetVariantsRecursive()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = $coke->createVariant('Cherry Coke');
-
- $vanillaCherryCoke = $cherryCoke->createVariant('Vanilla Cherry Coke');
-
- $vanillaLimeCherryCoke = $vanillaCherryCoke->createVariant('Vanilla Lime Cherry Coke');
-
- $variants = $coke->getVariants(true);
-
- $this->assertEquals($cherryCoke->name, $variants->get(0)->name);
- $this->assertEquals($vanillaCherryCoke->name, $variants->get(0)->variants->get(0)->name);
- $this->assertEquals($vanillaLimeCherryCoke->name, $variants->get(0)->variants->get(0)->variants->get(0)->name);
- }
-
- public function testGetParent()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = Inventory::create([
- 'name' => 'Cherry Coke',
- 'description' => 'Delicious Cherry Coke',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $cherryCoke->makeVariantOf($coke);
-
- $parent = $cherryCoke->getParent();
-
- $this->assertEquals('Coke', $parent->name);
- $this->assertEquals(null, $parent->parent_id);
- }
-
- public function testGetTotalVariantStock()
- {
- $this->newCategory();
- $this->newMetric();
-
- $coke = Inventory::create([
- 'name' => 'Coke',
- 'description' => 'Delicious Pop',
- 'metric_id' => 1,
- 'category_id' => 1,
- ]);
-
- $cherryCoke = $coke->createVariant('Cherry Coke');
-
- $cherryCoke->makeVariantOf($coke);
-
- $vanillaCherryCoke = $cherryCoke->createVariant('Vanilla Cherry Coke');
-
- $vanillaCherryCoke->makeVariantOf($cherryCoke);
-
- DB::shouldReceive('beginTransaction')->once()->andReturn(true);
- DB::shouldReceive('commit')->once()->andReturn(true);
-
- Event::shouldReceive('fire')->once()->andReturn(true);
-
- $location = $this->newLocation();
-
- // Allow duplicate movements configuration option
- Config::shouldReceive('get')->twice()->andReturn(true);
-
- // Stock change reasons (one for create, one for put, for both items)
- Lang::shouldReceive('get')->times(4)->andReturn('Default Reason');
-
- $cherryCoke->createStockOnLocation(20, $location);
-
- $vanillaCherryCoke->createStockOnLocation(20, $location);
-
- $this->assertEquals(40, $coke->getTotalVariantStock());
- }
-}
diff --git a/tests/Transactions/InventoryTransactionBackOrderTest.php b/tests/Transactions/InventoryTransactionBackOrderTest.php
deleted file mode 100644
index 8dd7bf25..00000000
--- a/tests/Transactions/InventoryTransactionBackOrderTest.php
+++ /dev/null
@@ -1,68 +0,0 @@
-newTransaction();
-
- $transaction->backOrder(500);
-
- $this->assertEquals(500, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_BACK_ORDERED, $transaction->state);
- }
-
- public function testInventoryTransactionBackOrderFilled()
- {
- $transaction = $this->newTransaction();
-
- $transaction->backOrder(25);
-
- $stock = $transaction->getStockRecord();
-
- $stock->put(5);
-
- $transaction->fillBackOrder();
-
- $this->assertEquals(25, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_BACK_ORDER_FILLED, $transaction->state);
- }
-
- public function testInventoryTransactionBackOrderInvalidQuantityException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->backOrder('40s');
- }
-
- public function testInventoryTransactionBackOrderInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->checkout(5)->backOrder(3);
- }
-
- public function testInventoryTransactionBackOrderFilledDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- $transaction->backOrder(5);
-
- $stock = $transaction->getStockRecord();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->fillBackOrder();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionCancelledTest.php b/tests/Transactions/InventoryTransactionCancelledTest.php
deleted file mode 100644
index 654d77bf..00000000
--- a/tests/Transactions/InventoryTransactionCancelledTest.php
+++ /dev/null
@@ -1,101 +0,0 @@
-newTransaction();
-
- $transaction->reserved(5)->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
- }
-
- public function testInventoryTransactionCancelAfterOnHold()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals(20, $stock->quantity);
- }
-
- public function testInventoryTransactionCancelAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals(20, $stock->quantity);
- }
-
- public function testInventoryTransactionCancelAfterBackOrder()
- {
- $transaction = $this->newTransaction();
-
- $transaction->backOrder(500)->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
- }
-
- public function testInventoryTransactionCancelAfterOrdered()
- {
- $transaction = $this->newTransaction();
-
- $transaction->ordered(500)->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
- }
-
- public function testInventoryTransactionCancelAfterOpened()
- {
- $transaction = $this->newTransaction();
-
- $transaction->cancel();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_CANCELLED, $transaction->state);
- }
-
- public function testInventoryTransactionCancelAfterCancelFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->cancel()->cancel();
- }
-
- public function testInventoryTransactionCancelledDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5);
-
- $stock = $transaction->getStockRecord();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->cancel();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionCheckoutTest.php b/tests/Transactions/InventoryTransactionCheckoutTest.php
deleted file mode 100644
index ab546aba..00000000
--- a/tests/Transactions/InventoryTransactionCheckoutTest.php
+++ /dev/null
@@ -1,225 +0,0 @@
-newTransaction();
-
- DB::shouldReceive('startTransaction')->once();
-
- DB::shouldReceive('commit')->once();
-
- $transaction->checkout(5, 'Checking out', 25);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Checking out', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionIsCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5);
-
- $this->assertTrue($transaction->isCheckout());
- }
-
- public function testInventoryTransactionIsNotCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->reserved(5);
-
- $this->assertFalse($transaction->isCheckout());
- }
-
- public function testInventoryTransactionCheckoutFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $transaction->checkout(5000);
- }
-
- public function testInventoryTransactionCheckoutQuantityFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->checkout('30as');
- }
-
- public function testInventoryTransactionReservationAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved();
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RESERVED, $transaction->state);
- }
-
- /**
- * The transaction quantity stays at 5 because a partial reserve cannot be made on a checkout.
- */
- public function testInventoryTransactionReservationAfterCheckoutQuantity()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved(500);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RESERVED, $transaction->state);
- }
-
- /**
- * This fails because the transaction is already set to checkout, a quantity update could simply be made
- * instead of calling checkout again.
- */
- public function testInventoryTransactionCheckoutAfterCheckoutFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->checkout(5)->checkout(500);
- }
-
- /*
- * This works because you can always update the quantity on any transaction
- * if needed
- */
- public function testInventoryTransactionQuantityUpdateAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5);
-
- $transaction->quantity = 10;
- $transaction->save();
-
- $this->assertEquals(10, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returned();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedPartialAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returned(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->sold();
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAmountAfterCheckoutFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->checkout(5)->sold(500);
- }
-
- public function testInventoryTransactionSoldAfterReservationAndCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved()->sold();
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionCheckoutSoldAndReturned()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved()->sold()->returned();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionCheckoutSoldAndReturnedPartial()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved()->sold()->returned(3);
-
- $this->assertEquals(2, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- /**
- * This fails because when a stock is returned a new transaction must be created
- * for any functions. It's an 'end of the line' state.
- */
- public function testInventoryTransactionCheckoutSoldReturnedAndReservedFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->checkout(5)->reserved()->sold()->returned()->reserved(5);
-
- $transaction->checkout(5)->reserved()->sold()->returned()->reserved();
- }
-
- public function testInventoryTransactionCheckoutReserved()
- {
- $transaction = $this->newTransaction();
-
- $transaction->reserved(5)->checkout();
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
- }
-
- public function testInventoryTransactionCheckoutDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->checkout(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionHoldTest.php b/tests/Transactions/InventoryTransactionHoldTest.php
deleted file mode 100644
index 4a52c8eb..00000000
--- a/tests/Transactions/InventoryTransactionHoldTest.php
+++ /dev/null
@@ -1,64 +0,0 @@
-newTransaction();
-
- $transaction->hold(10, 'Holding', 25);
-
- $this->assertEquals(10, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_ON_HOLD, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Holding', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionHoldInvalidQuantityException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->hold('40a');
- }
-
- public function testInventoryTransactionHoldInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->ordered(5)->hold(5);
- }
-
- public function testInventoryTransactionHoldNotEnoughStockException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $transaction->hold(500);
- }
-
- public function testInventoryTransactionHoldDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->hold(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionOrderedTest.php b/tests/Transactions/InventoryTransactionOrderedTest.php
deleted file mode 100644
index de88b08e..00000000
--- a/tests/Transactions/InventoryTransactionOrderedTest.php
+++ /dev/null
@@ -1,85 +0,0 @@
-newTransaction();
-
- $transaction->ordered(5);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_ORDERED_PENDING, $transaction->state);
- }
-
- public function testInventoryTransactionOrderedReceived()
- {
- $transaction = $this->newTransaction();
-
- $transaction->ordered(5)->received(5, 'Received Order', 25);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_ORDERED_RECEIVED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Received Order', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionOrderedReceivedPartial()
- {
- $transaction = $this->newTransaction();
-
- $transaction->ordered(5)->received(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_ORDERED_PENDING, $transaction->state);
- }
-
- public function testInventoryTransactionOrderedReceivedPartialAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->ordered(5)->received(10);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_ORDERED_RECEIVED, $transaction->state);
- }
-
- public function testInventoryTransactionOrderedInvalidQuantityException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->ordered('40a');
- }
-
- public function testInventoryTransactionOrderedInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->reserved(5)->ordered(10);
- }
-
- public function testInventoryTransactionReceivedDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->ordered(5)->received(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionReleaseTest.php b/tests/Transactions/InventoryTransactionReleaseTest.php
deleted file mode 100644
index 823943b0..00000000
--- a/tests/Transactions/InventoryTransactionReleaseTest.php
+++ /dev/null
@@ -1,85 +0,0 @@
-newTransaction();
-
- $transaction->hold(5)->release(null, 'Released', 25);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_RELEASED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Released', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionReleasePartial()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->release(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_ON_HOLD, $transaction->state);
- }
-
- public function testInventoryTransactionReleaseAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->releaseAll();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_RELEASED, $transaction->state);
- }
-
- public function testInventoryTransactionReleasePartialAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->release(10);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_RELEASED, $transaction->state);
- }
-
- public function testInventoryTransactionReleaseInvalidQuantity()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->release('asddsa');
-
- $this->assertEquals(5, $transaction->quantity);
- }
-
- public function testInventoryTransactionReleaseInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->ordered(5)->release();
- }
-
- public function testInventoryTransactionReleaseDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->twice()->andReturn('test');
-
- $transaction->hold(5)->release(3);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionRemoveTest.php b/tests/Transactions/InventoryTransactionRemoveTest.php
deleted file mode 100644
index d30a84a5..00000000
--- a/tests/Transactions/InventoryTransactionRemoveTest.php
+++ /dev/null
@@ -1,94 +0,0 @@
-newTransaction();
-
- $transaction->remove(5, 'Removed from inventory', 25);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_REMOVED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Removed from inventory', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionRemovePartial()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->remove(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_ON_HOLD, $transaction->state);
- }
-
- public function testInventoryTransactionRemovePartialFailureRollback()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->remove('testing');
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_ON_HOLD, $transaction->state);
- }
-
- public function testInventoryTransactionRemovePartialAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->hold(5)->remove(10);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_INVENTORY_REMOVED, $transaction->state);
- }
-
- public function testInventoryTransactionRemoveInvalidQuantityException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->remove('10a');
- }
-
- public function testInventoryTransactionRemoveBlankInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->remove();
- }
-
- public function testInventoryTransactionRemoveInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->ordered(5)->remove();
- }
-
- public function testInventoryTransactionRemoveDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->remove(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionReservedTest.php b/tests/Transactions/InventoryTransactionReservedTest.php
deleted file mode 100644
index d424c27c..00000000
--- a/tests/Transactions/InventoryTransactionReservedTest.php
+++ /dev/null
@@ -1,75 +0,0 @@
-newTransaction();
-
- $transaction->reserved(10, $backOrder = false, 'Reservation', 25);
-
- $this->assertEquals(10, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RESERVED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals(10, $stock->quantity);
- $this->assertEquals('Reservation', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionReservedNotEnoughStockException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $transaction->reserved(100);
- }
-
- public function testInventoryTransactionReservedInvalidQuantityException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->reserved('40a');
- }
-
- public function testInventoryTransactionReservedInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->hold(5)->reserved(20);
- }
-
- public function testInventoryTransactionReservedCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->reserved();
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RESERVED, $transaction->state);
- }
-
- public function testInventoryTransactionReservedDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->reserved(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionReturnedTest.php b/tests/Transactions/InventoryTransactionReturnedTest.php
deleted file mode 100644
index 9ba955e8..00000000
--- a/tests/Transactions/InventoryTransactionReturnedTest.php
+++ /dev/null
@@ -1,116 +0,0 @@
-newTransaction();
-
- $transaction->sold(5)->returned(5, 'Returned', 25);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('Returned', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionReturnedAllAfterSold()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returnedAll();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedPartialAfterSold()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returned(3);
-
- $this->assertEquals(2, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returned();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedAllAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returnedAll();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedPartialAfterCheckoutRollback()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returned('testing');
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedPartialAfterCheckout()
- {
- $transaction = $this->newTransaction();
-
- $transaction->checkout(5)->returned(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_CHECKOUT, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedPartialAfterSoldRollBack()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returned('testing');
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionReturnedInvalidTransactionStateException()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->returned(5);
- }
-
- public function testInventoryTransactionReturnedDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->twice()->andReturn('test');
-
- $transaction->sold(5)->returned(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionSoldTest.php b/tests/Transactions/InventoryTransactionSoldTest.php
deleted file mode 100644
index 456e02e1..00000000
--- a/tests/Transactions/InventoryTransactionSoldTest.php
+++ /dev/null
@@ -1,124 +0,0 @@
-newTransaction();
-
- $transaction->sold(5, 'Sold some', 25);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals(15, $stock->quantity);
- $this->assertEquals('Sold some', $stock->reason);
- $this->assertEquals(25, $stock->cost);
- }
-
- public function testInventoryTransactionSoldNotEnoughStockFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $transaction->sold(5000);
- }
-
- public function testInventoryTransactionSoldInvalidQuantityFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->sold('50a');
- }
-
- public function testInventoryTransactionSoldAndThenReturned()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returned();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAndThenReturnedAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returnedAll();
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAndThenReturnedPartial()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returned(2);
-
- $this->assertEquals(3, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAndThenReturnedPartialAll()
- {
- $transaction = $this->newTransaction();
-
- $transaction->sold(5)->returned(5);
-
- $this->assertEquals(0, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_RETURNED, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAmount()
- {
- $transaction = $this->newTransaction();
-
- $transaction->soldAmount(5);
-
- $this->assertEquals(5, $transaction->quantity);
- $this->assertEquals(InventoryTransaction::STATE_COMMERCE_SOLD, $transaction->state);
- }
-
- public function testInventoryTransactionSoldAmountInvalidQuantityFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidQuantityException');
-
- $transaction->soldAmount('40a');
- }
-
- public function testInventoryTransactionSoldAmountNotEnoughStockFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\NotEnoughStockException');
-
- $transaction->soldAmount(5000);
- }
-
- public function testInventoryTransactionSoldDefaultReason()
- {
- $transaction = $this->newTransaction();
-
- Lang::shouldReceive('get')->once()->andReturn('test');
-
- $transaction->sold(5);
-
- $stock = $transaction->getStockRecord();
-
- $this->assertEquals('test', $stock->reason);
- }
-}
diff --git a/tests/Transactions/InventoryTransactionTest.php b/tests/Transactions/InventoryTransactionTest.php
deleted file mode 100644
index 8029ac75..00000000
--- a/tests/Transactions/InventoryTransactionTest.php
+++ /dev/null
@@ -1,71 +0,0 @@
-newInventoryStock();
-
- return $stock->newTransaction();
- }
-
- public function testInventoryTransactionStockNotFoundException()
- {
- $transaction = $this->newTransaction();
-
- $transaction->stock_id = 15;
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\StockNotFoundException');
-
- $transaction->getStockRecord();
- }
-
- public function testInventoryTransactionSetStateFailure()
- {
- $transaction = $this->newTransaction();
-
- $this->setExpectedException('Stevebauman\Inventory\Exceptions\InvalidTransactionStateException');
-
- $transaction->state = 'test';
- }
-
- public function testInventoryTransactionSetStateSuccess()
- {
- $transaction = $this->newTransaction();
-
- $transaction->state = InventoryTransaction::STATE_COMMERCE_RESERVED;
- }
-
- public function testInventoryTransactionGetByState()
- {
- $transaction = $this->newTransaction();
-
- $transaction->reserved(2);
-
- $results = InventoryTransaction::getByState(InventoryTransaction::STATE_COMMERCE_RESERVED);
-
- $this->assertEquals(1, $results->count());
- }
-}