def setHeader(self, xml, document): self._logger.info('Setting header...') document.setSender( self.getText(xml, self._properties.getProperty('bpPathSender'))) document.setDateFrom( self.parseDate( self.getText(xml, self._properties.getProperty('bpPathDateFrom')))) document.setDateTo( self.parseDate( self.getText(xml, self._properties.getProperty('bpPathDateTo')))) document.setAccountNumber( self.getText(xml, self._properties.getProperty('bpPathAccountNumber'))) document.setExtractNumber( self.getText(xml, self._properties.getProperty('bpPathExtractNumber'))) document.setIncome( BigDecimal( self.getText(xml, self._properties.getProperty('bpPathIncome')))) document.setSpending( BigDecimal( self.getText(xml, self._properties.getProperty('bpPathSpending')))) document.setPositionCounter( int( self.getText( xml, self._properties.getProperty('bpPathPositionCounter')))) self.saveDocument(document)
def test_arithmetic_error(self): try: from java.math import BigDecimal d = BigDecimal(3.14159) zero = BigDecimal(0.0) x = d.divide(zero) except ArithmeticError as ex: pass
def getStartBalance(self): balance = BigDecimal(0) for zpk in self._possession.getZpks(): balance = balance.add( BigDecimal(zpk.getCurrentBalance().getStartCredit() - zpk.getCurrentBalance().getStartDebit()).setScale( 2, RoundingMode.HALF_UP)) return balance
def calculateValue(self, document): value = BigDecimal(0) for position in document.getPositions(): if document.getType() == "CHARGING": value = value.add(position.getValue().multiply(BigDecimal(-1))) else: value = value.add(position.getValue()) return value
def test_arithmetic_error(self): try: from java.math import BigDecimal d = BigDecimal(3.14159) zero = BigDecimal(0.0) x = d.divide(zero) except ArithmeticError as ex: pass
def calculateValue(self, invoice): value = BigDecimal(0.0) for position in invoice.getPositions(): if position.getType( ) == "INVOICE_COST" and not position.isCanceled(): value = value.add(position.getValue().setScale( 2, RoundingMode.HALF_UP)) invoice.putAttribute( "VALUE", str(value.setScale(2, RoundingMode.HALF_UP).floatValue()))
def calculate(self, zpk, statusDate): balance = zpk.getCurrentBalance() calculatedDebit = (self.sumDebit(zpk.getId(), statusDate).add( BigDecimal(balance.getStartDebit()))).setScale( 2, RoundingMode.HALF_UP) calculatedCredit = (self.sumCredit(zpk.getId(), statusDate).add( BigDecimal(balance.getStartCredit()))).setScale( 2, RoundingMode.HALF_UP) return calculatedDebit, calculatedCredit
def calculateValueNet(self, volume, unitPrice): try: bdVolume = BigDecimal(volume).setScale(2, RoundingMode.HALF_UP) bdUnitPrice = BigDecimal(unitPrice).setScale( 2, RoundingMode.HALF_UP) return str( bdVolume.multiply(bdUnitPrice).setScale( 2, RoundingMode.HALF_UP).floatValue()) except: return '0'
def obtainData(self): self._community = self.findById("Community", self._svars.get('communityId')) self._possession = self.findById("Possession", self._svars.get('possessionId')) self._total = BigDecimal(0) self._items = self.collectItems() self._paymentStartDate = self.getPaymentStartDate() self._chargingAccount = self.getChargingAccount() self._rfAccount = self.getRFAccount()
def testSumOfDecimal(self): t = tWithDecimalCursor(self.context) v = viewWithDecimalCursor(self.context) t.insert() t.insert() v.first() self.assertEquals(BigDecimal('48.02'), v.f1.stripTrailingZeros()) self.assertEquals(BigDecimal('2.0002'), v.f2.stripTrailingZeros()) self.assertEquals(BigDecimal('50.0202'), v.f12.stripTrailingZeros())
def parse_example_target(self, target): parsed = self.parse_entity_id(target) if parsed: return Datamodel.makeWikidataItemIdValue(parsed) r = re.compile('[± ]+') if self.datatype == 'quantity' or self.datatype == 'number': # First remove any spurious spaces or commas spurious_space_comma_re = re.compile('[ ,](\d\d\d)') target = spurious_space_comma_re.sub(r'\1', target) try: parts = [p.strip() for p in r.split(target) if p.strip()] print(parts) if parts[-1].startswith('[') and parts[-1].endswith(']'): parts = parts[:-1] amount = BigDecimal(parts[0]) precision = 0 unit = "" if len(parts) > 1: unit_qid = self.parse_entity_id(parts[-1]) if unit_qid: unit = Datamodel.makeWikidataItemIdValue( unit_qid).getIri() try: precision = BigDecimal(parts[1]) except NumberFormatException: pass if precision: return Datamodel.makeQuantityValue( amount, amount.subtract(precision), amount.add(precision), unit) else: return Datamodel.makeQuantityValue(amount, unit) except NumberFormatException as e: print(e) target = target.strip() if target.startswith('<code>') and target.endswith('</code>'): target = target[len('<code>'):-len('</code>')] if target.startswith('['): wiki = mwparserfromhell.parse(target) for extlink in wiki.filter_external_links(): return Datamodel.makeStringValue(unicode( extlink.title.strip())) if target.startswith('"') and target.endswith( '"') and self.datatype == 'string': return Datamodel.makeStringValue(target[1:-1]) elif self.datatype == 'string' or self.datatype == 'external-id': return Datamodel.makeStringValue(target.strip())
def recalculateShares(self, community): totalArea = BigDecimal(0) percent = BigDecimal(100) for possession in community.getPossessions(): totalArea = totalArea.add(possession.getArea()) self._logger.info("Total area of community %s calculated as %f" % (community.getName(), totalArea.floatValue())) for possession in community.getPossessions(): tmpPossessionArea = possession.getArea().divide( totalArea, 6, RoundingMode.HALF_UP) possessionArea = tmpPossessionArea.multiply(percent) self._logger.info( "Possession area for %d calculated as %f" % (possession.getId(), possessionArea.floatValue())) possession.setShare(possessionArea)
def bookPosition(self, position): if not position.isCanceled() and not position.isBooked( ) and position.getCreditZpk() != None and position.getDebitZpk( ) != None: debitBalance = position.getDebitZpk().getCurrentBalance() creditBalance = position.getCreditZpk().getCurrentBalance() debitBalance.setDebit(position.getValue().add( BigDecimal(debitBalance.getDebit())).floatValue()) creditBalance.setCredit(position.getValue().add( BigDecimal(creditBalance.getCredit())).floatValue()) position.setBooked(True) position.setBookedAt(Date()) self.saveEntity(debitBalance) self.saveEntity(creditBalance) self.savePosition(position)
def test_decimal(self): c = tWithDecimalCursor(self.context) c.insert() c.first() self.assertEquals(BigDecimal('5.2'), c.cost.stripTrailingZeros()) c.cost = BigDecimal('5.289') c.update() c.first() self.assertEquals(BigDecimal('5.29'), c.cost.stripTrailingZeros()) c.cost = BigDecimal('123.2') update = lambda: c.update() self.assertThrows(CelestaException, update)
def sumDebit(self, zpkId): sql = "Select sum(e.value) From DocumentPosition e Where e.debitZpk.id = %d and e.booked = 1 and e.bookingPeriod.defaultPeriod = 1" % zpkId result = self._entityManager.createQuery(sql).getSingleResult() if result == None: return BigDecimal(0) else: return result
def mapDecimal(self, propertyName, validators, mappedEntity=None): if mappedEntity == None: mappedEntity = self._entity for validator in validators: validator.validate(self._svars.get(propertyName)) methodName = "set" + propertyName[0].upper() + propertyName[1:] getattr(mappedEntity, methodName)(BigDecimal(self._svars.get(propertyName)))
def collectItems(self): output = [] elements = self._possession.getElements() elements = sorted( elements, key=lambda item: item.getGroup().getValue() + item.getName()) lastGroupId = elements[0].getGroup().getId() groupTotal = BigDecimal(0) groupItems = 0 for element in elements: if element.getGroup().getId() != lastGroupId: if groupItems > 1: self.createTotalLine(output, groupTotal) groupTotal = BigDecimal(0) self.createEmptyLine(output) groupItems = 0 lastGroupId = element.getGroup().getId() groupTotal = BigDecimal(0) item = dict([]) item['group'] = element.getGroup().getValue() item['element'] = element.getName() value = self.calculateValue(element) item['value'] = value groupTotal = groupTotal.add(value) self._total = self._total.add(value) groupItems += 1 output.append(item) self.createTotalLine(output, groupTotal) self.createEmptyLine(output) self.createTotalLine(output, self._total) return output
def sumDebit(self, zpkId, statusDate): date = SimpleDateFormat('dd-MM-yyyy').parse(statusDate) sql = "Select sum(e.value) From DocumentPosition e Where e.debitZpk.id = :debitId and e.booked = 1 and e.bookingPeriod.defaultPeriod = 1 and e.createdAt <= :date" query = self._entityManager.createQuery(sql) query.setParameter("debitId", zpkId) query.setParameter("date", date, TemporalType.DATE) result = query.getSingleResult() if result == None: return BigDecimal(0) else: return result
def setPositions(self, xml, document): self._logger.info('Setting positions...') for xmlPosition in self.getChildren( xml, self._properties.getProperty('bpPathPositions')): position = IncomingPaymentDocumentPosition() position.setPositionNo( int( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionPositionNo')))) position.setIncome( BigDecimal( self.getText( xmlPosition, self._properties.getProperty('bpPathPositionIncome')))) position.setClientNumber( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionClientNumber'))) position.setRequestDate( self.parseDate( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionRequestDate')))) position.setBookingDate( self.parseDate( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionBookingDate')))) position.setTitle( self.getText( xmlPosition, self._properties.getProperty('bpPathPositionTitle'))) position.setClientName( self.getText( xmlPosition, self._properties.getProperty('bpPathPositionClientName'))) position.setClientAddress( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionClientAddress'))) position.setClientAccountNumber( self.getText( xmlPosition, self._properties.getProperty( 'bpPathPositionClientAccountNumber'))) position.setDocument(document) position.setStatus(self.getStatus()) self.saveDocument(position)
def testBigDecimalConvertedToDouble(self): """testing value of BigDecimal when converted to double""" assert self.has_table("floattable"), "missing attribute floattable" from java.math import BigDecimal values = [ BigDecimal(x).setScale(2, BigDecimal.ROUND_UP) for x in [4.22, 123.44, 292.09, 33.2, 102.00, 445] ] self._test_precision(self.table("floattable"), lambda x, y: x - y.doubleValue(), values, "doubleValue")
def checkIfPayed(self, invoice): costs = BigDecimal(0.0) payments = BigDecimal(0.0) for position in invoice.getPositions(): if position.getType( ) == "INVOICE_COST" and not position.isCanceled(): costs = costs.add(position.getValue()) elif position.getType( ) == "INVOICE_PAYMENT" and not position.isCanceled(): payments = payments.add(position.getValue()) if costs.equals(payments): self._logger.info("Costs equals payments, marking as payed...") invoice.putAttribute("PAYED", 'true') else: self._logger.info( "Costs(%f) doesn't equal payments(%f), marking as unpayed..." % (costs.floatValue(), payments.floatValue())) invoice.putAttribute("PAYED", 'false')
def testBigDecimal(self): """testing value of BigDecimal""" assert self.has_table("floattable"), "missing attribute floattable" from java.math import BigDecimal values = [ BigDecimal(x).setScale(2, BigDecimal.ROUND_UP) for x in [4.22, 123.44, 292.09, 33.2, 102.00, 445] ] self._test_precision( self.table("floattable"), lambda x, y, b=BigDecimal: b(x).subtract(y).doubleValue(), values, "doubleValue")
def testSumOfDecimal(self): t = t3Cursor(self.context) t.insert() t.f2 = BigDecimal('0.0001') t.insert() pv = pView4Cursor(self.context, BigDecimal('1.00001')) pv.first() self.assertEquals(BigDecimal('24.01'), pv.f1.stripTrailingZeros()) self.assertEquals(BigDecimal('1.0001'), pv.f2.stripTrailingZeros()) self.assertEquals(BigDecimal('25.0101'), pv.f12.stripTrailingZeros()) pv = pView4Cursor(self.context, BigDecimal('0.00001')) pv.first() self.assertEquals(BigDecimal('48.02'), pv.f1.stripTrailingZeros()) self.assertEquals(BigDecimal('1.0002'), pv.f2.stripTrailingZeros()) self.assertEquals(BigDecimal('49.0202'), pv.f12.stripTrailingZeros())
def checkZpk(self, zpk): balance = zpk.getCurrentBalance() calculatedCredit = (self.sumCredit(zpk.getId()).add( BigDecimal(balance.getStartCredit()))).setScale( 2, RoundingMode.HALF_UP) calculatedDebit = (self.sumDebit(zpk.getId()).add( BigDecimal(balance.getStartDebit()))).setScale( 2, RoundingMode.HALF_UP) expectedCredit = BigDecimal(balance.getCredit()).setScale( 2, RoundingMode.HALF_UP) expectedDebit = BigDecimal(balance.getDebit()).setScale( 2, RoundingMode.HALF_UP) if not expectedCredit.equals(calculatedCredit): self._logger.info("On zpk %d found wrongly calculated credit:" % zpk.getId()) self._logger.info("calculated: %s" % calculatedCredit.toPlainString()) self._logger.info("expected: %s" % expectedCredit.toPlainString()) if not expectedDebit.equals(calculatedDebit): self._logger.info("On zpk %d found wrongly calculated debit:" % zpk.getId()) self._logger.info("calculated: %s" % calculatedDebit.toPlainString()) self._logger.info("expected: %s" % expectedDebit.toPlainString())
def calculateValueGross(self, valueNet, taxId): try: tax = self.findById("Dictionary", taxId) bdValueNet = BigDecimal(valueNet) bdTax = BigDecimal(tax.getKey()) return bdValueNet.add( bdValueNet.multiply(bdTax).setScale( 2, RoundingMode.HALF_UP)).setScale(2, RoundingMode.HALF_UP) except: return BigDecimal(0)
def handleOverpayment(self): if self._svars.get('overpayedValue') != '' and float( self._svars.get('overpayedValue')) > 0: howTo = self.findById("Dictionary", self._svars.get('overpayedId')) if howTo != None and howTo.getKey() == "RENT": value = BigDecimal(self._svars.get('rentValue')).add( BigDecimal(self._svars.get('overpayedValue'))).setScale( 2, RoundingMode.HALF_UP) self._svars.put('rentValue', value.toString()) elif howTo != None: value = BigDecimal(self._svars.get('rfValue')).add( BigDecimal(self._svars.get('overpayedValue'))).setScale( 2, RoundingMode.HALF_UP) self._svars.put('rfValue', value.toString()) else: raise ValidationError( self.findBy('Label', 'name', "'validators.document.payment.overpayment'"). getMessage())
def testSumOfDecimal(self): t = table5Cursor(self.context) mv = mView6Cursor(self.context) t.insert() t.insert() t.f1 = BigDecimal('24.02') t.insert() mv.first() self.assertEquals(BigDecimal('24.01'), mv.f1) self.assertEquals(BigDecimal('48.02'), mv.s1) self.assertEquals(BigDecimal('2.0002'), mv.s2) mv.next() self.assertEquals(BigDecimal('24.02'), mv.f1) self.assertEquals(BigDecimal('24.02'), mv.s1) self.assertEquals(BigDecimal('1.0001'), mv.s2)
def initPosition(self, document, prefix=''): position = DocumentPosition() position.setCreatedAt(Date()) position.setType(document.getType() + "_POSITION") position.setBookingPeriod( BookingPeriodManager().findDefaultBookingPeriod()) position.setMonth(BookingPeriodManager().getCurrentMonth().getValue()) value = self.parseFloat(self._svars.get(prefix + 'value')) position.setValue(BigDecimal(value).setScale(2, RoundingMode.HALF_UP)) position.setDescription(self._svars.get(prefix + 'positionDescription')) if self._svars.get(prefix + 'accountId') != None and int( self._svars.get(prefix + 'accountId')) > 0: position.setAccount( self.findById("Account", int(self._svars.get(prefix + 'accountId')))) else: self._logger.info( "Position doesn't have accountID set under key %s" % (prefix + 'accountId')) self._logger.info( "New document position of type %s created(%f)" % (position.getType(), position.getValue().floatValue())) return position
def __javaServiceMethodProxy(component, request, method, method_name, input, params, http_method): """ Calls service methods in Java components. Prepares parameters, converts exceptions and results. """ if request: request.setNativeMode() # We remove the resource creation time parameters from the map and # assign them directly to the component as new attributes. After that, # the pruned parameter map can be passed as keyword arg dict to the # service method. for name in component.componentDescriptor.getParamMap().keySet(): if name in params: if type(component.componentDescriptor.getParamMap().get( name)) is ParameterDefNumber: # Why do we have this? The default type for numeric parameters is # BigDecimal. We can't just assign a float (or other numeric value) # to a BigDecimal variable. Instead, we need to create a new # instance of that type explicitly. setattr(component, name, BigDecimal(params[name])) else: setattr(component, name, params[name]) del params[name] try: param_order = component.getParameterOrder()[method_name] param_types = component.getParameterTypes()[method_name] # Assemble the list of additional service method parameters. We need # to perform a case, so we combine the type list and parameter name list, # index the parameter map and perform the cast all in one swoop. if param_order and param_types: # Yes, the following CAN be written as a single line with list comprehension, # but then the 'reader comprehension' suffers. So, I wrote it out explicitly. arglist = list() for param_type, name in zip(param_types, param_order): param_value = params[name] if param_type != type(param_value): # Some type conversion is required arglist.append(param_type(param_value)) else: # Type is already in the right argument (often the case when a default # value was specified). arglist.append(param_value) else: arglist = list() # Importing at this odd place here avoids circular imports in other places from resource_accessor import ResourceAccessor # Provide a conversion methods specific to this component's language. # Passing them to ResourceAccessor means that I don't have to import those # symbols in the resource_accessor module. component.resourceAccessor = ResourceAccessor(__javaStructToPython, __pythonStructToJava) res = method(http_method, String(input if input is not None else ""), *arglist) except RestxException, e: raise e
def export(fdmAPI, fdmContext): #************************************************************************************ #Build query to get max custom dims #************************************************************************************ def getMaxCustomDims(appID): #return "SELECT COUNT(BALANCE_COLUMN_NAME) FROM AIF_TARGET_APPL_DIMENSIONS WHERE APPLICATION_ID = ? AND BALANCE_COLUMN_NAME IS NOT NULL AND BALANCE_COLUMN_NAME LIKE 'UD%' AND TARGET_DIMENSION_CLASS_NAME <> 'LOOKUP'" return "SELECT COUNT(BALANCE_COLUMN_NAME) FROM AIF_TARGET_APPL_DIMENSIONS WHERE APPLICATION_ID = " + appID + " AND BALANCE_COLUMN_NAME IS NOT NULL AND BALANCE_COLUMN_NAME LIKE 'UD%' AND TARGET_DIMENSION_CLASS_NAME <> 'LOOKUP'" def generateFXRatesLoadFile(loadID, strFile, hfmAPI, fdmAPI, fxEntity, beginAccount, endAccount, averageAccount): import codecs import os colName = "" DELIM = ";" objFile = codecs.open(strFile, "a", "UTF-16_LE") if fxEntity == "IsEmpty": objFile.write("!Entity = [None]" + os.linesep) objFile.write("!Value = [None]" + os.linesep) else: objFile.write("!Entity = " + fxEntity + os.linesep) #************************************************************************************ #Get the location's DataValue #************************************************************************************ rs = fdmAPI.getLocationDetails( BigDecimal(str(fdmContext["LOCKEY"]))) while (rs.next()): strDataValue = rs.getString("PARTDATAVALUE") #If data value is not set default to <entity currency> if strDataValue == None: strDataValue = "<entity currency>" Position = strDataValue.find(DELIM) if Position > 0: strDataValue = strDataValue[:Position] objFile.write("!Value = " + strDataValue + os.linesep) #************************************************************************************ objFile.write("!ICP = [ICP None]" + os.linesep) objFile.write("!VIEW = YTD" + os.linesep) try: rs = hfmAPI.getActiveTargetDims(False) while (rs.next()): colName = rs.getString("TDATASEG_COLUMN") if colName.startswith("UD"): if colName != "UD1" and colName != "UD2": objFile.write("!" + rs.getString("DIMENSION_NAME")) objFile.write(" = [None]") objFile.write(os.linesep) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) objFile.close return False objFile.write(os.linesep) objFile.write("!Data" + os.linesep) try: fxSQL = "SELECT (SELECT A.CATNAME FROM TPOVCATEGORY A INNER JOIN AIF_BAL_RULE_LOADS B ON A.CATKEY = B.CATKEY WHERE B.LOADID = " + loadID + ") as CATNAME, EPM_YEAR, EPM_PERIOD, FROM_CURRENCY, TO_CURRENCY, RATE_TYPE, CONVERSION_RATE FROM AIF_HS_EXCHANGE_RATES WHERE LOADID = " + loadID + " ORDER BY RATE_TYPE" rs = fdmAPI.executeQuery(fxSQL, None) while (rs.next()): objFile.write(rs.getString("CATNAME") + DELIM) objFile.write(rs.getString("EPM_YEAR") + DELIM) objFile.write(rs.getString("EPM_PERIOD") + DELIM) if rs.getString("RATE_TYPE") == "BEGIN": objFile.write(beginAccount + DELIM) elif rs.getString("RATE_TYPE") == "END": objFile.write(endAccount + DELIM) elif rs.getString("RATE_TYPE") == "AVERAGE": objFile.write(averageAccount + DELIM) objFile.write(rs.getString("FROM_CURRENCY") + DELIM) objFile.write(rs.getString("TO_CURRENCY") + DELIM) objFile.write(str(rs.getBigDecimal("CONVERSION_RATE", 38))) objFile.write(os.linesep) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(fxSQL).encode("utf-8")) objFile.close return False objFile.close return True def exportICP(fileName, rs, fdmCustoms): import codecs import os #CONSTANTS DELIM = ";" if rs == None: return False objFile = codecs.open(strFile, "a", "UTF-16_LE") objFile.write("!InterCompany Detail" + os.linesep) objFile.write("!Column_Order = ") objFile.write("Entity" + DELIM) objFile.write("Partner" + DELIM) objFile.write("Account" + DELIM) objFile.write("C1" + DELIM) objFile.write("C2" + DELIM) x = 1 while x <= fdmCustoms: objFile.write("C" + str((x + 2)) + DELIM) x += 1 objFile.write("TransID" + DELIM) objFile.write("SubID" + DELIM) objFile.write("RefID" + DELIM) objFile.write("Date" + DELIM) objFile.write("EntCurrAmt" + DELIM) objFile.write("TransCurr" + DELIM) objFile.write("Rate" + DELIM) objFile.write("Comment1" + DELIM) objFile.write("TransAmt" + os.linesep) currentScenario = "" scenario = "" currentYear = "" year = "" currentPeriod = "" period = "" while (rs.next()): currentScenario = rs.getString("SCENARIO") if currentScenario != scenario: objFile.write("!Scenario=" + currentScenario + os.linesep) currentYear = rs.getString("YEAR") if currentYear != year: objFile.write("!Year=" + currentYear + os.linesep) currentPeriod = rs.getString("PERIOD") if currentPeriod != period: objFile.write("!Period=" + currentPeriod + os.linesep) objFile.write(rs.getString("ENTITY") + DELIM) objFile.write(rs.getString("ICP") + DELIM) objFile.write(rs.getString("ACCOUNT") + DELIM) objFile.write(rs.getString("UD1") + DELIM) objFile.write(rs.getString("UD2") + DELIM) x = 1 while x <= fdmCustoms: objFile.write(rs.getString("UD" + str((x + 2))) + DELIM) x += 1 #TransID if rs.getString("ATTR1") != None: objFile.write(rs.getString("ATTR1") + DELIM) else: objFile.write(DELIM) #SubID if rs.getString("ATTR2") != None: objFile.write(rs.getString("ATTR2") + DELIM) else: objFile.write(DELIM) #RefID if rs.getString("ATTR3") != None: objFile.write(rs.getString("ATTR3") + DELIM) else: objFile.write(DELIM) #Date if rs.getString("ATTR4") != None: objFile.write(rs.getString("ATTR4") + DELIM) else: #date is required objFile.write('12/31/2014;') #EntCurrAmt if rs.getString("ATTR5") != None: objFile.write(rs.getString("ATTR5") + DELIM) else: objFile.write(DELIM) #TransCurr if rs.getString("ATTR6") != None: objFile.write(rs.getString("ATTR6") + DELIM) else: objFile.write(DELIM) #Rate if rs.getString("ATTR7") != None: objFile.write(rs.getString("ATTR7") + DELIM) else: objFile.write(DELIM) #Comment1 if rs.getString("ATTR11") != None: objFile.write(rs.getString("ATTR11") + DELIM) else: objFile.write(DELIM) #TransAmt objFile.write(rs.getString("AMOUNT") + os.linesep) scenario = currentScenario year = currentYear period = currentPeriod objFile.close() return True #************************************************************************************ #End of Utility Methods #************************************************************************************ #************************************************************************************ #EXPORT ACTION #************************************************************************************ #************************************************************************************ #Import Required Libraries #************************************************************************************ import sys import os import codecs import java.math.BigDecimal as BigDecimal import java.util.ArrayList as ArrayList import java.util.TreeMap as TreeMap import com.hyperion.aif.hfm.HfmAdapter as HfmAdapter import com.hyperion.aif.hfm.ProtectionData as ProtectionData #************************************************************************************ try: #instantiate adapter hfmAdapter = HfmAdapter() except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError("Could not instantiate the HfmAdapter.") return False userName = unicode(fdmContext["USERNAME"]) locale = unicode(fdmContext["USERLOCALE"]) if locale == "None": fdmAPI.logDebug("User Locale is not set. Defaulting to: en_US") locale = "en_US" else: fdmAPI.logDebug("User Locale is: " + locale) #************************************************************************************ #CONSTANTS #************************************************************************************ PROCESS_EXPORT = "PROCESS_BAL_EXP_HFM" PROCESS_RATES = "PROCESS_EXCHANGE_RATE_LOAD_HFM" PROCESS_RUNNING = "RUNNING" PROCESS_SUCCESS = "SUCCESS" PROCESS_FAILED = "FAILED" DELIM = ";" #************************************************************************************ #************************************************************************************ #generate path for .dat file #************************************************************************************ strFile = "%s\%s_%s.dat" % (fdmContext["OUTBOXDIR"], fdmContext["APPNAME"], str(fdmContext["LOADID"])) strFile = strFile.replace('\\', '/') strFile = os.path.normpath(strFile) #************************************************************************************ #************************************************************************************ #Initialize the adapter #************************************************************************************ try: hfmAdapter.init(fdmContext["LOADID"]) #Create an entry for the Process Details fdmAPI.insertIntoProcessDetails(PROCESS_EXPORT, fdmContext["APPNAME"], PROCESS_RUNNING) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() fdmAPI.insertIntoProcessDetails(PROCESS_EXPORT, fdmContext["APPNAME"], PROCESS_FAILED) return False #************************************************************************************ #Get HFM Cluster #************************************************************************************ try: fmCluster = hfmAdapter.getHfmCluster(userName) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fmCluster = "HFMCluster" #************************************************************************************ #************************************************************************************ #Get the Target System Options #************************************************************************************ try: #get adapter options rs = hfmAdapter.getAdapterOptionsForLoadID() TargetOptions = TreeMap() while (rs.next()): TargetOptions.put( rs.getString("PARAMETER_NAME").upper(), rs.getString("PROPERTY_VALUE")) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False #************************************************************************************ #************************************************************************************ #Check for Global Login ID #************************************************************************************ globalID = hfmAdapter.getGlobalUserID() fdmAPI.logDebug("Global User ID: " + str(globalID).encode("utf-8")) if globalID != "": userName = globalID #************************************************************************************ #************************************************************************************ #Connect to HFM #************************************************************************************ isConnectedForLineItems = False isConnectedForDataProtection = False #try: # isConnected = hfmAdapter.connect(userName, locale, fmCluster, unicode(fdmContext["TARGETAPPNAME"])) # if isConnected == False: # fdmAPI.logError("Failed to connect to:%s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) # fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) # hfmAdapter.close() # return False # else: # fdmAPI.logDebug("Connected to: %s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) #except: # fdmAPI.logError("Failed to connected to: %s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) # hfmAdapter.close() # return False #************************************************************************************ #************************************************************************************ #Get Max Custom Dimensions #************************************************************************************ try: #Get Max custom dims being loaded to target strSQL = getMaxCustomDims(str(fdmContext["APPID"])) rs = fdmAPI.executeQuery(strSQL, None) while (rs.next()): fdmCustoms = int(rs.getString(1)) - 2 except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(strSQL).encode("utf-8")) hfmAdapter.close() return False #************************************************************************************ #************************************************************************************ #Get the location's DataValue #************************************************************************************ rs = fdmAPI.getLocationDetails(BigDecimal(str(fdmContext["LOCKEY"]))) while (rs.next()): strDataValue = rs.getString("PARTDATAVALUE") #If data value is not set default to <entity currency> if strDataValue == None: strDataValue = "<entity currency>" #************************************************************************************ #************************************************************************************ #Check Journal Loading Options #************************************************************************************ Position = strDataValue.find(DELIM) if bool(int(TargetOptions.get("ENABLE_JOURNAL_LOAD"))) == True: if Position > 0: blnLoadAsJournals = True else: blnLoadAsJournals = False else: blnLoadAsJournals = False if Position > 0: strDataValue = strDataValue[:Position] if strDataValue.lower() in ("<entity curr adjs>", "<parent curr adjs>", "[contribution adjs]", "[parent adjs]"): if blnLoadAsJournals == False: #DataValue Requires Journal Loading, Set to false and load as entity currency blnDataAsJournal = False strDataValue = "<Entity Currency>" else: blnDataAsJournal = True else: blnDataAsJournal = False #************************************************************************************ #Default to True bolResult = True datFileCreated = False loadFXRates = False #************************************************************************************ #Check for FX Rate Load Option #************************************************************************************ try: strSQL = "Select LOAD_EXCHANGE_RATE_FLAG From AIF_BAL_RULE_LOADS WHERE LOADID = %s AND LOAD_EXCHANGE_RATE_FLAG IS NOT NULL" % str( fdmContext["LOADID"]) rs = fdmAPI.executeQuery(strSQL, None) while (rs.next()): loadFXRates = True except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(strSQL).encode("utf-8")) loadFXRates = False if loadFXRates == True: strFXRatesFile = "%s\%s_%s_FXRates.dat" % (fdmContext["OUTBOXDIR"], fdmContext["APPNAME"], str(fdmContext["LOADID"])) strFXRatesFile = strFXRatesFile.replace('\\', '/') strFXRatesFile = os.path.normpath(strFXRatesFile) #Get the Global Adapter Options - Only these contain the currency rate account options beginAccount = "[None]" endAccount = "[None]" averageAccount = "[None]" fxEntity = "IsEmpty" try: rs = hfmAdapter.getAdapterOptions() while (rs.next()): if rs.getString("LOOKUP_CODE") == "CURR_RATE_ACCT_BEGIN_RATE": if rs.getString("PROPERTY_VALUE") != None: beginAccount = rs.getString("PROPERTY_VALUE") elif rs.getString("LOOKUP_CODE") == "CURR_RATE_ACCT_END_RATE": if rs.getString("PROPERTY_VALUE") != None: endAccount = rs.getString("PROPERTY_VALUE") elif rs.getString("LOOKUP_CODE") == "CURR_RATE_ACCT_AVG_RATE": if rs.getString("PROPERTY_VALUE") != None: averageAccount = rs.getString("PROPERTY_VALUE") elif rs.getString("LOOKUP_CODE") == "CURR_RATE_ENTITY": if rs.getString("PROPERTY_VALUE") != None: fxEntity = rs.getString("PROPERTY_VALUE") except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False if (generateFXRatesLoadFile(str(fdmContext["LOADID"]), strFXRatesFile, hfmAdapter, fdmAPI, fxEntity, beginAccount, endAccount, averageAccount)) == False: fdmAPI.insertIntoProcessDetails(PROCESS_RATES, fdmContext["APPNAME"], PROCESS_FAILED) fdmAPI.logDebug("Export Exchange Rates failed.") else: fdmAPI.insertIntoProcessDetails(PROCESS_RATES, fdmContext["APPNAME"], PROCESS_RUNNING) #************************************************************************************ #Are we loading data as journal? If so, exit the Export script and enter the Load script #************************************************************************************ if blnDataAsJournal == True: #Check the journal numbering switch blnJournalIDPerEntity = bool( int(TargetOptions.get("ENABLE_JOURNAL_JVID_ENTITY"))) #Set the journal ID based on the numbering type (Single ID or One Per Entity) if blnJournalIDPerEntity == True: try: #Execute Journal Entry Number Per Entity bolResult = hfmAdapter.setJournalNumberPerEntity() except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(strSQL).encode("utf-8")) hfmAdapter.close() bolResult = False else: #Execute the single journal entry number update try: #rowsAffected = fdmAPI.executeDML(strSQL,None,True) rowsAffected = hfmAdapter.setJournalNumberAll() if rowsAffected > 0: bolResult = True except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(strSQL).encode("utf-8")) hfmAdapter.close() bolResult = False #Check the result of journal number setting if bolResult == True: #Create an empty file stating "Data Loaded as Journal" objFile = codecs.open(strFile, "w", "UTF-16_LE") strFile = "%s\%s_%s.jlf" % (fdmContext["OUTBOXDIR"], fdmContext["APPNAME"], str(fdmContext["LOADID"])) strFile = strFile.replace('\\', '/') objFile.write( "All data loaded as a Journal. See the Journal Data file (" + strFile + ") contents.") objFile.close() fdmAPI.updateProcessDetails(PROCESS_SUCCESS, PROCESS_EXPORT) fdmAPI.logDebug( "Data as Journal detected. Journal File will be created in the HFM_LOAD.py Action Script." ) else: fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) fdmAPI.logDebug( "Data as Journal detected, but there was an error updating the Journal number." ) hfmAdapter.close() return False #Data As Journal - No errors: HFM_LOAD.py handles the rest. hfmAdapter.close() return True #************************************************************************************ if hfmAdapter.doesLoadIDLoadICP() == True: if hfmAdapter.importFormatLoadsIcp() == True: strFile = "%s\%s_%s.trn" % (fdmContext["OUTBOXDIR"], fdmContext["APPNAME"], str(fdmContext["LOADID"])) strFile = strFile.replace('\\', '/') strFile = os.path.normpath(strFile) rsICP = hfmAdapter.getTrialBalanceIcp() if hfmAdapter.generateUnicodeFile(strFile) != True: fdmAPI.logError("Failed to generate ICP Load file.") fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) hfmAdapter.close() return False else: if (exportICP(strFile, rsICP, fdmCustoms) == True): fdmAPI.updateProcessDetails(PROCESS_SUCCESS, PROCESS_EXPORT) fdmAPI.logDebug("IC Detail Export was successful. See %s" % str(strFile).encode("utf-8")) return True else: fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) fdmAPI.logDebug("IC Detail Export failed.") hfmAdapter.close() return False #******************************************************************* #Line Item Detail Processing #******************************************************************* loadLineItems = bool(int(TargetOptions.get("LOAD_LINE_ITEM_DETAIL"))) lidLoadType = TargetOptions.get("LID_LOAD_TYPE") try: rsActiveDims = hfmAdapter.getActiveTargetDims(True) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False if blnLoadAsJournals == True: fdmAPI.logDebug("***Export data as data and journals as journals***") #exclude FDM Journals from DAT file strSelect = "SELECT " strFrom = " FROM AIF_HS_BALANCES" strGroupBy = " GROUP BY SCENARIO, PERIOD, DATAVIEW, ENTITY, " strWhere = " WHERE LOADID = " + str(fdmContext["LOADID"]) strWhere += " AND (" + fdmAPI.getDBProperties( )["LENGTH_FUNCTION"] + "(JournalID) = 0 OR JournalID Is Null)" while (rsActiveDims.next()): strSelect += rsActiveDims.getString("TDATASEG_COLUMN") + ", " if rsActiveDims.getString("TDATASEG_COLUMN") <> "ENTITY": strGroupBy += rsActiveDims.getString("TDATASEG_COLUMN") + ", " strSelect = strSelect + "YEAR as YEAR, PERIOD as PERIOD, SCENARIO AS SCENARIO, DATAVIEW AS DATAVIEW, DATAVALUE AS VALUE, SUM(AMOUNT) AS AMOUNT, JOURNALID as JOURNALID" strGroupBy = strGroupBy + "YEAR,PERIOD,SCENARIO,DATAVIEW,DATAVALUE,JOURNALID" else: fdmAPI.logDebug("***Export data and Journals as data***") #include both FDM Journals and standard data values strSelect = "SELECT " strFrom = " FROM AIF_HS_BALANCES" strGroupBy = " GROUP BY SCENARIO, PERIOD, DATAVIEW, " strWhere = " WHERE LOADID = " + str(fdmContext["LOADID"]) while (rsActiveDims.next()): strSelect += rsActiveDims.getString("TDATASEG_COLUMN") + ", " strGroupBy += rsActiveDims.getString("TDATASEG_COLUMN") + ", " strSelect = strSelect + "YEAR as YEAR, PERIOD as PERIOD, SCENARIO AS SCENARIO, DATAVIEW AS DATAVIEW, DATAVALUE AS VALUE, SUM(AMOUNT) AS AMOUNT, JOURNALID as JOURNALID" strGroupBy = strGroupBy + "YEAR,PERIOD,SCENARIO,DATAVIEW,DATAVALUE,JOURNALID" rsExport = fdmAPI.executeQuery( strSelect + strFrom + strWhere + strGroupBy + " ORDER BY YEAR, PERIOD, SCENARIO, DATAVIEW, JOURNALID, ACCOUNT", None) while (rsExport.next()): if datFileCreated != True: if hfmAdapter.generateUnicodeFile(strFile) != True: fdmAPI.logError("Failed to generate data load file.") fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) hfmAdapter.close() return False else: objFile = codecs.open(strFile, "a", "UTF-16_LE") objFile.write("!Data" + os.linesep) datFileCreated = True lidLinesWritten = False #Category strLine = rsExport.getString("SCENARIO") + DELIM #Year strLine += rsExport.getString("YEAR") + DELIM #Period strLine += rsExport.getString("PERIOD") + DELIM #View strLine += rsExport.getString("DATAVIEW") + DELIM #Entity strLine += rsExport.getString("ENTITY") + DELIM #DATAVALUE strLine += strDataValue + DELIM #ACCOUNT strLine += rsExport.getString("ACCOUNT") + DELIM #ICP strLine += rsExport.getString("ICP") + DELIM #C1 strLine += rsExport.getString("UD1") + DELIM #C2 strLine += rsExport.getString("UD2") + DELIM x = 1 while x <= fdmCustoms: strLine += rsExport.getString("UD" + str((x + 2))) + DELIM x += 1 #Line Item Detail if loadLineItems == True: #************************************************************************************ #Connect to HFM #************************************************************************************ if isConnectedForLineItems == False: try: isConnectedForLineItems = hfmAdapter.connect( userName, locale, fmCluster, unicode(fdmContext["TARGETAPPNAME"])) if isConnectedForLineItems == False: fdmAPI.logError( "Failed to connect to:%s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) hfmAdapter.close() return False else: fdmAPI.logDebug( "Connected to: %s for line items" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) except: fdmAPI.logError( "Failed to connected to: %s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) hfmAdapter.close() return False if hfmAdapter.accountUsesLineItems( unicode(rsExport.getString("ACCOUNT"))) == True: if lidLoadType == "1": #summary line items objFile.write("!LINE_ITEM_DETAIL" + os.linesep) #Amount, finish the line with normal length strLine += '"' + rsExport.getString( "ACCOUNT" ) + '"' + DELIM + hfmAdapter.setAmountToHFMUserPref( rsExport.getString("AMOUNT")) #Write the line objFile.write(strLine + os.linesep) objFile.write("!DATA" + os.linesep) elif lidLoadType == "2": #DETAIL LINE ITEMS objFile.write("!LINE_ITEM_DETAIL" + os.linesep) aCustoms = ArrayList() x = 1 while x <= (fdmCustoms + 2): aCustoms.add(rsExport.getString("UD" + str((x)))) x += 1 try: rsDrill = hfmAdapter.getLineItemDetail( unicode(rsExport.getString("SCENARIO")), unicode(rsExport.getString("PERIOD")), unicode(rsExport.getString("YEAR")), unicode(rsExport.getString("DATAVIEW")), unicode(rsExport.getString("ENTITY")), unicode(rsExport.getString("ACCOUNT")), unicode(rsExport.getString("ICP")), aCustoms) while (rsDrill.next()): #Write the DETAIL line to the file try: amt = hfmAdapter.setAmountToHFMUserPref( rsDrill.getString("AMOUNTX")) except: amt = rsDrill.getString("AMOUNTX") lidLinesWritten = True objFile.write( strLine + '"' + unicode(rsDrill.getString("ACCOUNT")) + '-' + unicode(rsDrill.getString("ENTITY")) + '-' + unicode(rsDrill.getString("DESC1")) + '"' + DELIM + amt + os.linesep) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False if lidLinesWritten == False: try: amt = hfmAdapter.setAmountToHFMUserPref( rsExport.getString("AMOUNT")) except: amt = rsExport.getString("AMOUNT") #finish line with normal length strLine += ('"' + rsExport.getString("ACCOUNT") + '"' + DELIM + amt) objFile.write(strLine + os.linesep) objFile.write("!DATA" + os.linesep) else: try: strLine += hfmAdapter.setAmountToHFMUserPref( rsExport.getString("AMOUNT")) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) strLine += rsExport.getString("AMOUNT") objFile.write(strLine + os.linesep) else: try: #Check for Zero Suppression if bool(int( TargetOptions.get("HFM_ENABLE_MULTI_LOAD_LOADING"))): strLine += hfmAdapter.setAmountToHFMUserPref( rsExport.getString("AMOUNT")) else: if float(rsExport.getString("AMOUNT")) != 0: strLine += hfmAdapter.setAmountToHFMUserPref( rsExport.getString("AMOUNT")) else: strLine += "" except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) strLine += rsExport.getString("AMOUNT") objFile.write(strLine + os.linesep) rsExport.close() #---------------------------------------------------------------------------- #Data Protection - Extract Protection Data & Append to DAT file #---------------------------------------------------------------------------- if bool(int(TargetOptions.get("ENABLE_DATA_PROTECTION"))) == True: fdmAPI.logDebug("Data Protection is on.") #************************************************************************************ #Connect to HFM #************************************************************************************ if isConnectedForDataProtection == False: try: isConnectedForDataProtection = hfmAdapter.connect( userName, locale, fmCluster, unicode(fdmContext["TARGETAPPNAME"])) if isConnectedForDataProtection == False: fdmAPI.logError( "Failed to connect to:%s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) hfmAdapter.close() return False else: fdmAPI.logDebug( "Connected to: %s for data protection" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) except: fdmAPI.logError( "Failed to connected to: %s" % str(fdmContext["TARGETAPPNAME"]).encode("utf-8")) hfmAdapter.close() return False try: extractedProtectionData = hfmAdapter.extractDataProtection( fdmContext["OUTBOXDIR"], DELIM, TargetOptions.get("PROTECTION_OPERATOR"), TargetOptions.get("PROTECTION_VALUE"), False, False) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False fdmAPI.logDebug("ppodhiya - Before check") if extractedProtectionData.size() > 0: fdmAPI.logDebug("ppodhiya - After check. Size > 0") objFile.write(os.linesep) objFile.write( "'The following data is added to this file as a result of Data Protection" + os.linesep) blnCellText = False for pData in extractedProtectionData: if pData.find("!DESCRIPTIONS") != -1: fdmAPI.logDebug( "ppodhiya - *************** Found Cell Text Section ***************" ) fdmAPI.logDebug( "ppodhiya - Setting blnCellText to True to skip cell text data" ) blnCellText = True if blnCellText == False: objFile.write(pData + os.linesep) #END FOR objFile.write(os.linesep) #END IF - DATA PROTECTION if datFileCreated == True: objFile.close() else: if hfmAdapter.generateUnicodeFile(strFile) != True: fdmAPI.logError("Failed to generate data load file.") fdmAPI.updateProcessDetails(PROCESS_FAILED, PROCESS_EXPORT) hfmAdapter.close() return False else: objFile = codecs.open(strFile, "a", "UTF-16_LE") objFile.write("!DATA" + os.linesep) objFile.close() try: hfmAdapter.close() except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) hfmAdapter.close() return False #Update Export Status fdmAPI.updateProcessDetails(PROCESS_SUCCESS, PROCESS_EXPORT)
def generateFXRatesLoadFile(loadID, strFile, hfmAPI, fdmAPI, fxEntity, beginAccount, endAccount, averageAccount): import codecs import os colName = "" DELIM = ";" objFile = codecs.open(strFile, "a", "UTF-16_LE") if fxEntity == "IsEmpty": objFile.write("!Entity = [None]" + os.linesep) objFile.write("!Value = [None]" + os.linesep) else: objFile.write("!Entity = " + fxEntity + os.linesep) #************************************************************************************ #Get the location's DataValue #************************************************************************************ rs = fdmAPI.getLocationDetails( BigDecimal(str(fdmContext["LOCKEY"]))) while (rs.next()): strDataValue = rs.getString("PARTDATAVALUE") #If data value is not set default to <entity currency> if strDataValue == None: strDataValue = "<entity currency>" Position = strDataValue.find(DELIM) if Position > 0: strDataValue = strDataValue[:Position] objFile.write("!Value = " + strDataValue + os.linesep) #************************************************************************************ objFile.write("!ICP = [ICP None]" + os.linesep) objFile.write("!VIEW = YTD" + os.linesep) try: rs = hfmAPI.getActiveTargetDims(False) while (rs.next()): colName = rs.getString("TDATASEG_COLUMN") if colName.startswith("UD"): if colName != "UD1" and colName != "UD2": objFile.write("!" + rs.getString("DIMENSION_NAME")) objFile.write(" = [None]") objFile.write(os.linesep) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) objFile.close return False objFile.write(os.linesep) objFile.write("!Data" + os.linesep) try: fxSQL = "SELECT (SELECT A.CATNAME FROM TPOVCATEGORY A INNER JOIN AIF_BAL_RULE_LOADS B ON A.CATKEY = B.CATKEY WHERE B.LOADID = " + loadID + ") as CATNAME, EPM_YEAR, EPM_PERIOD, FROM_CURRENCY, TO_CURRENCY, RATE_TYPE, CONVERSION_RATE FROM AIF_HS_EXCHANGE_RATES WHERE LOADID = " + loadID + " ORDER BY RATE_TYPE" rs = fdmAPI.executeQuery(fxSQL, None) while (rs.next()): objFile.write(rs.getString("CATNAME") + DELIM) objFile.write(rs.getString("EPM_YEAR") + DELIM) objFile.write(rs.getString("EPM_PERIOD") + DELIM) if rs.getString("RATE_TYPE") == "BEGIN": objFile.write(beginAccount + DELIM) elif rs.getString("RATE_TYPE") == "END": objFile.write(endAccount + DELIM) elif rs.getString("RATE_TYPE") == "AVERAGE": objFile.write(averageAccount + DELIM) objFile.write(rs.getString("FROM_CURRENCY") + DELIM) objFile.write(rs.getString("TO_CURRENCY") + DELIM) objFile.write(str(rs.getBigDecimal("CONVERSION_RATE", 38))) objFile.write(os.linesep) except: fdmAPI.logError(str(sys.exc_info()[1]).encode("utf-8")) fdmAPI.logError(str(fxSQL).encode("utf-8")) objFile.close return False objFile.close return True