source: WAeUP_SRP/trunk/ScratchCards.py @ 16680

Last change on this file since 16680 was 5040, checked in by Henrik Bettermann, 15 years ago

improve logging

  • Property svn:keywords set to Id
File size: 10.3 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: ScratchCards.py 5040 2010-02-25 15:39:13Z 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    # use importPinBatch to import original pin batch files
36    security.declareProtected(ModifyPortalContent,"importPinBatch") ###(
37    def importPinBatch(self):
38        """import PinBatch"""
39        #name = "PinsToImport"
40        logger = logging.getLogger('ScratchCards.ScratchCardBatchesFolder.importPinBatch')
41        pins_section = self.portal_url.getPortalObject().campus.pins
42        p_pins = self.portal_pins
43        base_dir = "%s/import/pins" % (i_home)
44        logger.info('Start loading pin batch files from %s' % base_dir)
45        files = os.listdir(base_dir)
46        for fn in files:
47            pins = csv.DictReader(open("%s/%s" % (base_dir,fn),"rb"))
48            n = 0
49            for pin in pins:
50                if n == 0:
51                    bid = "%(Serial)s_%(Pin)s" % pin
52                    pins_section.invokeFactory('ScratchCardBatch', bid)
53                    batch = getattr(pins_section,bid)
54                    dict = {}
55                    prefix = pin['Serial']
56                    dict['prefix'] = pin['Serial']
57                    batch_no = pin['Pin']
58                    dict['batch_no'] = int(batch_no)
59                    dict['cost'] = float(pin['Cost'])
60                    dict['sold_by'] = pin['Sold']
61                    #import pdb;pdb.set_trace()
62                    n += 1
63                    continue
64                puid = "".join(pin['Pin'].split('-'))
65                p_pins.addRecord(pin=puid,serial=n,student="",prefix_batch="%s%s" % (prefix, batch_no))
66                n += 1
67            dict['no_of_pins'] = n - 1
68            batch.getContent().edit(mapping=dict)
69            logger.info('%s with %d PINs added' % (bid,n-1))
70        return self.REQUEST.RESPONSE.redirect("%s" % self.REQUEST.get('URL1'))
71    ###)
72
73InitializeClass(ScratchCardBatchesFolder)
74
75def addScratchCardBatchesFolder(container, id, REQUEST=None, **kw):
76    """Add a Students personal data."""
77    ob = ScratchCardBatchesFolder(id, **kw)
78    return CPSBase_adder(container, ob, REQUEST=REQUEST)
79
80###)
81
82from Products.WAeUP_SRP.WAeUPTables import PinTable
83
84class ScratchCardBatch(CPSDocument): ###(
85    """
86    WAeUP Student container for the various student data
87    """
88    meta_type = 'ScratchCardBatch'
89    portal_type = meta_type
90    security = ClassSecurityInfo()
91
92    security.declareProtected(View,"Title")
93    def Title(self):
94        """compose title"""
95        return "Pin Batch"
96
97    security.declareProtected(ModifyPortalContent,"makePins") ###(
98    def makePins(self):
99        """generate Pins"""
100        batch = self.getContent()
101        nr = batch.no_of_pins
102        prefix = batch.prefix
103        sold = batch.sold_by
104        cost = batch.cost
105        import random
106        r = random
107        b_no = batch.batch_no
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
113        for i in range(1,nr+1):
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)
119            pins.addRecord(pin=pin,
120                           serial=i,
121                           student="",
122                           cost = cost,
123                           prefix_batch="%s%d" % (prefix, b_no))
124            generated.append('"%(i)d","%(prefix)s-%(b_no)d-%(ri)d"' % vars())
125        print '\n'.join(generated)
126        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
127        open("%s/export/%s-%s-%s.csv" % (i_home,prefix,b_no,current),"w+").write('\n'.join(generated))
128    ###)
129
130    security.declareProtected(ModifyPortalContent,"restorePins") ###(
131    def restorePins(self):
132        "restore Pins from file named PinsToRestore.csv"
133        pins = self.portal_pins
134        filename = "%s/import/PinsToRestore.csv" % (i_home)
135        logger = logging.getLogger('ScratchCards.ScratchCardBatch.restorePins')
136        if not os.path.exists(filename):
137            logger.info('no file %s' % filename)
138            return
139        src = open(filename,"rb")
140        records = csv.DictReader(src)
141        cards = []
142        already_in = []
143        #import pdb;pdb.set_trace()
144        records.next()
145        for record in records:
146            d = {}
147            d['pin'] = record['Pin'].replace('-','')
148            if pins(pin=d['pin']):
149                logger.info("pin %(pin)s already in Pins" % d)
150                already_in += d['pin'],
151                continue
152            d['serial'] = record['Serial']
153            d['cost'] = record['Cost']
154            d['student'] = ''
155            d['prefix_batch'] = "".join(record['Pin'].split('-')[:2])
156            cards += d,
157        if already_in:
158            logger.info("found %d existing pins in %s" % (len(already_in),filename))
159            return
160        anz = len(cards)
161        logger.info("start restoring %d pins from %s" % (anz,filename))
162        for card in cards:
163            pins.addRecord(**card)
164        logger.info("sucessfully restored %d pins from %s" % (anz,filename))
165        url = self.REQUEST.get('URL1')
166        return self.REQUEST.RESPONSE.redirect(url)
167
168    security.declareProtected(ModifyPortalContent,"archiveBatch") ###(
169    def archiveBatch(self,delete=False):
170        """archive a batch"""
171        #import pdb;pdb.set_trace()
172        batch = self.getContent()
173        member = self.portal_membership.getAuthenticatedMember()
174        logger = logging.getLogger('ScratchCards.ScratchCardBatch.archiveBatch')
175        nr = batch.no_of_pins
176        prefix = batch.prefix
177        sold = batch.sold_by
178        cost = batch.cost
179        batch_no = batch.batch_no
180        current = DateTime.DateTime().strftime("%d-%m-%y_%H_%M_%S")
181        export_file = "%s/export/%s-%s_archive_%s.csv" % (i_home,prefix,batch_no,current)
182        lines = []
183        fields = ['prefix','serial','pin','student']
184        headline = ','.join(fields)
185        out = open(export_file,"wb")
186        out.write('%(prefix)s,%(cost)8.2f,%(batch_no)d,%(nr)d,%(sold)s\n\n' % vars())
187        out.write(headline +'\n')
188        out.close()
189        out = open(export_file,"a")
190        csv_writer = csv.DictWriter(out,fields,)
191        pins = self.portal_pins(prefix_batch = "%(prefix)s%(batch_no)d" % vars())
192        logger.info('%s starts archiving %s_%s with %s records ' % (member,
193                                                                    prefix,
194                                                                    batch_no,
195                                                                    len(pins)))
196
197        pin_list = []
198        for pin in pins:
199            pin_list += pin.pin,
200            lines.append(self.portal_pins.record2dict(fields,pin,'dummy'))
201        total = len(lines)
202        csv_writer.writerows(lines)
203        msg = "wrote %(total)d records to %(export_file)s" % vars()
204        logger.info(msg)
205        if delete:
206            for pin in pin_list:
207                self.portal_pins.deleteRecord(pin)
208            msg = "deleted %d pin from portal_pins" % len(pin_list)
209            logger.info(msg)
210        url = self.REQUEST.get('URL1')
211        return self.REQUEST.RESPONSE.redirect(url)
212    ###)
213
214    security.declareProtected(ModifyPortalContent,"getUnusedPins") ###(
215    def getUnusedPins(self):
216        """return a list of unused Pins"""
217        max_pins = 10
218        #import pdb;pdb.set_trace()
219        pins_cat = self.portal_pins
220        doc = self.getContent()
221        unused = [{'pin': p.pin,
222              'serial': p.serial,
223              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
224                                               % (doc.prefix,doc.batch_no),
225                                               ) if not p.student]
226        if len(unused) > max_pins:
227            return unused[-max_pins:]
228        return unused
229    ###)
230
231    security.declareProtected(View,"getUsedPins") ###(
232    def getUsedPins(self):
233        """return a list of used Pins"""
234        #import pdb;pdb.set_trace()
235        pins_cat = self.portal_pins
236        doc = self.getContent()
237        used = [{'pin': p.pin,
238              'prefix_batch': p.prefix_batch,
239              'serial': p.serial,
240              'student': p.student,
241              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
242                                               % (doc.prefix,doc.batch_no),
243                                               ) if p.student]
244        return used
245    ###)
246
247    security.declareProtected(View,"getNumberOfUsedPins") ###(
248    def getNumberOfUsedPins(self):
249        """return the number of used Pins"""
250        #import pdb;pdb.set_trace()
251        pins_cat = self.portal_pins
252        doc = self.getContent()
253        used = [{'pin': p.pin,
254              'serial': p.serial,
255              'student': p.student,
256              } for p in pins_cat.searchResults(prefix_batch = "%s%d"
257                                               % (doc.prefix,doc.batch_no),
258                                               ) if p.student]
259        return len(used)
260    ###)
261
262InitializeClass(ScratchCardBatch)
263
264def addScratchCardBatch(container, id, REQUEST=None, **kw):
265    """Add a Students personal data."""
266    ob = ScratchCardBatch(id, **kw)
267    return CPSBase_adder(container, ob, REQUEST=REQUEST)
268
269###)
Note: See TracBrowser for help on using the repository browser.