////////////////////////////////////////////////////////////////////////////////
// Hook for dbs | invoice
// => Hooks for insert and update of invoice documents
// File-Encoding: UTF-8 without BOM( Test: ü,ä,ö )
//------------------------------------------------------------------------------
// Created/Edited       | Description
//------------------------------------------------------------------------------
// 08.2017              | dbs | invoice workflow 1.1.0
////////////////////////////////////////////////////////////////////////////////

//------------------------------------------------------------------------------
// InsertEntry10_dbsInvoice
/*------------------------------------------------------------------------------
// docType Invoice: 
//   - get creditor master data
//   - check of duplicates
//   - default value 'today' for capture date and delivery date
// docType Invoice Attachment:
//  [ - copy attributes of vendor transaction folder ( is configured in d.3 administration! )]
//------------------------------------------------------------------------------
*/
proc InsertEntry10_dbsInvoice( pUser, pDocTypeShort )
{
	call api_log( gLOGLEVEL, "Start of InsertEntry10_dbsInvoice( :pUser, :pDocTypeShort )" )
	vars lReturnValue = 0

	// when doctype short is equal invoice
	if ( pDocTypeShort == gDTS_INVOICE )
	{
      // get meta data from ERP-System (will only called if modified in 11_defintions_dbs_invoice.jpl)
      lReturnValue = getMetaDataFromERP()
      if( lReturnValue != 0 )
      {
         return lReturnValue
      }
   
		// update / validate creditor master data
      call updateCreditorData( "" )
		 
		// determine if check of duplicates is required
		if ( gGMF_CHECK_DUPLICATES == "1" )
		{
			vars lYear = dok_dat_feld[ gDDF_INVOICE_DATE ](7,4) // Format in d.3 always is '%0d.%0m.%4y %0h:%0M:%0s' or '%0d.%0m.%4y'
         
			if ( dok_dat_feld[ gDDF_CONTACT_ID ] != "" &&  dok_dat_feld[ gDDF_INVOICE_ID ] != "" && lYear != "" )
			{
				lReturnValue = checkDuplicates( dok_dat_feld[ gDDF_CONTACT_ID ], dok_dat_feld[ gDDF_INVOICE_ID ], lYear, "" )

				if ( lReturnValue != 0 )
				{
					return lReturnValue
				}			
			}
			else
			{
				call api_log_info("missing mandatory fields for checkDuplicates")
			}		
		}
		
		// determine if capture date is empty
		if ( dok_dat_feld[ gDDF_CAPTURE_DATE ] == "" )
		{
			// default = today -> Format in d.3 always is '%0d.%0m.%4y %0h:%0M:%0s' or '%0d.%0m.%4y'
			dok_dat_feld[ gDDF_CAPTURE_DATE ] = sm_sdtime(" %0d.%0m.%4y") 
		}
      
      // determine if delivery date is empty
		if ( dok_dat_feld[ gDDF_DELIVERY_DATE ] == "" )
		{
			// default = today -> Format in d.3 always is '%0d.%0m.%4y %0h:%0M:%0s' or '%0d.%0m.%4y'
			dok_dat_feld[ gDDF_DELIVERY_DATE ] = sm_sdtime(" %0d.%0m.%4y")
		}
		
		// determine if status is empty
		if ( dok_dat_feld[ gDDF_WFL_STATUS ] == "" && dok_dat_feld[ gDDF_STORAGE ] == gSTORAGE_WORKFLOW )
		{
			// default = gWFL_STATUS_NEW
			dok_dat_feld[ gDDF_WFL_STATUS ] = gWFL_STATUS_NEW
		}		
		
		// DIW-211	
		vars lTaxValue, lCounter, lArrayLength, lTaxIDMasterData, lSchemeClause
		vars lIsString, lWhereClause
		
		//add scheme to from clause if set
		if(gGMF_SCHEME_NAME_RUN_TIME != "")
		{
			lSchemeClause = ":(gGMF_SCHEME_NAME_RUN_TIME)."
		}
		else
		{
			lSchemeClause = ""
		}
		
		lArrayLength = sm_n_num_occurs("dok_dat_feld_:gDDF_TAX_KEY")
		for lCounter = 1 while ( lCounter <= lArrayLength ) step 1
        {
            lTaxValue = dok_dat_feld_:(gDDF_TAX_KEY)[ lCounter ]
			if( lTaxValue != "" )
			{
				lIsString = lTaxValue * 1			
				// check if lTaxValue is string or number
				if( lIsString != lTaxValue ) 
				{
					lWhereClause = "id = :+lTaxValue"
				}
				else
				{
					lWhereClause = "value = :lTaxValue OR id = :+lTaxValue"
				}
								
				DBMS ALIAS lTaxIDMasterData
				DBMS SQL SELECT TOP 1 id FROM :(lSchemeClause):(gGMF_TABLE_TAX_KEY) \                    
					   WHERE :lWhereClause
				DBMS ALIAS
				
				if( lTaxIDMasterData != "" )
				{
					dok_dat_feld_:(gDDF_TAX_KEY)[ lCounter ] = lTaxIDMasterData
				}
			}
        }
		// ende DIW-211
	}
   else if ( pDocTypeShort == gDTS_INVOICE_ATTACHMENT )
   {
      // update / validate creditor master data
      call updateCreditorData( "" )
   }
	
	call api_log( gLOGLEVEL, "End of InsertEntry10_dbsInvoice" )
   
   return 0
} //end of InsertEntry10_dbsInvoice

