/*
    $Id$
 */

// 1 enkele invoice syncen
function SyncSupplierInvoice(InvoiceId, invoice)
{
    var apiU4Record = "SupplierInvoice";
    var newData = {
                    InvoiceId            : InvoiceId,
                    FiscalYear           : invoice.FISCALYEAR,
                    GrootboekPrefix      : invoice.GROOTBOEKPREFIX,
                    InvoiceDate          : invoice.INVOICEDATE,
                    InvoiceExpirationDate: invoice.INVOICEEXPIRATIONDATE,
                    JournalId            : invoice.JOURNALID,
                    JournalTransaction   : invoice.JOURNALTRANSACTION,
                    PaymentConditionId   : invoice.PAYMENTCONDITIONID,
                    PaymentReference     : invoice.PAYMENTREFERENCE,
                    PeriodNumber         : invoice.PERIODNUMBER,
                    RebateExpirationDate : invoice.REBATEEXPIRATIONDATE,
                    Reference            : invoice.REFERENCE,
                    SupplierId           : invoice.SUPPLIERID,
                    SupplierInvoiceLines : invoice.lines,
                    VatOnInvoice         : invoice.VATONINVOICE,
                    VatTransactionLines  : invoice.vats
                };

    var url = "/api/" + database + "/" + apiU4Record + "/" + InvoiceId + ".json";
    var theData = unit4.apiUnit4("GET", url);
    if (theData)
    {   // Bestaande data is al opgehaald
        var method = "PUT";
    }
    else // new record
    {
        method = "POST";
        var url = "/api/" + database + "/" + apiU4Record;
        var theData = {};
    }
    for (var i in newData)
        theData[i] = newData[i];
    theData.BrokenRulesCollection = [];
    WScript.Echo("About to " + method + " " + url + "\n" + JSON.stringify(theData, null, '  '));

    return unit4.apiUnit4(method, url, theData);
}


function SyncSupplierInvoices()
{
//unit4.apiUnit4("DELETE", "/api/MVL00829/SupplierInvoice/47610001", null);
//unit4.apiUnit4("DELETE", "/api/MVL00829/SupplierInvoice/47290001", null);

    // FACILITOR invoices lijst ophalen
    // We filteren niet op database, dat doen we wel/alleen bij SupplierInvoices
    // ==== Invoice lines ====
    var fcltInvoiceLines = apiFACILITOR("UNIT4", "<GetSupplierInvoiceLines/>");
    if (!(fcltInvoiceLines.supplierinvoiceline instanceof Array))
        fcltInvoiceLines.supplierinvoiceline = [fcltInvoiceLines.supplierinvoiceline];
    __Log("Found " + fcltInvoiceLines.supplierinvoiceline.length + " FACILITOR SupplierInvoiceLines (all databases)");
    var Lines = {}; // Groeperen per invoice
    for (var a in fcltInvoiceLines.supplierinvoiceline)
    {
        var invlinedata = fcltInvoiceLines.supplierinvoiceline[a];
        var invoiceId = invlinedata.INVOICEID;
        if (!(invoiceId in Lines))
            Lines[invoiceId] = [];
        Lines[invoiceId].push({
                                AccountId      : invlinedata.ACCOUNTID,
                                DebitAmountCur : invlinedata.DEBITAMOUNTCUR,
                                Description    : invlinedata.DESCRIPTION,
                                VatCodeId      : invlinedata.VATCODEID,
                                TransActionDate: invlinedata.TRANSACTIONDATE
                               });
    }
    // ==== Vat lines ====
    // We filteren niet op database, dat doen we wel/alleen bij SupplierInvoices
    var fcltVatLines = apiFACILITOR("UNIT4", "<GetVatTransactionLines/>");
    if (!(fcltVatLines.vattransactionline instanceof Array))
        fcltVatLines.vattransactionline = [fcltVatLines.vattransactionline];
    __Log("Found " + fcltVatLines.vattransactionline.length + " FACILITOR VatTransactionLines (all databases)");

    var Vats = {}; // Groeperen per invoice
    for (var a in fcltVatLines.vattransactionline)
    {
        var vatdata = fcltVatLines.vattransactionline[a];
        var invoiceId = vatdata.INVOICEID;
        if (!(invoiceId in Vats))
            Vats[invoiceId] = [];
        Vats[invoiceId].push({
                                AmountTurnoverCur: vatdata.AMOUNTTURNOVERCUR,
                                VatAmountCur: vatdata.VATAMOUNTCUR
                               });
    }

    // ==== Invoice records ====
    var fcltInvoice = apiFACILITOR("UNIT4", "<GetSupplierInvoices><database>" + database + "</database></GetSupplierInvoices>");
    if (!(fcltInvoice.supplierinvoice instanceof Array))
        fcltInvoice.supplierinvoice = [fcltInvoice.supplierinvoice];

    __Log("Found " + fcltInvoice.supplierinvoice.length + " FACILITOR SupplierInvoices for database " + database);

    var anybad = false;
    for (var a in fcltInvoice.supplierinvoice)
    {
        var invdata = fcltInvoice.supplierinvoice[a];
        var invoiceId = invdata.INVOICEID;
        invdata.lines = Lines[invoiceId];
        invdata.vats = Vats[invoiceId];
        var resp = SyncSupplierInvoice(invdata.INVOICEID, invdata);
        anybad = anybad || resp.error;
    }
    return anybad;
}
