SupplierReceipting.pm 29.5 KB
Newer Older
Nigel Kukard's avatar
Nigel Kukard committed
1
# Supplier receipting functions
2
# Copyright (C) 2009-2014, AllWorldIT
Nigel Kukard's avatar
Nigel Kukard committed
3
# Copyright (C) 2008, LinuxRulz
4
#
Nigel Kukard's avatar
Nigel Kukard committed
5
6
7
8
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
9
#
Nigel Kukard's avatar
Nigel Kukard committed
10
11
12
13
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
14
#
Nigel Kukard's avatar
Nigel Kukard committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.




package wiaflos::server::SupplierReceipting;

use strict;
use warnings;


use wiaflos::version;
use wiaflos::constants;
use wiaflos::server::config;
use wiaflos::server::dblayer;
use wiaflos::server::cache;
33
use wiaflos::server::templating;
Nigel Kukard's avatar
Nigel Kukard committed
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
use wiaflos::server::Suppliers;
use wiaflos::server::GL;

# Whole money transactions, precision is two
use Math::BigFloat;
Math::BigFloat::precision(-2);




# Our current error message
my $error = "";

# Set current error message
# Args: error_message
sub setError
{
	my $err = shift;
	my ($package,$filename,$line) = caller;
	my (undef,undef,undef,$subroutine) = caller(1);

	# Set error
	$error = "$subroutine($line): $err";
}

# Return current error message
# Args: none
sub Error
{
	my $err = $error;

	# Reset error
	$error = "";

	# Return error
	return $err;
}



# Check if receipt exists
# Backend function, takes 1 parameter which is the receipt ID
sub supplierReceiptIDExists
{
	my $receiptID = shift;


	# Select receipt count
	my $rows = DBSelectNumResults("FROM supplier_receipts WHERE ID = ".DBQuote($receiptID));
	if (!defined($rows)) {
Nigel Kukard's avatar
Nigel Kukard committed
84
85
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
	}

	return $rows > 0 ? 1 : 0;
}



# Check if receipt number exists
sub supplierReceiptNumberExists
{
	my $number = shift;


	# Sanitize
	$number = uc($number);
	$number =~ s#^SRT/##;

	# Select receipt count
	my $rows = DBSelectNumResults("FROM supplier_receipts WHERE Number = ".DBQuote($number));
	if (!defined($rows)) {
Nigel Kukard's avatar
Nigel Kukard committed
106
107
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
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
	}

	return $rows > 0 ? 1 : 0;
}



# Return receipt ID from number
sub getSupplierReceiptIDFromNumber
{
	my $number = shift;


	# Sanitize
	$number = uc($number);
	$number =~ s#^SRT/##;

	# Check cache
	my ($cache_res,$cache) = cacheGetKeyPair('SupplierReceipt/Number-to-ID',$number);
	if ($cache_res != RES_OK) {
		setError(wiaflos::server::cache::Error());
		return $cache_res;
	}
	return $cache if (defined($cache));

	# Select receipt
	my $sth = DBSelect("SELECT ID FROM supplier_receipts WHERE Number = ".DBQuote($number));
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
136
137
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
138
139
140
141
142
143
144
145
146
147
	}

	my $row = $sth->fetchrow_hashref();
	DBFreeRes($sth);

	# Check we got a result
	if (!defined($row)) {
		setError("Error finding supplier receipt '$number'");
		return ERR_NOTFOUND;
	}
148

Nigel Kukard's avatar
Nigel Kukard committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	# Cache this
	$cache_res = cacheStoreKeyPair('SupplierReceipt/Number-to-ID',$number,$row->{'ID'});
	if ($cache_res != RES_OK) {
		setError(wiaflos::server::cache::Error());
		return $cache_res;
	}

	return $row->{'ID'};
}