//------------------------------------------------------------------------------
// InsertExit30_dbsInvoice
/*------------------------------------------------------------------------------
// docType Invoice: 
//  - generation of transaction id
// docType Invoice Attachment:
//  [ - link document with vendor transaction folder ( is configured in d.3 administration! no overwrite of existing documents )]
//  - generation of transaction id
//------------------------------------------------------------------------------
*/
proc InsertExit30_dbsInvoice( pDocId, pFileDestination, pImportOk, pUser, pDocTypeShort )
{
	call api_log( gLOGLEVEL, "Start of InsertExit30_dbsInvoice( :pUser, :pFileDestination, :pImportOk, :pUser, :pDocTypeShort )" )
	vars lReturnValue, lCount
   
	// generation of transaction id required? is invoice? transaction id empty?
	if( pDocTypeShort == gDTS_INVOICE )  
	{
      //vars lNewTransactionId
      // set newly generated transaction id to current document if generation of transaction id is configured
      //lNewTransactionId = updateTransactionID( pDocId, pDocTypeShort )
      call updateTransactionID( pDocId, pDocTypeShort )
      
      // find matching other documents and fill them with generated transaction id
      // STEPS: 1. find all documents with current GUID, 2. fill all documents with current GUID with generated transaction id      
      
      // 1. find all documents with current GUID     
      // delete API-Context
      call api_clear_document_context()
      
      // set search criteria
      api_doc_type_short = gDTS_INVOICE_ATTACHMENT
      
      if(dok_dat_feld[ gDDF_GUID ] != "")
      {
         api_doc_field[ gDDF_GUID ] = dok_dat_feld[ gDDF_GUID ]
      
         // execute function document_find_ids
         lReturnValue = api_function ("document_find_ids", "")
         if (lReturnValue == 0)
         {
            vars lFoundDocumentIds = api_single_info
            api_single_info = ""
         
            // 2. fill all documents with current GUID with new transaction id
            // run through all document ids with current GUID
            for lCount = 1 while lCount <= lFoundDocumentIds step 1
            {
               // in case of updating transaction id: stop hook execution
               SERVER_API_NO_HOOKS = 1
               //call api_function( "attribute_update_single", gDDF_TRANSACTION_ID, lNewTransactionId, 0, api_doc_ids[lCount], "Master" )
               call api_function( "attribute_update_single", gDDF_TRANSACTION_ID, dok_dat_feld[ gDDF_TRANSACTION_ID ], 0, api_doc_ids[lCount], "Master" )              
               SERVER_API_NO_HOOKS = 0
            }
         }         
         else
         {
            call api_log_error("Error code :lReturnValue for document_find_ids in InsertExit30_dbsInvoice!")
         }
      }
      
      // create record in erp and start workflow (will only called if modified in 51_erp_dbs_rechnungsworkflow.jpl)
      lReturnValue = createRecordInERP( pDocId )
      
      if( lReturnValue != 0 )
      {
         return lReturnValue
      }
	}
   else
   {
      // find matching other documents and fill them with transaction id
      // STEPS: 1. find all documents with current GUID, 2. find valid transaction id for GUID, 3. fill current document with valid transaction id
      if ( pDocTypeShort == gDTS_INVOICE_ATTACHMENT && dok_dat_feld[ gDDF_TRANSACTION_ID ] == "" )
      {
         vars lReturnValue // errorcode
         vars lCount // counter
         vars lTransactionId = ""
         // delete API-Context
         call api_clear_document_context()
         
         // 1. find all documents with current GUID
         // set search criteria
         api_doc_type_short = gDTS_INVOICE
         api_doc_field[ gDDF_GUID ] = dok_dat_feld[ gDDF_GUID ]
         
         // execute function document_find_ids
         lReturnValue = api_function ("document_find_ids", "")
         
         // 2. find valid transaction id for GUID
         // run through all document ids with current GUID
         if (lReturnValue == 0)
         {
            vars lFoundDocumentIds = api_single_info
            api_single_info = ""
            
            call api_log_info(":lFoundDocumentIds Document-IDs for current GUID have been found!")
            
            for lCount = 1 while lCount <= lFoundDocumentIds step 1
            {
               // call api_log_info("doc_id :lCount: :api_doc_ids[lCount]")
               lReturnValue = api_function( "attribute_get_single", gDDF_TRANSACTION_ID, 0, api_doc_ids[lCount], "Master" )
               if( lReturnValue == 0 && api_single_info != "" ) 
               {
                  lTransactionId = api_single_info
                  break
               }
            }
            
            // 3. fill document with valid transaction id
            if( lTransactionId != "" ) 
            {
               // run through all document ids with current GUID
               // in case of updating transaction: stop hook execution
               SERVER_API_NO_HOOKS = 1
               call api_function( "attribute_update_single", gDDF_TRANSACTION_ID, lTransactionId, 0, pDocId, "Master" )
               SERVER_API_NO_HOOKS = 0
            }
         }
         else
         {
            call api_log_error("Error code :lReturnValue for document_find_ids in InsertExit30_dbsInvoice!")
         }
      }
   }
		
	call api_log( gLOGLEVEL, "End of InsertExit30_dbsInvoice" )
   
   return 0
} //end of InsertExit30_dbsInvoice


