## Script (Python) "changeCostInPins"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=batch_id,old_cost
##title=
##
# $Id: changeCostInPins.py 3132 2008-02-08 21:10:38Z henrik $
"""
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

mtool = context.portal_membership
member = mtool.getAuthenticatedMember()
if str(member) not in ('admin','joachim'):
    return

import logging
import DateTime
logger = logging.getLogger('Skins.changeCostInPins')
from Products.AdvancedQuery import Eq, Between, Le,In
aq_pins = context.portal_pins.evalAdvancedQuery

request = context.REQUEST
session = request.SESSION
batch = getattr(context.portal_url.getPortalObject().campus.pins,batch_id,None)
if batch is None:
    logger.info('No such batch %s' % batch_id)
new_cost = batch.getContent().cost
prefix_batch = batch_id.replace('_','')
query = Eq('prefix_batch',prefix_batch)
pins = aq_pins(query)
if len(pins) is None:
    logger.info('No pins with prefix_batch  %s' % prefix_batch)
edited = 0
wrong = 0
count = 0
commit_after = 50
#logger.info('started to change %d pins cost from %s to %s' %
#            (len(pins),old_cost,new_cost))
to_edit = []
for pin in pins:
    count += 1
    if pin.cost != float(old_cost):
        logger.info("%s: cost %s does not match %s" % (pin.key,
                                                       pin.cost,
                                                       old_cost))
        wrong += 1
        continue
    to_edit += pin.pin,
logger.info('%d %s pins found, start editing cost from %s to %s' %
            (len(pins),batch_id,old_cost,new_cost))            
for pin in to_edit:
    context.portal_pins.modifyRecord(**{'pin': pin, 'cost': float(new_cost)})
logger.info('finished editing %d %s pins, %d had wrong cost' % (count, batch_id,
                                                                     wrong))
