source: WAeUP_SRP/branches/uli/ScratchCards.py @ 14046

Last change on this file since 14046 was 1593, checked in by uli, 18 years ago

Merged current trunk into uli-branch.

  • Property svn:keywords set to Id
File size: 6.7 KB
RevLine 
[489]1#-*- mode: python; mode: fold -*-
[805]2# $Id: ScratchCards.py 1593 2007-03-19 18:57:54Z uli $
[489]3from Globals import InitializeClass
4from AccessControl import ClassSecurityInfo
5from AccessControl.SecurityManagement import newSecurityManager
6from zExceptions import BadRequest
7from Products.CMFCore.utils import UniqueObject, getToolByName
8from Products.CMFCore.permissions import View
9from Products.CMFCore.permissions import ModifyPortalContent
10from Products.CPSCore.CPSBase import CPSBase_adder, CPSBaseFolder
11#from Products.CPSCore.CPSBase import CPSBaseDocument as BaseDocument
12from Products.CPSDocument.CPSDocument import CPSDocument
[502]13import DateTime
14import Globals
[947]15import logging
16import os,csv,re
17import Globals
18MAX_TRANS = 1000
[502]19p_home = Globals.package_home(globals())
20i_home = Globals.INSTANCE_HOME
[489]21
22class ScratchCardBatchesFolder(CPSDocument): ###(
23    """
24    WAeUP Student container for the various student data
25    """
26    meta_type = 'ScratchCardBatchesFolder'
27    portal_type = meta_type
28    security = ClassSecurityInfo()
29
30    security.declareProtected(View,"Title")
31    def Title(self):
32        """compose title"""
33        return "Pin Batches"
34
[947]35    security.declareProtected(ModifyPortalContent,"importPinBatch") ###(
36    def importPinBatch(self):
37        """import PinBatch"""
38        name = "PINS"
[1593]39        logger = logging.getLogger('Students.ScratchCardBatchesFolder.importPinBatch')
[947]40        logger.info('Start loading from %s.csv' % name)
41        pins_section = self.portal_url.getPortalObject().campus.pins
42        p_pins = self.portal_pins
43        base_dir = "%s/import/pins" % (i_home)
44        files = os.listdir(base_dir)
45        for fn in files:
[948]46            pins = csv.DictReader(open("%s/%s" % (base_dir,fn),"rb"))
[947]47            n = 0
48            for pin in pins:
49                if n == 0:
50                    bid = "%(Serial)s_%(Pin)s" % pin
51                    pins_section.invokeFactory('ScratchCardBatch', bid)
52                    batch = getattr(pins_section,bid)
53                    dict = {}
54                    prefix = pin['Serial']
[1082]55                    dict['prefix'] = pin['Serial']
[947]56                    batch_no = pin['Pin']
57                    dict['batch_no'] = int(batch_no)
58                    dict['cost'] = float(pin['Cost'])
59                    dict['sold_by'] = pin['Sold']
60                    #import pdb;pdb.set_trace()
61                    n += 1
62                    continue
[978]63                puid = "".join(pin['Pin'].split('-'))
64                p_pins.addRecord(pin=puid,serial=n,student="",prefix_batch="%s%s" % (prefix, batch_no))
[947]65                n += 1
66            dict['no_of_pins'] = n - 1
67            batch.getContent().edit(mapping=dict)
[1593]68            logger.info('%s with %d PINs added' % (bid,n-1))
[947]69        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
70    ###)
[489]71
72InitializeClass(ScratchCardBatchesFolder)
73
74def addScratchCardBatchesFolder(container, id, REQUEST=None, **kw):
75    """Add a Students personal data."""
76    ob = ScratchCardBatchesFolder(id, **kw)
77    return CPSBase_adder(container, ob, REQUEST=REQUEST)
78
79###)
80
81from Products.WAeUP_SRP.WAeUPTables import PinTable
82
83class ScratchCardBatch(CPSDocument): ###(
84    """
85    WAeUP Student container for the various student data
86    """
87    meta_type = 'ScratchCardBatch'
88    portal_type = meta_type
89    security = ClassSecurityInfo()
90
91    security.declareProtected(View,"Title")
92    def Title(self):
93        """compose title"""
94        doc = self.getContent()
95        return "Pin Batch %s BatchNo %d" % (doc.prefix, doc.batch_no)
96
[535]97    security.declareProtected(ModifyPortalContent,"makePins") ###(
[489]98    def makePins(self):
99        """generate Pins"""
100        batch = self.getContent()
101        nr = batch.no_of_pins
[502]102        prefix = batch.prefix
103        sold = batch.sold_by
104        cost = batch.cost
[489]105        import random
106        r = random
107        b_no = batch.batch_no
[502]108        #import pdb;pdb.set_trace()
109        generated = []
110        generated.append('"Serial","Pin","Sold","Cost"' % vars())
111        generated.append('"%(prefix)s","%(b_no)d","%(sold)s","%(cost)f"' % vars())
112        pins = self.portal_pins
[682]113        for i in range(1,nr+1):
[502]114            ri = r.randint(1000000000,9999999999)
115            pin = "%s%d%d" % (prefix,b_no,ri)
116            while len(pins.searchResults({'pin': pin})) > 0:
117                ri = r.randint(1000000000,9999999999)
118                pin = "%s%d%d" % (prefix,b_no,ri)
[535]119            pins.addRecord(pin=pin,serial=i,student="",prefix_batch="%s%d" % (prefix, b_no))
[502]120            generated.append('"%(i)d","%(prefix)s-%(b_no)d-%(ri)d"' % vars())
121        print '\n'.join(generated)
122        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
[612]123        open("%s/import/%s-%s-%s.csv" % (i_home,prefix,b_no,current),"w+").write('\n'.join(generated))
[535]124    ###)
[489]125
[947]126
[535]127    security.declareProtected(ModifyPortalContent,"getUnusedPins")
128    def getUnusedPins(self):
129        """return a list of unused Pins"""
[688]130        max_pins = 10
[535]131        #import pdb;pdb.set_trace()
132        pins_cat = self.portal_pins
133        doc = self.getContent()
[686]134        unused = [{'pin': p.pin,
[535]135              'serial': p.serial,
[612]136              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
137                                               % (doc.prefix,doc.batch_no),
[1395]138                                               ) if not p.student]
139        if len(unused) > max_pins:
140            return unused[-max_pins:]
[1002]141        return unused
[1593]142
[1120]143    security.declareProtected(View,"getUsedPins")
144    def getUsedPins(self):
145        """return a list of used Pins"""
146        #import pdb;pdb.set_trace()
147        pins_cat = self.portal_pins
148        doc = self.getContent()
149        used = [{'pin': p.pin,
150              'prefix_batch': p.prefix_batch,
151              'serial': p.serial,
152              'student': p.student,
153              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
154                                               % (doc.prefix,doc.batch_no),
155                                               ) if p.student]
156        return used
157
[1012]158    security.declareProtected(View,"getNumberOfUsedPins")
159    def getNumberOfUsedPins(self):
160        """return the number of used Pins"""
161        #import pdb;pdb.set_trace()
162        pins_cat = self.portal_pins
163        doc = self.getContent()
164        used = [{'pin': p.pin,
165              'serial': p.serial,
166              'student': p.student,
167              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
168                                               % (doc.prefix,doc.batch_no),
169                                               ) if p.student]
170        return len(used)
171
[489]172InitializeClass(ScratchCardBatch)
173
174def addScratchCardBatch(container, id, REQUEST=None, **kw):
175    """Add a Students personal data."""
176    ob = ScratchCardBatch(id, **kw)
177    return CPSBase_adder(container, ob, REQUEST=REQUEST)
178
179###)
Note: See TracBrowser for help on using the repository browser.