//------------------------------------------------------------------------------
// LinkExit10_dbsInvoice
/*------------------------------------------------------------------------------
// docType Invoice and Attachment: 
//   - copy multval attributes to all corresponding invoice attachments 
//   - set net_amount, gross_amount and tax_amount always to 0 when values equal null
//------------------------------------------------------------------------------
*/
proc LinkExit10_dbsInvoice( pDocIdFather, pDocIdChild, pErrorCode, pErrorNumber )
{
   call api_log( gLOGLEVEL, "Start of LinkExit10_dbsInvoice( :pDocIdFather, :pDocIdChild, :pErrorCode, :pErrorNumber )" )
   call inheritImpCrdTrsFldAttr( pDocIdFather, pDocIdChild )
   call api_log( gLOGLEVEL, "End of LinkExit10_dbsInvoice" )
}

//------------------------------------------------------------------------------
// UpdateAttribExit20_dbsInvoice
/*------------------------------------------------------------------------------
// docType Invoice: 
//   - copy multval attributes to all corresponding invoice attachments 
//   - set net_amount, gross_amount and tax_amount always to 0 when values equal null
//------------------------------------------------------------------------------
*/
proc UpdAttribExit20_dbsInvoice( pDocId, pErrorNumber, pUser, pDocTypeShort )
{
	call api_log( gLOGLEVEL, "Start of UpdAttribExit20_dbsInvoice( :pDocId, :pErrorNumber, :pUser, :pDocTypeShort, :dokuart_kurz )" )
	   
	// Update successfull ?
	if ( pErrorNumber == 0 )
	{  	
		if ( dokuart_kurz == gDTS_INVOICE )
		{
         // inherit creditor transaction folder attributes
			call inheritCrdTrsFldAttributes( pDocId, dokuart_kurz, "" )
         // update creditor master data
         call updateCreditorData( pDocId ) // not necessary anymore, only write creditor data in import
		}
	}
	call api_log( gLOGLEVEL, "End of UpdAttribExit20_dbsInvoice" )
   
   return 0
}// end  of UpdAttribExit20_dbsInvoice