# Backend function to build item hash
sub sanitizeRawItem
{
	my $rawData = shift;
166
167


Nigel Kukard's avatar
Nigel Kukard committed
168
	my $item;
169

Nigel Kukard's avatar
Nigel Kukard committed
170
171
172
173
174
	$item->{'ID'} = $rawData->{'ID'};

	my $data;

	# Pull in supplier data
Nigel Kukard's avatar
Nigel Kukard committed
175
	$item->{'SupplierID'} = $rawData->{'SupplierID'};
Nigel Kukard's avatar
Nigel Kukard committed
176
177
178
179

	$data = undef;
	$data->{'ID'} = $rawData->{'SupplierID'};
	my $supplier = wiaflos::server::Suppliers::getSupplier($data);
Nigel Kukard's avatar
Nigel Kukard committed
180
	$item->{'SupplierCode'} = $supplier->{'Code'};
181

Nigel Kukard's avatar
Nigel Kukard committed
182
183

	# Pull in GL account info
Nigel Kukard's avatar
Nigel Kukard committed
184
185
	$item->{'GLAccountID'} = $rawData->{'GLAccountID'};
	$item->{'GLAccountNumber'} = wiaflos::server::GL::getGLAccountNumberFromID($rawData->{'GLAccountID'});
Nigel Kukard's avatar
Nigel Kukard committed
186

Nigel Kukard's avatar
Nigel Kukard committed
187
	$item->{'Number'} = "SRT/".uc($rawData->{'Number'});
Nigel Kukard's avatar
Nigel Kukard committed
188

Nigel Kukard's avatar
Nigel Kukard committed
189
190
191
	$item->{'TransactionDate'} = $rawData->{'TransactionDate'};
	$item->{'Reference'} = $rawData->{'Reference'};
	$item->{'Amount'} = $rawData->{'Amount'};
192

Nigel Kukard's avatar
Nigel Kukard committed
193
	$item->{'GLTransactionID'} = $rawData->{'GLTransactionID'};
Nigel Kukard's avatar
Nigel Kukard committed
194
	$item->{'Posted'} = defined($rawData->{'GLTransactionID'}) ? 1 : 0;
195

Nigel Kukard's avatar
Nigel Kukard committed
196
197
198
199
200
201
202
203
204
205
206
	$item->{'Closed'} = $rawData->{'Closed'};

	return $item;
}



# Backend function to build item hash
sub sanitizeRawAllocationItem
{
	my $rawData = shift;
207
208


Nigel Kukard's avatar
Nigel Kukard committed
209
	my $item;
210

Nigel Kukard's avatar
Nigel Kukard committed
211
212
213
214
215
	$item->{'ID'} = $rawData->{'ID'};


   	# Pull in credit note data
	$item->{'SupplierCreditNoteID'} = $rawData->{'SupplierCreditNoteID'};
216

Nigel Kukard's avatar
Nigel Kukard committed
217
218
	my $data;
	$data->{'ID'} = $rawData->{'SupplierCreditNoteID'};
Nigel Kukard's avatar
Nigel Kukard committed
219
	my $creditnote = wiaflos::server::SupplierCreditNotes::getSupplierCreditNote($data);
Nigel Kukard's avatar
Nigel Kukard committed
220
	$item->{'SupplierCreditNoteNumber'} = $creditnote->{'Number'};
221

Nigel Kukard's avatar
Nigel Kukard committed
222
223
	# And the receipt
	$item->{'SupplierReceiptID'} = $rawData->{'SupplierReceiptID'};
224

Nigel Kukard's avatar
Nigel Kukard committed
225
	$data = undef;
Nigel Kukard's avatar
Nigel Kukard committed
226
	$data->{'ID'} = $rawData->{'SupplierReceiptID'};
Nigel Kukard's avatar
Nigel Kukard committed
227
228
229
230
	my $receipt = getSupplierReceipt($data);
	$item->{'SupplierReceiptNumber'} = $receipt->{'Number'};


Nigel Kukard's avatar
Nigel Kukard committed
231
	$item->{'Amount'} = $rawData->{'Amount'};
232

Nigel Kukard's avatar
Nigel Kukard committed
233
	$item->{'Posted'} = defined($rawData->{'SupplierCreditNoteTransactionID'}) ? 1 : 0;
Nigel Kukard's avatar
Nigel Kukard committed
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

	return $item;
}



