source: remit/vouchers/models.py @ e1086bd

client
Last change on this file since e1086bd was f52f909, checked in by Alex Dehnert <adehnert@…>, 15 years ago

Allow sorting requests (Trac: #39)

  • Property mode set to 100644
File size: 8.3 KB
Line 
1from django.db import models
2import settings
3import finance_core
4from finance_core.models import BudgetArea, BudgetTerm
5
6import datetime
7
8APPROVAL_STATE_PENDING = 0
9APPROVAL_STATE_APPROVED = 1
10APPROVAL_STATE_REJECTED = -1
11APPROVAL_STATES = (
12    (APPROVAL_STATE_PENDING,  'Pending'),
13    (APPROVAL_STATE_APPROVED, 'Approved'),
14    (APPROVAL_STATE_REJECTED, 'Rejected'),
15)
16
17class ReimbursementRequest(models.Model):
18    submitter = models.CharField(max_length=30) # Username of submitter
19    check_to_first_name = models.CharField(max_length=50, verbose_name="check recipient's first name")
20    check_to_last_name = models.CharField(max_length=50, verbose_name="check recipient's last name")
21    check_to_email = models.EmailField(verbose_name="email address for check pickup")
22    check_to_addr = models.TextField(blank=True, verbose_name="address for check mailing", help_text="For most requests, this should be blank for pickup in SAO (W20-549)")
23    amount = models.DecimalField(max_digits=7, decimal_places=2, help_text='Do not include "$"')
24    budget_area = models.ForeignKey(BudgetArea, related_name='as_budget_area')
25    budget_term = models.ForeignKey(BudgetTerm)
26    expense_area = models.ForeignKey(BudgetArea, related_name='as_expense_area') # ~GL
27    incurred_time = models.DateTimeField(default=datetime.datetime.now, help_text='Time the item or service was purchased')
28    request_time = models.DateTimeField(default=datetime.datetime.now)
29    approval_time = models.DateTimeField(blank=True, null=True,)
30    approval_status = models.IntegerField(default=0, choices=APPROVAL_STATES)
31    name = models.CharField(max_length=50, verbose_name='short description', )
32    description = models.TextField(blank=True, verbose_name='long description', )
33    documentation = models.ForeignKey('Documentation', null=True, blank=True, )
34    voucher       = models.ForeignKey('Voucher',       null=True, )
35
36    class Meta:
37        permissions = (
38            ('can_list', 'Can list requests',),
39            ('can_approve', 'Can approve requests',),
40            ('can_email', 'Can send mail about requests',),
41        )
42        ordering = ['id', ]
43
44    def __unicode__(self, ):
45        return "%s: %s %s (%s) (by %s) for $%s" % (
46            self.name,
47            self.check_to_first_name,
48            self.check_to_last_name,
49            self.check_to_email,
50            self.submitter,
51            self.amount,
52        )
53
54    def convert(self, signatory, signatory_email=settings.SIGNATORY_EMAIL):
55        voucher = Voucher()
56        voucher.group_name = settings.GROUP_NAME
57        voucher.account = self.budget_area.get_account_number()
58        voucher.signatory = signatory
59        voucher.signatory_email = signatory_email
60        voucher.first_name = self.check_to_first_name
61        voucher.last_name = self.check_to_last_name
62        voucher.email_address = self.check_to_email
63        voucher.mailing_address = self.check_to_addr
64        voucher.amount = self.amount
65        voucher.description = self.label() + ': ' + self.name
66        voucher.gl = self.expense_area.get_account_number()
67        voucher.documentation = self.documentation
68        voucher.save()
69        finance_core.models.make_transfer(
70            self.name,
71            self.amount,
72            finance_core.models.LAYER_EXPENDITURE,
73            self.budget_term,
74            self.budget_area,
75            self.expense_area,
76            self.description,
77            self.incurred_time,
78        )
79        self.approval_status = 1
80        self.approval_time = datetime.datetime.now()
81        self.voucher = voucher
82        self.save()
83
84    def label(self, ):
85        return settings.GROUP_ABBR + unicode(self.pk) + 'RR'
86
87class Voucher(models.Model):
88    group_name = models.CharField(max_length=40)
89    account = models.IntegerField()
90    signatory = models.CharField(max_length=50)
91    signatory_email = models.EmailField()
92    first_name = models.CharField(max_length=20)
93    last_name = models.CharField(max_length=20)
94    email_address = models.EmailField(max_length=50)
95    mailing_address = models.TextField(blank=True, )
96    amount = models.DecimalField(max_digits=7, decimal_places=2,)
97    description = models.TextField()
98    gl = models.IntegerField()
99    processed = models.BooleanField()
100    process_time = models.DateTimeField(blank=True, null=True,)
101    documentation = models.ForeignKey('Documentation', blank=True, null=True, )
102
103    def mailing_addr_lines(self):
104        import re
105        if self.mailing_address:
106            lst = re.split(re.compile('[\n\r]*'), self.mailing_address)
107            lst = filter(lambda elem: len(elem)>0, lst)
108        else:
109            lst = []
110        lst = lst + ['']*(3-len(lst))
111        return lst
112
113    def mark_processed(self, ):
114        self.process_time = datetime.datetime.now()
115        self.processed = True
116        self.save()
117
118    def __unicode__(self, ):
119        return "%s: %s %s (%s) for $%s" % (
120            self.description,
121            self.first_name,
122            self.last_name,
123            self.email_address,
124            self.amount,
125        )
126
127    class Meta:
128        permissions = (
129            ('generate_vouchers', 'Can generate vouchers',),
130        )
131
132
133class Documentation(models.Model):
134    backing_file = models.FileField(upload_to='documentation', verbose_name='File', help_text='PDF files only', )
135    label = models.CharField(max_length=50, default="")
136    submitter = models.CharField(max_length=30, null=True, ) # Username of submitter
137    upload_time = models.DateTimeField(default=datetime.datetime.now)
138
139    def __unicode__(self, ):
140        return "%s; uploaded at %s" % (self.label, self.upload_time, )
141
142
143class StockEmail:
144    def __init__(self, name, label, recipients, template, subject_template, context, ):
145        """
146        Initialize a stock email object.
147       
148        Each argument is required.
149       
150        name:       Short name. Letters, numbers, and hyphens only.
151        label:      User-readable label. Briefly describe what the email says
152        recipients: Who receives the email. List of "recipient" (check recipient), "area" (area owner), "admins" (site admins)
153        template:   Django template filename with the actual text
154        subject_template: Django template string with the subject
155        context:    Type of context the email needs. Must be 'request' currently.
156        """
157
158        self.name       = name
159        self.label      = label
160        self.recipients = recipients
161        self.template   = template
162        self.subject_template = subject_template
163        self.context    = context
164
165    def send_email_request(self, request,):
166        """
167        Send an email that requires context "request".
168        """
169
170        assert self.context == 'request'
171
172        # Generate text
173        from django.template import Context, Template
174        from django.template.loader import get_template
175        ctx = Context({
176            'prefix': settings.EMAIL_SUBJECT_PREFIX,
177            'request': request,
178            'sender': settings.USER_EMAIL_SIGNATURE,
179        })
180        tmpl = get_template(self.template)
181        body = tmpl.render(ctx)
182        subject_tmpl = Template(self.subject_template)
183        subject = subject_tmpl.render(ctx)
184
185        # Generate recipients
186        recipients = []
187        for rt in self.recipients:
188            if rt == 'recipient':
189                recipients.append(request.check_to_email)
190            elif rt == 'area':
191                recipients.append(request.budget_area.owner_address())
192            elif rt == 'admins':
193                pass # you don't *actually* have a choice...
194        for name, addr in settings.ADMINS:
195            recipients.append(addr)
196
197        # Send mail!
198        from django.core.mail import send_mail
199        send_mail(
200            subject,
201            body,
202            settings.SERVER_EMAIL,
203            recipients,
204        )
205
206stock_emails = {
207    'nodoc': StockEmail(
208        name='nodoc',
209        label='No documentation',
210        recipients=['recipient', 'area',],
211        template='vouchers/emails/no_docs_user.txt',
212        subject_template='{{prefix}}Missing documentation for reimbursement',
213        context = 'request',
214    ),
215    'voucher-sao': StockEmail(
216        name='voucher-sao',
217        label='Voucher submitted to SAO',
218        recipients=['recipient', ],
219        template='vouchers/emails/voucher_sao_user.txt',
220        subject_template='{{prefix}}Reimbursement sent to SAO for processing',
221        context = 'request',
222    ),
223}
Note: See TracBrowser for help on using the repository browser.