SupplierReceipting.pm 30.2 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
# 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.




22
package wiaflos::server::core::SupplierReceipting;
Nigel Kukard's avatar
Nigel Kukard committed
23
24
25
26
27
28
29

use strict;
use warnings;


use wiaflos::version;
use wiaflos::constants;
30
31
32
33
34
35
use wiaflos::server::core::config;
use awitpt::db::dblayer;
use awitpt::cache;
use wiaflos::server::core::templating;
use wiaflos::server::core::Suppliers;
use wiaflos::server::core::GL;
Nigel Kukard's avatar
Nigel Kukard committed
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

# 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)) {
84
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
85
		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)) {
106
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
107
		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
	}

	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) {
128
		setError(awitpt::cache::Error());
Nigel Kukard's avatar
Nigel Kukard committed
129
130
131
132
133
134
135
		return $cache_res;
	}
	return $cache if (defined($cache));

	# Select receipt
	my $sth = DBSelect("SELECT ID FROM supplier_receipts WHERE Number = ".DBQuote($number));
	if (!$sth) {
136
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
137
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
138
139
	}

140
	my $row = hashifyLCtoMC($sth->fetchrow_hashref(),qw( ID ));
Nigel Kukard's avatar
Nigel Kukard committed
141
142
143
144
145
146
147
	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
	# Cache this
	$cache_res = cacheStoreKeyPair('SupplierReceipt/Number-to-ID',$number,$row->{'ID'});
	if ($cache_res != RES_OK) {
152
		setError(awitpt::cache::Error());
Nigel Kukard's avatar
Nigel Kukard committed
153
154
155
156
157
158
159
160
161
162
163
164
165
		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

	$data = undef;
	$data->{'ID'} = $rawData->{'SupplierID'};
179
	my $supplier = wiaflos::server::core::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
	$item->{'GLAccountID'} = $rawData->{'GLAccountID'};
185
	$item->{'GLAccountNumber'} = wiaflos::server::core::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'};
219
	my $creditnote = wiaflos::server::core::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

	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
291
	my $supplierID  = wiaflos::server::core::Suppliers::getSupplierIDFromCode($detail->{'SupplierCode'});
Nigel Kukard's avatar
Nigel Kukard committed
292
	if ($supplierID < 1) {
293
		setError(wiaflos::server::core::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
294
295
296
297
		return $supplierID;
	}

	# Check GL account exists
298
	my $GLAccountID = wiaflos::server::core::GL::getGLAccountIDFromNumber($detail->{'GLAccountNumber'});
Nigel Kukard's avatar
Nigel Kukard committed
299
	if ($GLAccountID < 1) {
300
		setError(wiaflos::server::core::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
301
302
303
304
305
306
307
308
309
310
311
		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) {
326
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
327
		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) {
354
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
355
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
356
357
358
	}

	# Fetch rows
359
360
361
	while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(),
			qw( ID SupplierID GLAccountID Number TransactionDate Reference Amount Closed )
	)) {
Nigel Kukard's avatar
Nigel Kukard committed
362
363
		# Check what kind of receipts do we want
		if (($type eq "open") && $row->{'Closed'} eq "0") {
Nigel Kukard's avatar
Nigel Kukard committed
364
			push(@receipts,sanitizeRawItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
365
		} elsif ($type eq "all") {
Nigel Kukard's avatar
Nigel Kukard committed
366
			push(@receipts,sanitizeRawItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
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
402
403
		}
	}

	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'};
	}
404

Nigel Kukard's avatar
Nigel Kukard committed
405
406
407
408
409
410
411
412
	# 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("
413
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
414
415
416
417
418
419
420
			ID, SupplierID, GLAccountID, Number, TransactionDate, Reference, Amount, GLTransactionID, Closed
		FROM
			supplier_receipts
		WHERE
			ID = ".DBQuote($receiptID)."
	");
	if (!$sth) {
421
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
422
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
423
424
425
	}

	# Fetch rows
426
427
	my $row = hashifyLCtoMC($sth->fetchrow_hashref(),
			qw( ID SupplierID GLAccountID Number TransactionDate Reference Amount GLTransactionID Closed ));
Nigel Kukard's avatar
Nigel Kukard committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
	DBFreeRes($sth);

	return sanitizeRawItem($row);
}



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


	my $data;
444

Nigel Kukard's avatar
Nigel Kukard committed
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'};
463
	my $supplier = wiaflos::server::core::Suppliers::getSupplier($data);
Nigel Kukard's avatar
Nigel Kukard committed
464
	if (ref $supplier ne "HASH") {
465
		setError(wiaflos::server::core::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
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;
476
	my $GLTransactionID = wiaflos::server::core::GL::createGLTransaction($data);
Nigel Kukard's avatar
Nigel Kukard committed
477
	if ($GLTransactionID < 1) {
478
		setError(wiaflos::server::core::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
479
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
480
		return $GLTransactionID;
Nigel Kukard's avatar
Nigel Kukard committed
481
482
483
484
485
486
487
488
489
490
491
	}

	# 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();
492
493
	if ((my $res = wiaflos::server::core::GL::linkGLTransaction($data)) < 1) {
		setError(wiaflos::server::core::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
494
495
496
497
498
499
500
501
502
503
504
505
		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();
506
507
	if ((my $res = wiaflos::server::core::GL::linkGLTransaction($data)) < 1) {
		setError(wiaflos::server::core::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
508
509
510
511
512
513
514
515
516
517
518
519
520
		DBRollback();
		return $res;
	}

	# Post receipt
	my $sth = DBDo("
		UPDATE supplier_receipts
		SET
			GLTransactionID = ".DBQuote($GLTransactionID)."
		WHERE
			ID = ".DBQuote($receipt->{'ID'})."
	");
	if (!$sth) {
521
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
522
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
523
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
524
525
526
527
528
	}

	# Post transaction
	$data = undef;
	$data->{'ID'} = $GLTransactionID;
529
530
	if ((my $res = wiaflos::server::core::GL::postGLTransaction($data)) != 0) {
		setError(wiaflos::server::core::GL::Error());
Nigel Kukard's avatar
Nigel Kukard committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
		DBRollback();
		return $res;
	}

	DBCommit();

	return $GLTransactionID;
}



# Create allocation
# Parameters:
#		ReceiptNumber	- Receipt number
Nigel Kukard's avatar
Nigel Kukard committed
545
#		SupplierCreditNoteNumber	- Credit note number
Nigel Kukard's avatar
Nigel Kukard committed
546
547
548
549
550
551
552
553
554
555
556
557
558
#		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
559
	if (!defined($detail->{'SupplierCreditNoteNumber'}) || $detail->{'SupplierCreditNoteNumber'} eq "") {
Nigel Kukard's avatar
Nigel Kukard committed
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
587
588
		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");
589
		return ERR_POSTED;
Nigel Kukard's avatar
Nigel Kukard committed
590
591
592
593
	}

	# Grab credit note
	$data = undef;
Nigel Kukard's avatar
Nigel Kukard committed
594
	$data->{'Number'} = $detail->{'SupplierCreditNoteNumber'};
595
	my $creditnote = wiaflos::server::core::SupplierCreditNotes::getSupplierCreditNote($data);
Nigel Kukard's avatar
Nigel Kukard committed
596
	if (ref $creditnote ne "HASH") {
597
		setError(wiaflos::server::core::SupplierCreditNotes::Error());
Nigel Kukard's avatar
Nigel Kukard committed
598
599
600
601
602
603
604
		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");
605
		return ERR_POSTED;
Nigel Kukard's avatar
Nigel Kukard committed
606
607
608
609
610
	}


	# Grab allocations
	$data = undef;
Nigel Kukard's avatar
Nigel Kukard committed
611
	$data->{'SupplierReceiptID'} = $receipt->{'ID'};
Nigel Kukard's avatar
Nigel Kukard committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
	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
632
				(SupplierReceiptID,SupplierCreditNoteID,Amount)
Nigel Kukard's avatar
Nigel Kukard committed
633
634
635
636
637
638
639
640
			VALUES
				(
					".DBQuote($receipt->{'ID'}).",
					".DBQuote($creditnote->{'ID'}).",
					".DBQuote($detail->{'Amount'})."
				)
	");
	if (!$sth) {
641
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
642
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
	}

	# 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) = @_;
661

Nigel Kukard's avatar
Nigel Kukard committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
	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
677
		if (($receiptID = getSupplierReceiptIDFromNumber($detail->{'SupplierReceiptNumber'})) < 1) {
Nigel Kukard's avatar
Nigel Kukard committed
678
679
680
			setError(Error());
			return $receiptID;
		}
681

Nigel Kukard's avatar
Nigel Kukard committed
682
683
684
685
686
687
688
689
690
691
		$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;
	}
692

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

	# Fetch rows
708
709
710
	while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(),
			qw( ID SupplierCreditNoteID SupplierReceiptID Amount SupplierCreditNoteTransactionID )
	)) {
Nigel Kukard's avatar
Nigel Kukard committed
711
		push(@allocations,sanitizeRawAllocationItem($row));
Nigel Kukard's avatar
Nigel Kukard committed
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
	}

	DBFreeRes($sth);

	return \@allocations;
}



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

Nigel Kukard's avatar
Nigel Kukard committed
728
729
730
731
732
733
734
735
736

	# 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("
737
		SELECT
Nigel Kukard's avatar
Nigel Kukard committed
738
739
740
741
742
743
744
			ID, SupplierReceiptID, SupplierCreditNoteID, Amount, SupplierCreditNoteTransactionID
		FROM
			supplier_receipt_allocations
		WHERE
			ID = ".DBQuote($detail->{'ID'})."
	");
	if (!$sth) {
745
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
746
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
747
748
749
	}

	# Fetch rows
750
751
	my $row = hashifyLCtoMC($sth->fetchrow_hashref(),
			qw( ID SupplierReceiptID SupplierCreditNoteID Amount SupplierCreditNoteTransactionID ));
Nigel Kukard's avatar
Nigel Kukard committed
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
	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;
774

Nigel Kukard's avatar
Nigel Kukard committed
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
	# 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'};
802
	my $creditnote = wiaflos::server::core::SupplierCreditNotes::getSupplierCreditNote($data);
Nigel Kukard's avatar
Nigel Kukard committed
803
	if (ref $creditnote ne "HASH") {
804
		setError(wiaflos::server::core::SupplierCreditNotes::Error());
Nigel Kukard's avatar
Nigel Kukard committed
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
855
856
857
858
		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();
859

Nigel Kukard's avatar
Nigel Kukard committed
860
861
862
863
	# If we equal out, mark it as being closed
	if ($receiptBalance->is_zero()) {
		# Close it off
		my $sth = DBDo("
864
			UPDATE
Nigel Kukard's avatar
Nigel Kukard committed
865
866
867
868
869
870
871
				supplier_receipts
			SET
				Closed = 1
			WHERE
				ID = ".DBQuote($receipt->{'ID'})."
		");
		if (!$sth) {
872
			setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
873
874
			DBRollback();
			return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
875
876
877
878
879
880
881
882
883
		}
	}


	# Create transaction
	$data = undef;
	$data->{'ID'} = $creditnote->{'ID'};
	$data->{'Amount'} = Math::BigFloat->new($allocation->{'Amount'})->bneg();
	$data->{'SupplierReceiptAllocationID'} = $allocation->{'ID'};
884
	my $creditNoteTransactionID = wiaflos::server::core::SupplierCreditNotes::allocateSupplierCreditNoteTransaction($data);
Nigel Kukard's avatar
Nigel Kukard committed
885
	if ($creditNoteTransactionID < 1) {
886
		setError(wiaflos::server::core::Invoicing::Error());
Nigel Kukard's avatar
Nigel Kukard committed
887
888
889
890
891
892
893
894
895
896
897
898
899
		DBRollback();
		return $creditNoteTransactionID;
	}

	# Post allocation
	my $sth = DBDo("
		UPDATE supplier_receipt_allocations
		SET
			SupplierCreditNoteTransactionID = ".DBQuote($creditNoteTransactionID)."
		WHERE
			ID = ".DBQuote($allocation->{'ID'})."
	");
	if (!$sth) {
900
		setError(awitpt::db::dblayer::Error());
Nigel Kukard's avatar
Nigel Kukard committed
901
		DBRollback();
Nigel Kukard's avatar
Nigel Kukard committed
902
		return ERR_DB;
Nigel Kukard's avatar
Nigel Kukard committed
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
	}


	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
929
	my $config = wiaflos::server::core::config::getConfig();
Nigel Kukard's avatar
Nigel Kukard committed
930
931
932
933

	# Grab receipt
	my $data;
	$data->{'Number'} = $detail->{'Number'};
Nigel Kukard's avatar
Nigel Kukard committed
934
	my $receipt = getSupplierReceipt($data);
Nigel Kukard's avatar
Nigel Kukard committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
	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
954
	my $supplier = wiaflos::server::core::Suppliers::getSupplier($data);
Nigel Kukard's avatar
Nigel Kukard committed
955
	if (ref $supplier ne "HASH") {
956
		setError(wiaflos::server::core::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
957
958
959
960
		return $supplier;
	}

	# Pull in addresses
961
	my $addresses = wiaflos::server::core::Suppliers::getSupplierAddresses($data);
Nigel Kukard's avatar
Nigel Kukard committed
962
	if (ref $addresses ne "ARRAY") {
963
		setError(wiaflos::server::core::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
964
965
		return $addresses;
	}
966

Nigel Kukard's avatar
Nigel Kukard committed
967
	# Pull in email addresses
968
	my $emailAddies = wiaflos::server::core::Suppliers::getSupplierEmailAddresses($data);
Nigel Kukard's avatar
Nigel Kukard committed
969
	if (ref $emailAddies ne "ARRAY") {
970
		setError(wiaflos::server::core::Suppliers::Error());
Nigel Kukard's avatar
Nigel Kukard committed
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
		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;
988
	# Setup shipping address
Nigel Kukard's avatar
Nigel Kukard committed
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'});