# Create receipt
# Parameters:
#		SupplierCode	- Supplier code
#		GLAccountNumber	- GL account where money was paid from
#		Number		- Number for this receipt
#		Date		- Date of receipt
#		Reference		- GL account entry reference (bank statement reference for example)
#		Amount		- Amount
sub createSupplierReceipt
{
	my ($detail) = @_;


	# Verify receipt number
	if (!defined($detail->{'Number'}) || $detail->{'Number'} eq "") {
		setError("No (or invalid) supplier receipt number provided");
		return ERR_PARAM;
	}
	(my $receiptNumber = uc($detail->{'Number'})) =~ s#^SRT/##;

	# Verify supplier code
	if (!defined($detail->{'SupplierCode'}) || $detail->{'SupplierCode'} eq "") {
		setError("No (or invalid) supplier code provided for supplier receipt '".$detail->{'Number'}."'");
		return ERR_PARAM;
	}

	# Verify GL account
	if (!defined($detail->{'GLAccountNumber'}) || $detail->{'GLAccountNumber'} eq "") {
		setError("No (or invalid) GL account provided for supplier receipt '".$detail->{'Number'}."'");
		return ERR_PARAM;
	}

	# Verify date
	if (!defined($detail->{'Date'}) || $detail->{'Date'} eq "") {
		setError("No (or invalid) date provided for supplier receipt '".$detail->{'Number'}."'");
		return ERR_PARAM;
	}

	# Verify reference
	if (!defined($detail->{'Reference'}) || $detail->{'Reference'} eq "") {
		setError("No (or invalid) reference provided for supplier receipt '".$detail->{'Number'}."'");
		return ERR_PARAM;
	}

	# Amount
	if (!defined($detail->{'Amount'}) || $detail->{'Amount'} eq "") {
		setError("No (or invalid) amount account provided for supplier receipt '".$detail->{'Number'}."'");
		return ERR_PARAM;
	}

	# Check if supplier exists
	my $supplierID  = wiaflos::server::Suppliers::getSupplierIDFromCode($detail->{'SupplierCode'});
	if ($supplierID < 1) {
		setError(wiaflos::server::Suppliers::Error());
		return $supplierID;
	}

	# Check GL account exists
	my $GLAccountID = wiaflos::server::GL::getGLAccountIDFromNumber($detail->{'GLAccountNumber'});
	if ($GLAccountID < 1) {
		setError(wiaflos::server::GL::Error());
		return $GLAccountID;
	}

	# Check for conflicts
	if (supplierReceiptNumberExists($receiptNumber)) {
		setError("Supplier receipt number '$receiptNumber' already exists");
		return ERR_CONFLICT;
	}

	# Create receipt
	my $sth = DBDo("
312
		INSERT INTO supplier_receipts
Nigel Kukard's avatar
Nigel Kukard committed
313
314
315
316
317
318
319
320
321
322
323
324
325
				(SupplierID,GLAccountID,Number,TransactionDate,Reference,Amount,Closed)
			VALUES
				(
					".DBQuote($supplierID).",
					".DBQuote($GLAccountID).",
					".DBQuote($receiptNumber).",
					".DBQuote($detail->{'Date'}).",
					".DBQuote($detail->{'Reference'}).",
					".DBQuote($detail->{'Amount'}).",
					0
				)
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
326
327
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
	}

	# Grab last ID
	my $ID = DBLastInsertID("supplier_receipts","ID");

	return $ID;
}



