source: WAeUP_SRP/trunk/ScratchCards.py @ 3810

Last change on this file since 3810 was 3616, checked in by Henrik Bettermann, 16 years ago

too tired

  • Property svn:keywords set to Id
File size: 10.2 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: ScratchCards.py 3616 2008-08-07 12:27:22Z henrik $
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 = "PinsToImport"
39        logger = logging.getLogger('Students.ScratchCardBatchesFolder.importPinBatch')
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                puid = "".join(pin['Pin'].split('-'))
64                p_pins.addRecord(pin=puid,serial=n,student="",prefix_batch="%s%s" % (prefix, batch_no))
65                n += 1
66            dict['no_of_pins'] = n - 1
67            batch.getContent().edit(mapping=dict)
68            logger.info('%s with %d PINs added' % (bid,n-1))
69        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
70    ###)
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        return "Pin Batch"
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,
119                           serial=i,
120                           student="",
121                           cost = cost,
122                           prefix_batch="%s%d" % (prefix, b_no))
123            generated.append('"%(i)d","%(prefix)s-%(b_no)d-%(ri)d"' % vars())
124        print '\n'.join(generated)
125        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
126        open("%s/export/%s-%s-%s.csv" % (i_home,prefix,b_no,current),"w+").write('\n'.join(generated))
127    ###)
128
129    security.declareProtected(ModifyPortalContent,"restorePins") ###(
130    def restorePins(self):
131        "restore Pins from file named pins_to_restore.csv"
132        pins = self.portal_pins
133        filename = "%s/import/PinsToRestore.csv" % (i_home)
134        logger = logging.getLogger('ScratchCards.restorePins')
135        if not os.path.exists(filename):
136            logger.info('no file %s' % filename)
137            return
138        src = open(filename,"rb")
139        records = csv.DictReader(src)
140        cards = []
141        already_in = []
142        #import pdb;pdb.set_trace()
143        records.next()
144        for record in records:
145            d = {}
146            d['pin'] = record['Pin'].replace('-','')
147            if pins(pin=d['pin']):
148                logger.info("pin %(pin)s already in Pins" % d)
149                already_in += d['pin'],
150                continue
151            d['serial'] = record['Serial']
152            d['cost'] = record['Cost']
153            d['student'] = ''
154            d['prefix_batch'] = "".join(record['Pin'].split('-')[:2])
155            cards += d,
156        if already_in:
157            logger.info("found %d existing pins in %s" % (len(already_in),filename))
158            return
159        anz = len(cards)
160        logger.info("start restoring %d pins from %s" % (anz,filename))
161        for card in cards:
162            pins.addRecord(**card)
163        logger.info("sucessfully restored %d pins from %s" % (anz,filename))
164        url = self.REQUEST.get('URL1')
165        return self.REQUEST.RESPONSE.redirect(url)
166
167    security.declareProtected(ModifyPortalContent,"archiveBatch") ###(
168    def archiveBatch(self,delete=False):
169        """archive a batch"""
170        #import pdb;pdb.set_trace()
171        batch = self.getContent()
172        member = self.portal_membership.getAuthenticatedMember()
173        logger = logging.getLogger('ScratchCards.archiveBatch')
174        nr = batch.no_of_pins
175        prefix = batch.prefix
176        sold = batch.sold_by
177        cost = batch.cost
178        batch_no = batch.batch_no
179        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
180        export_file = "%s/export/%s-%s_archive_%s.csv" % (i_home,prefix,batch_no,current)
181        lines = []
182        fields = ['prefix','serial','pin','student']
183        headline = ','.join(fields)
184        out = open(export_file,"wb")
185        out.write('%(prefix)s,%(cost)8.2f,%(batch_no)d,%(nr)d,%(sold)s\n\n' % vars())
186        out.write(headline +'\n')
187        out.close()
188        out = open(export_file,"a")
189        csv_writer = csv.DictWriter(out,fields,)
190        pins = self.portal_pins(prefix_batch = "%(prefix)s%(batch_no)d" % vars())
191        logger.info('%s starts archiving %s_%s with %s records ' % (member,
192                                                                    prefix,
193                                                                    batch_no,
194                                                                    len(pins)))
195
196        pin_list = []
197        for pin in pins:
198            pin_list += pin.pin,
199            lines.append(self.portal_pins.record2dict(fields,pin))
200        total = len(lines)
201        csv_writer.writerows(lines)
202        msg = "wrote %(total)d records to %(export_file)s" % vars()
203        logger.info(msg)
204        if delete:
205            for pin in pin_list:
206                self.portal_pins.deleteRecord(pin)
207            msg = "deleted %d pin from portal_pins" % len(pin_list)
208            logger.info(msg)
209        url = self.REQUEST.get('URL1')
210        return self.REQUEST.RESPONSE.redirect(url)
211    ###)
212
213    security.declareProtected(ModifyPortalContent,"getUnusedPins") ###(
214    def getUnusedPins(self):
215        """return a list of unused Pins"""
216        max_pins = 10
217        #import pdb;pdb.set_trace()
218        pins_cat = self.portal_pins
219        doc = self.getContent()
220        unused = [{'pin': p.pin,
221              'serial': p.serial,
222              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
223                                               % (doc.prefix,doc.batch_no),
224                                               ) if not p.student]
225        if len(unused) > max_pins:
226            return unused[-max_pins:]
227        return unused
228    ###)
229
230    security.declareProtected(View,"getUsedPins") ###(
231    def getUsedPins(self):
232        """return a list of used Pins"""
233        #import pdb;pdb.set_trace()
234        pins_cat = self.portal_pins
235        doc = self.getContent()
236        used = [{'pin': p.pin,
237              'prefix_batch': p.prefix_batch,
238              'serial': p.serial,
239              'student': p.student,
240              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
241                                               % (doc.prefix,doc.batch_no),
242                                               ) if p.student]
243        return used
244    ###)
245
246    security.declareProtected(View,"getNumberOfUsedPins") ###(
247    def getNumberOfUsedPins(self):
248        """return the number of used Pins"""
249        #import pdb;pdb.set_trace()
250        pins_cat = self.portal_pins
251        doc = self.getContent()
252        used = [{'pin': p.pin,
253              'serial': p.serial,
254              'student': p.student,
255              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
256                                               % (doc.prefix,doc.batch_no),
257                                               ) if p.student]
258        return len(used)
259    ###)
260
261InitializeClass(ScratchCardBatch)
262
263def addScratchCardBatch(container, id, REQUEST=None, **kw):
264    """Add a Students personal data."""
265    ob = ScratchCardBatch(id, **kw)
266    return CPSBase_adder(container, ob, REQUEST=REQUEST)
267
268###)
Note: See TracBrowser for help on using the repository browser.