source: WAeUP_SRP/trunk/ScratchCards.py @ 970

Last change on this file since 970 was 948, checked in by joachim, 18 years ago

fixed import path

  • Property svn:keywords set to Id
File size: 5.7 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: ScratchCards.py 948 2006-11-27 12:54:43Z joachim $
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
13import DateTime
14import Globals
15import logging
16import os,csv,re
17import Globals
18MAX_TRANS = 1000
19p_home = Globals.package_home(globals())
20i_home = Globals.INSTANCE_HOME
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
35    security.declareProtected(ModifyPortalContent,"importPinBatch") ###(
36    def importPinBatch(self):
37        """import PinBatch"""
38        name = "PINS"
39        logger = logging.getLogger('%s_import' % name)
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:
46            pins = csv.DictReader(open("%s/%s" % (base_dir,fn),"rb"))
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']
55                    dict['prefix'] = pin['Serial']
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
63                p_pins.addRecord(pin=pin['Pin'],serial=n,student="",prefix_batch="%s%s" % (prefix, batch_no))
64                n += 1
65            dict['no_of_pins'] = n - 1
66            batch.getContent().edit(mapping=dict)
67            logger.info('Added %s with %d Pins' % (bid,n-1))
68        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
69    ###)
70
71InitializeClass(ScratchCardBatchesFolder)
72
73def addScratchCardBatchesFolder(container, id, REQUEST=None, **kw):
74    """Add a Students personal data."""
75    ob = ScratchCardBatchesFolder(id, **kw)
76    return CPSBase_adder(container, ob, REQUEST=REQUEST)
77
78###)
79
80from Products.WAeUP_SRP.WAeUPTables import PinTable
81
82class ScratchCardBatch(CPSDocument): ###(
83    """
84    WAeUP Student container for the various student data
85    """
86    meta_type = 'ScratchCardBatch'
87    portal_type = meta_type
88    security = ClassSecurityInfo()
89
90    security.declareProtected(View,"Title")
91    def Title(self):
92        """compose title"""
93        doc = self.getContent()
94        return "Pin Batch %s BatchNo %d" % (doc.prefix, doc.batch_no)
95
96    security.declareProtected(ModifyPortalContent,"makePins") ###(
97    def makePins(self):
98        """generate Pins"""
99        batch = self.getContent()
100        nr = batch.no_of_pins
101        prefix = batch.prefix
102        sold = batch.sold_by
103        cost = batch.cost
104        import random
105        r = random
106        b_no = batch.batch_no
107        #import pdb;pdb.set_trace()
108        generated = []
109        generated.append('"Serial","Pin","Sold","Cost"' % vars())
110        generated.append('"%(prefix)s","%(b_no)d","%(sold)s","%(cost)f"' % vars())
111        pins = self.portal_pins
112        for i in range(1,nr+1):
113            ri = r.randint(1000000000,9999999999)
114            pin = "%s%d%d" % (prefix,b_no,ri)
115            while len(pins.searchResults({'pin': pin})) > 0:
116                ri = r.randint(1000000000,9999999999)
117                pin = "%s%d%d" % (prefix,b_no,ri)
118            pins.addRecord(pin=pin,serial=i,student="",prefix_batch="%s%d" % (prefix, b_no))
119            generated.append('"%(i)d","%(prefix)s-%(b_no)d-%(ri)d"' % vars())
120        print '\n'.join(generated)
121        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
122        open("%s/import/%s-%s-%s.csv" % (i_home,prefix,b_no,current),"w+").write('\n'.join(generated))
123    ###)
124
125
126    security.declareProtected(ModifyPortalContent,"getUnusedPins")
127    def getUnusedPins(self):
128        """return a list of unused Pins"""
129        max_pins = 10
130        #import pdb;pdb.set_trace()
131        pins_cat = self.portal_pins
132        doc = self.getContent()
133        unused = [{'pin': p.pin,
134              'serial': p.serial,
135              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
136                                               % (doc.prefix,doc.batch_no),
137                                               ) if not p.student]
138        used = [{'pin': p.pin,
139              'serial': p.serial,
140              'student': p.student,
141              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
142                                               % (doc.prefix,doc.batch_no),
143                                               ) if p.student]
144        if len (unused) <= max_pins:
145            return unused,used
146        return unused[:max_pins],used
147
148InitializeClass(ScratchCardBatch)
149
150def addScratchCardBatch(container, id, REQUEST=None, **kw):
151    """Add a Students personal data."""
152    ob = ScratchCardBatch(id, **kw)
153    return CPSBase_adder(container, ob, REQUEST=REQUEST)
154
155###)
Note: See TracBrowser for help on using the repository browser.