# Return an array of receipts
sub getSupplierReceipts
{
	my ($detail) = @_;
	my $type = defined($detail->{'Type'}) ? $detail->{'Type'} : "open";
	my @receipts = ();


	# Return list of receipts
	my $sth = DBSelect("
348
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
349
350
351
352
353
			ID, SupplierID, GLAccountID, Number, TransactionDate, Reference, Amount, Closed
		FROM
			supplier_receipts
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
354
355
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
356
357
358
359
360
361
	}

	# Fetch rows
	while (my $row = $sth->fetchrow_hashref()) {
		# Check what kind of receipts do we want
		if (($type eq "open") && $row->{'Closed'} eq "0") {
Nigel Kukard's avatar
Nigel Kukard committed
362
			push(@receipts,sanitizeRawItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
363
		} elsif ($type eq "all") {
Nigel Kukard's avatar
Nigel Kukard committed
364
			push(@receipts,sanitizeRawItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
		}
	}

	DBFreeRes($sth);

	return \@receipts;
}



# Return an receipt hash
# Optional:
#		Number	- Receipt number
#		ID		- Receipt ID
sub getSupplierReceipt
{
	my ($detail) = @_;


	my $receiptID;

	# Check which 'mode' we operating in
	if (!defined($detail->{'ID'}) || $detail->{'ID'} < 1) {
		# Verify receipt number
		if (!defined($detail->{'Number'}) || $detail->{'Number'} eq "") {
			setError("No (or invalid) supplier receipt number provided");
			return ERR_PARAM;
		}

		# Check if receipt exists
		if (($receiptID = getSupplierReceiptIDFromNumber($detail->{'Number'})) < 1) {
			setError(Error());
			return $receiptID;
		}
	} else {
		$receiptID = $detail->{'ID'};
	}
402

Nigel Kukard's avatar
Nigel Kukard committed
403
404
405
406
407
408
409
410
	# Verify receipt ID
	if (!$receiptID || $receiptID < 1) {
		setError("No (or invalid) supplier receipt number/id provided");
		return ERR_PARAM;
	}

	# Return list of receipts
	my $sth = DBSelect("
411
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
412
413
414
415
416
417
418
			ID, SupplierID, GLAccountID, Number, TransactionDate, Reference, Amount, GLTransactionID, Closed
		FROM
			supplier_receipts
		WHERE
			ID = ".DBQuote($receiptID)."
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
419
420
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
	}

	# Fetch rows
	my $row = $sth->fetchrow_hashref();

	DBFreeRes($sth);

	return sanitizeRawItem($row);
}



# One can now post the receipt, which sets GLTransactionID
# Parameters:
#		Number	- Receipt number
sub postSupplierReceipt
{
	my ($detail) = @_;


	my $data;
442

Nigel Kukard's avatar
Nigel Kukard committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
	# Grab receipt
	$data = undef;
	$data->{'Number'} = $detail->{'Number'};
	my $receipt = getSupplierReceipt($data);
	if (ref $receipt ne "HASH") {
		setError(Error());
		return $receipt;
	}

	# Make sure receipt is not posted
	if ($receipt->{'Posted'} eq "1") {
		setError("Receipt '".$receipt->{'Number'}."' already posted");
		return ERR_POSTED;
	}

	# Pull in supplier
	$data = undef;
	$data->{'ID'} = $receipt->{'SupplierID'};
	my $supplier = wiaflos::server::Suppliers::getSupplier($data);
	if (ref $supplier ne "HASH") {
Nigel Kukard's avatar
Nigel Kukard committed
463
		setError(wiaflos::server::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
464
465
466
467
468
469
470
471
472
473
474
475
		return $supplier;
	}

	DBBegin();

	# Create transaction
	my $transactionRef = sprintf('Receipt: %s',$receipt->{'Number'});
	$data = undef;
	$data->{'Date'} = $receipt->{'TransactionDate'};
	$data->{'Reference'} = $transactionRef;
	my $GLTransactionID = wiaflos::server::GL::createGLTransaction($data);
	if ($GLTransactionID < 1) {
Nigel Kukard's avatar
Nigel Kukard committed
476
		setError(wiaflos::server::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
477
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
478
		return $GLTransactionID;
Nigel Kukard's avatar
Nigel Kukard committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
	}

	# Pull in amount
	my $transValue = Math::BigFloat->new($receipt->{'Amount'});

	# Link from GL
	$data = undef;
	$data->{'ID'} = $GLTransactionID;
#	$data->{'Reference'} = $receipt->{'Reference'};
	$data->{'GLAccountID'} = $receipt->{'GLAccountID'};
	$data->{'Amount'} = $transValue->bstr();
	if ((my $res = wiaflos::server::GL::linkGLTransaction($data)) < 1) {
		setError(wiaflos::server::GL::Error());
		DBRollback();
		return $res;
	}

	# Negate for other side
	$transValue->bneg();

	# Link to supplier GL account
	$data = undef;
	$data->{'ID'} = $GLTransactionID;
	$data->{'GLAccountID'} = $supplier->{'GLAccountID'};
	$data->{'Amount'} = $transValue->bstr();
	if ((my $res = wiaflos::server::GL::linkGLTransaction($data)) < 1) {
		setError(wiaflos::server::GL::Error());
		DBRollback();
		return $res;
	}

	# Post receipt
	my $sth = DBDo("
		UPDATE supplier_receipts
		SET
			GLTransactionID = ".DBQuote($GLTransactionID)."
		WHERE
			ID = ".DBQuote($receipt->{'ID'})."
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
519
		setError(wiaflos::server::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
520
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
521
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
	}

	# Post transaction
	$data = undef;
	$data->{'ID'} = $GLTransactionID;
	if ((my $res = wiaflos::server::GL::postGLTransaction($data)) != 0) {
		setError(wiaflos::server::GL::Error());
		DBRollback();
		return $res;
	}

	DBCommit();

	return $GLTransactionID;
}



# Create allocation
# Parameters:
#		ReceiptNumber	- Receipt number
Nigel Kukard's avatar
Nigel Kukard committed
543
#		SupplierCreditNoteNumber	- Credit note number
Nigel Kukard's avatar
Nigel Kukard committed
544
545
546
547
548
549
550
551
552
553
554
555
556
#		Amount		- Amount
sub createSupplierReceiptAllocation
{
	my ($detail) = @_;


	# Verify receipt number
	if (!defined($detail->{'ReceiptNumber'}) || $detail->{'ReceiptNumber'} eq "") {
		setError("No (or invalid) supplier receipt number provided for supplier receipt allocation");
		return ERR_PARAM;
	}

	# Verify credit note number
Nigel Kukard's avatar
Nigel Kukard committed
557
	if (!defined($detail->{'SupplierCreditNoteNumber'}) || $detail->{'SupplierCreditNoteNumber'} eq "") {
Nigel Kukard's avatar
Nigel Kukard committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
		setError("No (or invalid) supplier credit note number provided for supplier receipt allocation");
		return ERR_PARAM;
	}

	# Amount
	if (!defined($detail->{'Amount'}) || $detail->{'Amount'} eq "") {
		setError("No (or invalid) amount account provided for supplier receipt allocation");
		return ERR_PARAM;
	}
	my $allocAmount = Math::BigFloat->new($detail->{'Amount'});
	if ($allocAmount->is_zero()) {
		setError("Supplier receipt allocation amount cannot be zero");
		return ERR_AMTZERO;
	}

	my $data;

	# Check if receipt exists & pull in
	$data = undef;
	$data->{'Number'} = $detail->{'ReceiptNumber'};
	my $receipt = getSupplierReceipt($data);
	if (ref $receipt ne "HASH" ) {
		setError(Error());
		return $receipt;
	}

	# Make sure receipt is posted
	if ($receipt->{'Posted'} ne "1") {
		setError("Receipt '".$receipt->{'Number'}."' must be posted before an allocation can be made");
587
		return ERR_POSTED;
Nigel Kukard's avatar
Nigel Kukard committed
588
589
590
591
	}

	# Grab credit note
	$data = undef;
Nigel Kukard's avatar
Nigel Kukard committed
592
	$data->{'Number'} = $detail->{'SupplierCreditNoteNumber'};
Nigel Kukard's avatar
Nigel Kukard committed
593
594
	my $creditnote = wiaflos::server::SupplierCreditNotes::getSupplierCreditNote($data);
	if (ref $creditnote ne "HASH") {
Nigel Kukard's avatar
Nigel Kukard committed
595
		setError(wiaflos::server::SupplierCreditNotes::Error());
Nigel Kukard's avatar
Nigel Kukard committed
596
597
598
599
600
601
602
		return $creditnote;
	}

	# Check if credit note is posted
	if ($creditnote->{'Posted'} ne "1") {
		setError("Cannot allocate an amount from supplier receipt '".$receipt->{'Number'}."' to creditnote '".
				$creditnote->{'Number'}."' as the credit note is not posted");
603
		return ERR_POSTED;
Nigel Kukard's avatar
Nigel Kukard committed
604
605
606
607
608
	}


	# Grab allocations
	$data = undef;
Nigel Kukard's avatar
Nigel Kukard committed
609
	$data->{'SupplierReceiptID'} = $receipt->{'ID'};
Nigel Kukard's avatar
Nigel Kukard committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
	my $allocs = getSupplierReceiptAllocations($data);
	if (ref $allocs ne "ARRAY") {
		setError(Error());
		return $allocs;
	}

	# Check if we either balance to 0 or have left over
	my $receiptBalance = Math::BigFloat->new($receipt->{'Amount'});
	foreach my $alloc (@{$allocs}) {
		$receiptBalance->bsub($alloc->{'Amount'});
	}
	$receiptBalance->bsub($detail->{'Amount'});
	if ($receiptBalance->is_neg()) {
		setError("Creating this allocation will exceed supplier receipt '".$receipt->{'Number'}."' amount by ".$receiptBalance->bstr());
		return ERR_OVERALLOC;
	}

	# Create supplier receipt allocation
	my $sth = DBDo("
		INSERT INTO supplier_receipt_allocations
630
				(SupplierReceiptID,SupplierCreditNoteID,Amount)
Nigel Kukard's avatar
Nigel Kukard committed
631
632
633
634
635
636
637
638
			VALUES
				(
					".DBQuote($receipt->{'ID'}).",
					".DBQuote($creditnote->{'ID'}).",
					".DBQuote($detail->{'Amount'})."
				)
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
639
640
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
	}

	# Grab last ID
	my $ID = DBLastInsertID("supplier_receipt_allocations","ID");

	return $ID;
}



# Return an array of receipt allocations
# Parameters:
#		SupplierReceiptNumber	- Receipt number
#		SupplierReceiptID	- Receipt ID
#		SupplierCreditNoteID	-  Credit note ID
sub getSupplierReceiptAllocations
{
	my ($detail) = @_;
659

Nigel Kukard's avatar
Nigel Kukard committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
	my @allocations = ();


	# SQL query string to use
	my $query = "";

	# ID mode
	if (defined($detail->{'SupplierReceiptID'}) && $detail->{'SupplierReceiptID'} > 0) {
		$query .= "SupplierReceiptID = ".$detail->{'SupplierReceiptID'};

	# Receipt number mode
	} elsif (defined($detail->{'SupplierReceiptNumber'}) && $detail->{'SupplierReceiptNumber'} ne "") {
		my $receiptID;

		# Check if receipt exists
Nigel Kukard's avatar
Nigel Kukard committed
675
		if (($receiptID = getSupplierReceiptIDFromNumber($detail->{'SupplierReceiptNumber'})) < 1) {
Nigel Kukard's avatar
Nigel Kukard committed
676
677
678
			setError(Error());
			return $receiptID;
		}
679

Nigel Kukard's avatar
Nigel Kukard committed
680
681
682
683
684
685
686
687
688
689
		$query .= "SupplierReceiptID = ".DBQuote($receiptID);

	# Credit note ID mode
	} elsif (defined($detail->{'SupplierCreditNoteID'}) && $detail->{'SupplierCreditNoteID'} ne "") {
		$query .= "SupplierCreditNoteID = ".DBQuote($detail->{'SupplierCreditNoteID'});

	} else {
		setError("No acceptable parameters provided to return supplier receipts allocations");
		return ERR_PARAM;
	}
690

Nigel Kukard's avatar
Nigel Kukard committed
691
692
	# Return list of receipt allocations
	my $sth = DBSelect("
693
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
694
695
			ID, SupplierCreditNoteID, SupplierReceiptID, Amount, SupplierCreditNoteTransactionID
		FROM
Nigel Kukard's avatar
Nigel Kukard committed
696
			supplier_receipt_allocations
Nigel Kukard's avatar
Nigel Kukard committed
697
698
699
700
		WHERE
			$query
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
701
702
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
703
704
705
706
	}

	# Fetch rows
	while (my $row = $sth->fetchrow_hashref()) {
Nigel Kukard's avatar
Nigel Kukard committed
707
		push(@allocations,sanitizeRawAllocationItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
	}

	DBFreeRes($sth);

	return \@allocations;
}



# Return an hash containing a allocation
# Parameters:
#		ID	- Allocation ID
sub getSupplierReceiptAllocation
{
	my ($detail) = @_;
723

Nigel Kukard's avatar
Nigel Kukard committed
724
725
726
727
728
729
730
731
732

	# Verify allocation id
	if (!defined($detail->{'ID'}) || $detail->{'ID'} eq "") {
		setError("No (or invalid) allocation ID provided");
		return ERR_PARAM;
	}

	# Return allocation
	my $sth = DBSelect("
733
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
734
735
736
737
738
739
740
			ID, SupplierReceiptID, SupplierCreditNoteID, Amount, SupplierCreditNoteTransactionID
		FROM
			supplier_receipt_allocations
		WHERE
			ID = ".DBQuote($detail->{'ID'})."
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
741
742
		setError(wiaflos::server::dblayer::Error());
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
	}

	# Fetch rows
	my $row = $sth->fetchrow_hashref();

	DBFreeRes($sth);

	return sanitizeRawAllocationItem($row);
}



# One can now post the allocation, which checks the invoice if its totally paid
# Parameters:
#		ID	- Receipt allocation ID
sub postSupplierReceiptAllocation
{
	my ($detail) = @_;


	# Verify allocation ID
	if (!defined($detail->{'ID'}) || $detail->{'ID'} eq "") {
		setError("No (or invalid) allocation ID provided");
		return ERR_PARAM;
	}

	my $data;
770

Nigel Kukard's avatar
Nigel Kukard committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
	# Check if allocation exists & pull in
	$data = undef;
	$data->{'ID'} = $detail->{'ID'};
	my $allocation = getSupplierReceiptAllocation($data);
	if (ref $allocation ne "HASH") {
		setError(Error());
		return $allocation;
	}

	# Make sure allocation is not posted
	if ($allocation->{'Posted'} ne "0") {
		setError("Supplier receipt allocation '".$allocation->{'ID'}."' already posted");
		return ERR_POSTED;
	}

	# Get corrosponding receipt
	$data = undef;
	$data->{'ID'} = $allocation->{'SupplierReceiptID'};
	my $receipt = getSupplierReceipt($data);
	if (ref $receipt ne "HASH") {
		setError(Error());
		return $receipt;
	}

	# Grab credit note
	$data = undef;
	$data->{'ID'} = $allocation->{'SupplierCreditNoteID'};
	my $creditnote = wiaflos::server::SupplierCreditNotes::getSupplierCreditNote($data);
	if (ref $creditnote ne "HASH") {
		setError(wiaflos::server::SupplierCreditNotes::Error());
		return $creditnote;
	}

	# Make sure credit note is posted
	if ($creditnote->{'Posted'} ne "1") {
		setError("Supplier credit note '".$creditnote->{'Number'}."' not posted");
		return ERR_POSTED;
	}

	# Grab credit note allocations
	$data = undef;
	$data->{'SupplierCreditNoteID'} = $allocation->{'SupplierCreditNoteID'};
	my $creditnoteAllocations = getSupplierReceiptAllocations($data);
	if (ref $creditnoteAllocations ne "ARRAY") {
		setError(Error());
		return $creditnoteAllocations;
	}
	# Add up credit note balance
	my $creditnoteBalance = Math::BigFloat->new($creditnote->{'Total'});
	foreach my $alloc (@{$creditnoteAllocations}) {
		if ($alloc->{'Posted'} eq "1") {
			$creditnoteBalance->bsub($alloc->{'Amount'});
		}
	}
	# Check credit note balance if its negative, this is if we've overallocated
	$creditnoteBalance->bsub($allocation->{'Amount'});
	if ($creditnoteBalance->is_neg()) {
		setError("Posting the allocation will end up in a balance of '".$creditnoteBalance->bstr()."' on credit note '".$creditnote->{'Number'}."'");
		return ERR_OVERALLOC;
	}

	# Grab receipt allocations
	$data = undef;
	$data->{'SupplierReceiptID'} = $receipt->{'ID'};
	my $receiptAllocations = getSupplierReceiptAllocations($data);
	if (ref $receiptAllocations ne "ARRAY") {
		setError(Error());
		return $receiptAllocations;
	}
	# Add up receipt balance
	my $receiptBalance = Math::BigFloat->new($receipt->{'Amount'});
	foreach my $alloc (@{$receiptAllocations}) {
		if ($alloc->{'Posted'} eq "1") {
			$receiptBalance->bsub($alloc->{'Amount'});
		}
	}
	# Check receipt balance if its negative, this is if we've overallocated
	$receiptBalance->bsub($allocation->{'Amount'});
	if ($receiptBalance->is_neg()) {
		setError("Posting the allocation will end up in a balance of '".$receiptBalance->bstr()."' on supplier receipt '".$receipt->{'Number'}."'");
		return ERR_OVERALLOC;
	}

	DBBegin();
855

Nigel Kukard's avatar
Nigel Kukard committed
856
857
858
859
	# If we equal out, mark it as being closed
	if ($receiptBalance->is_zero()) {
		# Close it off
		my $sth = DBDo("
860
			UPDATE
Nigel Kukard's avatar
Nigel Kukard committed
861
862
863
864
865
866
867
				supplier_receipts
			SET
				Closed = 1
			WHERE
				ID = ".DBQuote($receipt->{'ID'})."
		");
		if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
868
869
870
			setError(wiaflos::server::dblayer::Error());
			DBRollback();
			return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
		}
	}


	# Create transaction
	$data = undef;
	$data->{'ID'} = $creditnote->{'ID'};
	$data->{'Amount'} = Math::BigFloat->new($allocation->{'Amount'})->bneg();
	$data->{'SupplierReceiptAllocationID'} = $allocation->{'ID'};
	my $creditNoteTransactionID = wiaflos::server::SupplierCreditNotes::allocateSupplierCreditNoteTransaction($data);
	if ($creditNoteTransactionID < 1) {
		setError(wiaflos::server::Invoicing::Error());
		DBRollback();
		return $creditNoteTransactionID;
	}

	# Post allocation
	my $sth = DBDo("
		UPDATE supplier_receipt_allocations
		SET
			SupplierCreditNoteTransactionID = ".DBQuote($creditNoteTransactionID)."
		WHERE
			ID = ".DBQuote($allocation->{'ID'})."
	");
	if (!$sth) {
Nigel Kukard's avatar
Nigel Kukard committed
896
		setError(wiaflos::server::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
897
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
898
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
	}


	DBCommit();

	return RES_OK;
}



# Send receipt
# Parameters:
#		Number	- Receipt number
#		SendTo		- Send to,  email:  ,  file:  , return
sub sendSupplierReceipt
{
	my ($detail) = @_;


	# Verify SendTo
	if (!defined($detail->{'SendTo'}) || $detail->{'SendTo'} eq "") {
		setError("SendTo was not provided");
		return ERR_PARAM;
	}

	# Pull in config
	my $config = wiaflos::server::config::getConfig();

	# Grab receipt
	my $data;
	$data->{'Number'} = $detail->{'Number'};
Nigel Kukard's avatar
Nigel Kukard committed
930
	my $receipt = getSupplierReceipt($data);
Nigel Kukard's avatar
Nigel Kukard committed
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
	if (ref $receipt ne "HASH") {
		setError(Error());
		return $receipt;
	}

	# Grab items
	$data = undef;
	$data->{'SupplierReceiptID'} = $receipt->{'ID'};
	my $allocations = getSupplierReceiptAllocations($data);
	if (ref $allocations ne "ARRAY") {
		setError(Error());
		return $allocations;
	}

	# Setup request data
	$data = undef;
	$data->{'ID'} = $receipt->{'SupplierID'};

	# Pull supplier
	my $supplier = wiaflos::server::Suppliers::getSupplier($data);
	if (ref $supplier ne "HASH") {
		setError(wiaflos::server::Suppliers::Error());
		return $supplier;
	}

	# Pull in addresses
	my $addresses = wiaflos::server::Suppliers::getSupplierAddresses($data);
	if (ref $addresses ne "ARRAY") {
		setError(wiaflos::server::Suppliers::Error());
		return $addresses;
	}
962

Nigel Kukard's avatar
Nigel Kukard committed
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
	# Pull in email addresses
	my $emailAddies = wiaflos::server::Suppliers::getSupplierEmailAddresses($data);
	if (ref $emailAddies ne "ARRAY") {
		setError(wiaflos::server::Suppliers::Error());
		return $emailAddies;
	}

	# Parse in addresses
	my $billAddr;
	my $shipAddr = "";
	# Look for billing address
	foreach my $address (@{$addresses}) {
		if ($address->{'Type'} eq "billing") {
			$billAddr = $address->{'Address'};
		} elsif ($address->{'Type'} eq "shipping") {
			$shipAddr = $address->{'Address'};
		}
	}
	# If no billing address, use shipping address
	$billAddr = defined($billAddr) ? $billAddr : $shipAddr;
	$billAddr =~ s/\|/<br \/>/g;
984
	# Setup shipping address
Nigel Kukard's avatar
Nigel Kukard committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	$shipAddr =~ s/\|/<br \/>/g if defined($shipAddr);

	# Parse in email addresses
	my $billEmailAddr;
	my @billEmailAddrs;
	my @genEmailAddrs;
	# Look for accounts address
	foreach my $address (@{$emailAddies}) {
		if ($address->{'Type'} eq "accounts") {
			push(@billEmailAddrs,$address->{'Address'});
		} elsif ($address->{'Type'} eq "general") {
			push(@genEmailAddrs,$address->{'Address'});
		}
	}
	# If no accounts address, use general address
	$billEmailAddr = @billEmailAddrs > 0 ? join(',',@billEmailAddrs) : join(',',@genEmailAddrs);
For faster browsing, not all history is shown. View entire blame