/var/www/hkosl.com/littleark/webadmin/models/Inventory_20160805.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php

use Illuminate\Database\Capsule\Manager as DB;
use 
Carbon\Carbon as Carbon;

class 
Inventory extends BaseModel{
    protected 
$table "inventory";

    public function 
invetoryTxns(){
        return 
$this->hasMany('InventoryTxn');
    }

    public function 
proProductSku(){
        return 
$this->belongsTo('ProProductSku''productsku_id');
    }

    public function 
warehouse(){
        return 
$this->belongsTo('Warehouse''warehouse_id');
    }





    
//----------------------------static functions--------------------------------------

    
public static function stockin($productsku_id$qty$warehouse_id$settings=array()){
        global 
$dbh;
        
// insert into (optional)

        // insert into inventory
        
$inventory Inventory::create(array(
            
'company_id' => 1,
            
'productsku_id' => $productsku_id,
            
'warehouse_id' => $warehouse_id,
            
'stocktransfer_id' => $settings['to_stocktransfer_id'],
            
'org_qty' => $qty,
            
'qty' => $qty,
            
'docdate' => date('Y-m-d'),
            
'unit_cost' => $settings['unit_cost'] ?: 0,
        ));
        
$inventory_id $inventory->id;

        
// insert into inventory_txn
        
$inventory_txn InventoryTxn::create(array(
            
'company_id' => 1,
            
'productsku_id' => $productsku_id,
            
'inventory_id' => $inventory_id,
            
'docdate' => date('Y-m-d'),
            
'doc_type' => $settings['doc_type'] ?: 'StockAdjustment',
            
'doc_id' => $settings['doc_id'] ?: false,
            
'from_warehouse_id' => false,
            
'to_warehouse_id' => $warehouse_id,
            
'qty' => $qty,
        ));

        
// update productsku.qty
        
self::update_productsku_qty($productsku_id);
        return 
true;
    }

    public static function 
stockout_reserved($productsku_id$qty$settings=array()){
        return 
self::stockout($productsku_id$qty, array('deduct_reserved_qty'=>true)+$settings);
    }

    public static function 
stockout($productsku_id$qty$settings=array()){
        
$productsku ProProductSku::find($productsku_id);
        if(
$qty>$productsku['qty']){
            throw new 
Exception("Insufficient stock"1);
        }

        
$qty_remaining $qty;

        
$inventoryTxns = array();
        while(
$qty_remaining>0){
            
$inventory self::stockout_inventory($productsku_id$settings);
            if(!
$inventory){
                
vdump($settings);
                
dq(11);
                
// roll back
                
throw new Exception("Insufficient stock"1);
            }

            
$qty_to_deduct min($inventory['qty'], $qty_remaining);
            
$qty_remaining -= $qty_to_deduct;
            
// var_dump("Stock out {$qty_to_deduct} from inventory {$inventory['id']}");

            // insert into inventory_txn
            
$inventoryTxns[] = InventoryTxn::create(array(
                
'company_id' => 1,
                
'order_item_id' => $settings['order_item_id'],
                
'productsku_id' => $productsku_id,
                
'inventory_id' => $inventory['id'],
                
'docdate' => date('Y-m-d'),
                
'doc_type' => $settings['doc_type'] ?: 'StockAdjustment',
                
'doc_id' => $settings['doc_id'],
                
'from_warehouse_id' => $inventory['warehouse_id'],
                
'to_warehouse_id' => $settings['doc_type'] ?: false,
                
'qty' => $qty_to_deduct,
            ));

            
// update inventory.qty
            
self::update_inventory_qty($inventory['id'], $inventory['warehouse_id']);
            
// decrease pro_product_sku.reserved_qty
            
if($qty && $settings['deduct_reserved_qty']!==false){
                
// reserve qty in negative qty
                
self::reserve($productsku_id$qtyfalse);
            }
        }

        
// update productsku.qty
        
self::update_productsku_qty($productsku_id);
        return 
$inventoryTxns;
    }

    
// $settings = [
    //     'createby' => 'user1',
    //     'stockout_doc' => [
    //         'doc_type' => 'DeliveryNote',
    //         'doc_id' => '1000001',
    //     ],
    //     'stockin_doc' => [
    //         'doc_type' => 'TransferNote',
    //         'doc_id' => '50000000',
    //     ]
    // ]
    
public static function stockTransfer($productsku_id$qty$from_warehouse_id$to_warehouse_id$settings=array()){
        
// TODO: select specific inventory_id to stockout, preventing using wrong transport inventory
        
$transfer_settings =  $settings + array(
            
'doc_type' => $settings['stockout_doc']['doc_type'],
            
'doc_id' => $settings['stockout_doc']['doc_id'],
            
'from_warehouse_id' => $from_warehouse_id,
            
'to_warehouse_id' => $to_warehouse_id,
        );
        
$inventoryTxns self::stockout($productsku_id$qty$transfer_settings);
        
$total_cost 0;
        
$total_qty 0;
        foreach(
$inventoryTxns as $inventoryTxn){
            
$total_cost += $inventoryTxn->inventory->unit_cost $inventoryTxn->qty;
            
$total_qty += $inventoryTxn->qty;
            
// var_dump("Stockout for Txn:{$inventoryTxn->id} qty:{$inventoryTxn->qty} cost:{$inventoryTxn->inventory->unit_cost}");
        
}

        
// average cost of all transactions
        
self::stockin($productsku_id$total_qty$to_warehouse_id, array(
            
'to_stocktransfer_id' => $settings['to_stocktransfer_id'],
            
'doc_type' => $settings['stockin_doc']['doc_type'] ?: 'Stocktransfer',
            
'doc_id' => $settings['stockin_doc']['doc_id'] ?: 0,
            
'unit_cost' => $total_cost $total_qty,
        ));

        return 
count($inventoryTxns)>0;
    }

    
// reverse txn with AVERAGE unit cost
    
public static function stockReturn($inventory_txn_id$qty$settings=array()){
        
// txn lookup
        
$old_txn InventoryTxn::find($inventory_txn_id);
        
// var_dump($old_txn);

        
if($old_txn){
            if(!
$old_txn['from_warehouse_id'] && !$settings['to_warehouse_id']){
                
// default stock return warehouse
                
$settings['to_warehouse_id'] = Warehouse::stockin_warehouse($old_txn->proProductSku->supplier_id)->id;
            }

            if(
$settings['to_warehouse_id']){
                
// stockin to specific warehouse with orginal cost
                
self::stockin($productsku_id$qty$warehouse_id, array(
                    
'doc_type' => $settings['doc_type'],
                    
'doc_id' => $settings['doc_id'],
                    
'unit_cost' => $settings['unit_cost'] ?: $old_txn->inventory->unit_cost,
                ));
            }else{
                
// insert to txn
                
$inventroyTxn InventoryTxn::create(array(
                    
'company_id' => 1,
                    
'productsku_id' => $old_txn['productsku_id'],
                    
'inventory_id' => $old_txn['inventory_id'],
                    
'docdate' => date('Y-m-d'),
                    
'doc_type' => 'StockAdjustment',
                    
'doc_id' => 0,
                    
'from_warehouse_id' => $old_txn['to_warehouse_id'],
                    
'to_warehouse_id' => $old_txn['from_warehouse_id'],
                    
'qty' => $qty,
                ));

                
// update inventory.qty for both in and out
                
if($old_txn['from_warehouse_id']){
                    
self::update_inventory_qty($old_txn['inventory_id'], $old_txn['from_warehouse_id']);
                }
                if(
$old_txn['to_warehouse_id']){
                    
self::update_inventory_qty($old_txn['inventory_id'], $old_txn['to_warehouse_id']);
                }

                
// update productsku.qty
                
self::update_productsku_qty($old_txn->inventory->productsku_id);
            }
        }else{
            
// TODO: refactor flow control
            // transaction/source warehouse not found

            // somehow we managed to stockin unknown source product to the inventory with provided warehouse_id and unitcost
            // self::stockin()
        
}

    }

    public static function 
reserve($productsku_id$qty$is_reserve=true){
        
$proProductSku ProProductSku::find($productsku_id);
        if(!
$is_reserve){
            
$proProductSku->reserved_qty max($proProductSku->reserved_qty $qty0);
        }else{
            
$proProductSku->reserved_qty max($proProductSku->reserved_qty $qty0);
        }
        
$proProductSku->save();
    }

    protected static function 
stockout_inventory($productsku_id$settings = array()){
        if(isset(
$settings['from_warehouse_id'])){
            if(
$settings['from_stocktransfer_id']){
                
// specified stock (for stock transfer)
                
$inventory Inventory::whereDeleted(0)
                                ->
where('qty''>'0)
                                ->
where('productsku_id'$productsku_id)
                                ->
where('warehouse_id'$settings['from_warehouse_id'])
                                ->
where('stocktransfer_id'$settings['from_stocktransfer_id'])
                                ->
orderBy('id''asc')
                                ->
first();
                return 
$inventory;
            }else{
                
// specified stockout from warehouse
                
$inventory Inventory::whereDeleted(0)
                                ->
where('qty''>'0)
                                ->
where('productsku_id'$productsku_id)
                                ->
where('warehouse_id'$settings['from_warehouse_id'])
                                ->
where('stocktransfer_id'null)
                                ->
orderBy('id''asc')
                                ->
first();
                return 
$inventory;
            }
        }else{
            
// best strategy
            // if warehouse_productsku.priority exists:

            // stockout based on warehouse priority
            
$query Inventory::select('inventory.*')
                            ->
join('warehouse''warehouse.id''=''inventory.warehouse_id')
                            ->
leftjoin('warehouse_productsku', function($join) use ($productsku_id){
                                
$join->on('warehouse_productsku.warehouse_id''=''warehouse.id');
                                
$join->on('warehouse_productsku.sku_id''='$productsku_id);
                            })
                            ->
where('inventory.deleted'0)
                            ->
where('warehouse.deleted'0)
                            ->
where('inventory.qty''>'0)
                            ->
where('productsku_id'$productsku_id)
                            ->
where('is_eshop_warehouse'1)
                            ->
orderBy('warehouse_product_sku.priority''asc')
                            ->
orderBy('warehouse.priority''asc')
                            ->
orderBy('inventory.id''asc');

            
$inventory $query->first();
dq(1,1);
            return 
$inventory;
        }
    }

    protected static function 
update_productsku_qty($productsku_id){
        
$sum Inventory::whereDeleted(0)
                ->
where('productsku_id'$productsku_id)
                ->
where('qty''>'0)
                ->
sum('qty');

        
$proProductSku ProProductSku::find($productsku_id);
        
$proProductSku->qty $sum;
        
$proProductSku->save();
    }

    protected static function 
update_inventory_qty($inventory_id$warehouse_id){
        
$sum_to_inventory InventoryTxn::whereDeleted(0)
                                ->
where('inventory_id'$inventory_id)
                                ->
where('qty''>'0)
                                ->
where('to_warehouse_id'$warehouse_id)
                                ->
sum('qty');
        
$sum_from_inventory InventoryTxn::whereDeleted(0)
                                ->
where('inventory_id'$inventory_id)
                                ->
where('qty''>'0)
                                ->
where('from_warehouse_id'$warehouse_id)
                                ->
sum('qty');

        
$inventory Inventory::find($inventory_id);
        
$inventory->qty $sum_to_inventory $sum_from_inventory;
        
$inventory->save();
    }

    
// test cases =======================================================================================
    
public static function test_reserve(){
        global 
$dbh;
        
var_dump(__FUNCTION__'==START==');
        
$dbh->beginTransaction();

        
Inventory::reserve(42);

        
$dbh->commit();
        
var_dump('==ENDED==');
    }
    public static function 
test_stockin(){
        global 
$dbh;
        
var_dump(__FUNCTION__'==START==');
        
$dbh->beginTransaction();

        
Inventory::stockin(457);

        
$dbh->commit();
        
var_dump('==ENDED==');
    }
    public static function 
test_stockout(){
        global 
$dbh;
        
var_dump(__FUNCTION__'==START==');
        
$dbh->beginTransaction();

        
$txns Inventory::stockout(43);

        
$dbh->commit();
        
var_dump($txns);
        
var_dump('==ENDED==');
    }
    public static function 
test_stockout_reserved(){
        global 
$dbh;
        
var_dump(__FUNCTION__'==START==');
        
$dbh->beginTransaction();

        
Inventory::stockout_reserved(41, array('deduct_reserved_qty'=>1));

        
$dbh->commit();
        
var_dump('==ENDED==');
    }
    public static function 
test_selectInventory(){
        
var_dump(__FUNCTION__'==START==');
        
var_dumpInventory::stockout_inventory(1) );
        
// var_dump( Inventory::stockout_inventory(1, ['from_warehouse_id'=>2]) );
    
}
    public static function 
test_stockTransfer(){
        
Inventory::stockTransfer(43715, array(
            
'stockout_doc' => array(
                
'doc_type' => 'TransferNote',
                
'doc_id' => '50000000',
            ),
            
'stockin_doc' => array(
                
'doc_type' => 'TransferNote',
                
'doc_id' => '50000000',
            )
        ));
    }
}