## Script (Python) "ti_167_resolve"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
# $Id: ti_167_resolve.py 2062 2007-07-26 20:58:59Z joachim $
"""
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass
import logging
logger = logging.getLogger('Skins.ti_167_resolve')
from Products.AdvancedQuery import Eq, Between, Le,In,MatchGlob
aq_pins = context.portal_pins.evalAdvancedQuery
aq_portal = context.portal_catalog_real.evalAdvancedQuery

request = context.REQUEST
session = request.SESSION
response = request.RESPONSE
setheader = request.RESPONSE.setHeader
students = context.portal_url.getPortalObject().campus.students

#from string import Template
def rwrite(s):
    response.setHeader('Content-type','text/html; charset=ISO-8859-15')
    response.write("%s<br>\n\r" % s)

batches = context.portal_catalog(portal_type = "ScratchCardBatch")
logger.info("starting to insert cost property into pins-catatlog")
batch_cost = {}
for batch in batches:
    prefix_batch = ''.join(batch.getId.split('_'))
    cost = batch.getObject().getContent().cost
    batch_cost[prefix_batch] = cost
    query = Eq('prefix_batch',prefix_batch)
    pins = aq_pins(query)
    for pin in pins:
        context.portal_pins.modifyRecord(pin=pin.pin,cost=cost)
    #rwrite("%s, %s" % (prefix_batch,cost))
    logger.info("Cost %s (for %s) in portal_pins replaced" % (cost,prefix_batch))
query = Eq('portal_type',"Payment")
payments = aq_portal(query)
count = 0
no_cost = 0
commit_after = 100
for payment in payments:
    if payment.Title.find('n/a') > -1:
        #set_trace()
        payment_doc = payment.getObject().getContent()
        prefix_batch = ''.join(str(payment_doc.order_id).split('-')[:2])
        if batch_cost.has_key(prefix_batch):
            count += 1
            payment_doc.edit(mapping = {'amount':
                                        batch_cost[prefix_batch]})
            #rwrite("%s: %s:%s" % (count,prefix_batch,payment_doc.order_id))
            logger.info("Cost in payment object %s (%s) replaced (#%s)" % (payment.id,payment_doc.order_id,count))
        else:
            #rwrite("cost %s:%s not found" % (prefix_batch,payment_doc.order_id))
            logger.info("Prefix %s (%s) not found" % (prefix_batch,payment_doc.order_id))
            no_cost +=1
    if count and not count % commit_after:
        context.waeup_tool.doCommit()
        logger.info("Committing %s transactions, total %s" % (commit_after,count))
logger.info("updated %d payment amounts, %d costs not found" % (count,no_cost))


