class ChequeDeposit(models.Model): voucher_no = models.IntegerField() date = BSDateField(default=today) bank_account = models.ForeignKey(Account, related_name='cheque_deposits') clearing_date = BSDateField(default=today, null=True, blank=True) benefactor = models.ForeignKey(Account) deposited_by = models.CharField(max_length=254, blank=True, null=True) narration = models.TextField(null=True, blank=True) company = models.ForeignKey(Company) files = models.ManyToManyField(File, blank=True) def __init__(self, *args, **kwargs): super(ChequeDeposit, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(ChequeDeposit, self.company_id) def __str__(self): return str(self.voucher_no) + ' : ' + str(self.deposited_by) def get_voucher_no(self): return self.id class Meta: unique_together = ('voucher_no', 'company') @property def total(self): grand_total = 0 for obj in self.rows.all(): total = obj.amount grand_total += total return grand_total
class ImprestTransaction(models.Model): name = models.CharField(max_length=255, null=True, blank=True) type = models.CharField(max_length=255, choices=IMPREST_TRANSACTION_TYPES) date = BSDateField(null=True, blank=True, default=today, validators=[validate_in_fy]) date_of_payment = BSDateField(null=True, blank=True, default=today, validators=[validate_in_fy]) wa_no = models.CharField(max_length=10, verbose_name='Withdrawal Application No.', null=True, blank=True) # ref = models.CharField(max_length=10, verbose_name='Reference', null=True, blank=True) amount_nrs = models.FloatField(blank=True, null=True) amount_usd = models.FloatField(blank=True, null=True) # currency = models.ForeignKey(Currency) # description = models.TextField(null=True, blank=True) exchange_rate = models.FloatField(null=True, blank=True) project_fy = models.ForeignKey(ProjectFy) def __str__(self): return self.name or self.get_type_display()
class Collection(models.Model): count = models.PositiveIntegerField() interest_rate = models.FloatField() start_date = BSDateField(blank=True, null=True, default=today) end_date = BSDateField(blank=True, null=True, default=today) company = models.ForeignKey(Company) def __str__(self): return str(self.count) def get_class_name(self): return self.__class__.__name__
class EntryReport(models.Model): entry_report_no = models.PositiveIntegerField(blank=True, null=True) date = BSDateField(default=today, validators=[validate_in_fy]) source_content_type = models.ForeignKey(ContentType) source_object_id = models.PositiveIntegerField() source = GenericForeignKey('source_content_type', 'source_object_id') objects = FYManager() def __init__(self, *args, **kwargs): super(EntryReport, self).__init__(*args, **kwargs) if not self.pk and not self.entry_report_no: self.entry_report_no = get_next_voucher_no_for_fy(self.__class__, 'entry_report_no') def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(entry_report_no=self.entry_report_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(EntryReport, self).save(*args, **kwargs) @property def fiscal_year(self): return FiscalYear.from_date(self.source.date) def get_absolute_url(self): if self.source.__class__.__name__ == 'Handover': source_type = 'handover' else: source_type = 'purchase' return '/inventory/entry-report/' + source_type + '/' + str(self.source.id) def __str__(self): return unicode(self.entry_report_no)
class Expense(models.Model): voucher_no = models.IntegerField(blank=True, null=True) date = BSDateField(default=today) company = models.ForeignKey(Company) def __init__(self, *args, **kwargs): super(Expense, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(Expense, self.company_id) def clean(self): if self.company.settings.unique_voucher_number_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.unique_voucher_number: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) @property def total(self): grand_total = 0 for obj in self.rows.all(): total = obj.amount grand_total += total return grand_total
class PurchaseOrder(models.Model): party = models.ForeignKey(Party) order_no = models.IntegerField(blank=True, null=True) date = BSDateField(default=today, validators=[validate_in_fy]) due_days = models.IntegerField(default=3) entry_reports = GenericRelation(EntryReport, content_type_field='source_content_type_id', object_id_field='source_object_id') objects = FYManager() def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(order_no=self.order_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(PurchaseOrder, self).save(*args, **kwargs) def __init__(self, *args, **kwargs): super(PurchaseOrder, self).__init__(*args, **kwargs) if not self.pk and not self.order_no: self.order_no = get_next_voucher_no_for_fy(self.__class__, 'order_no') @property def sub_total(self): grand_total = 0 for obj in self.rows.all(): grand_total += obj.quantity * obj.rate return grand_total @property def tax_amount(self): _sum = 0 _sum = self.sub_total * 0.13 return _sum @property def total(self): amount = self.sub_total amount = self.sub_total + self.tax_amount return amount @property def fiscal_year(self): return FiscalYear.from_date(self.date) def get_entry_report(self): entry_reports = self.entry_reports.all() if len(entry_reports): return entry_reports[0] return None def get_absolute_url(self): return reverse('update_purchase_order', kwargs={'id': self.id}) def get_voucher_no(self): return self.order_no def __unicode__(self): return _('Purchase Order') + ' (' + str(self.order_no) + ')'
class ChequePayment(models.Model): cheque_number = models.CharField(max_length=50) date = BSDateField(default=today, null=True, blank=True) beneficiary = models.ForeignKey(Account) bank_account = models.ForeignKey(Account, related_name='cheque_payments') amount = models.FloatField() narration = models.TextField(null=True, blank=True) company = models.ForeignKey(Company) def get_voucher_no(self): return self.cheque_number
class Reimbursement(models.Model): date = BSDateField(null=True, blank=True, default=today, validators=[validate_in_fy]) bank_voucher_no = models.PositiveIntegerField(blank=True, null=True) wa_no = models.PositiveIntegerField(blank=True, null=True) amount = models.PositiveIntegerField(blank=True, null=True) project_fy = models.ForeignKey(ProjectFy) def __str__(self): return str(self.bank_voucher_no) + ':' + str(self.wa_no)
class DebitVoucher(models.Model): voucher_no = models.IntegerField() party = models.ForeignKey(Party, verbose_name='Paid To') date = BSDateField(default=today) reference = models.CharField(max_length=50, null=True, blank=True) amount = models.FloatField(null=True, blank=True) description = models.TextField() payment = models.ForeignKey(Account, blank=True, null=True, related_name="cash_payment") company = models.ForeignKey(Company) # statuses = [('Approved', 'Approved'), ('Unapproved', 'Unapproved')] # status = models.CharField(max_length=10, choices=statuses, default='Unapproved') def __init__(self, *args, **kwargs): super(DebitVoucher, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(DebitVoucher, self.company_id) def clean(self): if self.company.settings.unique_voucher_number_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.unique_voucher_number: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) @property def total(self): grand_total = 0 for obj in self.rows.all(): total = obj.payment grand_total += total return grand_total def get_voucher_no(self): return self.voucher_no def get_absolute_url(self): return reverse_lazy('debit_voucher_edit', kwargs={'pk': self.pk})
class ChequeDepositRow(models.Model): sn = models.IntegerField() cheque_number = models.CharField(max_length=50, blank=True, null=True) cheque_date = BSDateField(default=today, null=True, blank=True) drawee_bank = models.CharField(max_length=254, blank=True, null=True) drawee_bank_address = models.CharField(max_length=254, blank=True, null=True) amount = models.FloatField() cheque_deposit = models.ForeignKey(ChequeDeposit, related_name='rows') def get_absolute_url(self): return self.cheque_deposit.get_absolute_url() def get_voucher_no(self): return self.cheque_deposit.id
class JournalVoucher(models.Model): voucher_no = models.IntegerField() date = BSDateField(default=today) company = models.ForeignKey(Company) narration = models.TextField() statuses = [('Cancelled', 'Cancelled'), ('Approved', 'Approved'), ('Unapproved', 'Unapproved')] status = models.CharField(max_length=10, choices=statuses, default='Unapproved') def __init__(self, *args, **kwargs): super(JournalVoucher, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(JournalVoucher, self.company_id) def clean(self): if self.company.settings.unique_voucher_number_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.unique_voucher_number: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) def get_total_dr_amount(self): total_dr_amount = 0 for o in self.rows.all(): total_dr_amount += o.dr_amount return total_dr_amount def get_total_cr_amount(self): total_cr_amount = 0 for o in self.rows.all(): total_cr_amount += o.cr_amount return total_cr_amount def get_voucher_no(self): return self.voucher_no
class Inspection(models.Model): report_no = models.IntegerField() date = BSDateField(default=today, validators=[validate_in_fy]) # transaction = models.ForeignKey(Transaction, related_name='inspection') objects = FYManager() def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(report_no=self.report_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(Inspection, self).save(*args, **kwargs) @property def fiscal_year(self): return FiscalYear.from_date(self.date) def __str__(self): return unicode(self.report_no)
class JournalEntry(models.Model): date = BSDateField() content_type = models.ForeignKey(ContentType, related_name='inventory_journal_entries') model_id = models.PositiveIntegerField() creator = GenericForeignKey('content_type', 'model_id') @staticmethod def get_for(source): try: return JournalEntry.objects.get(content_type=ContentType.objects.get_for_model(source), model_id=source.id) except JournalEntry.DoesNotExist: return None def __str__(self): return str(self.content_type) + ': ' + str(self.model_id) + ' [' + str(self.date) + ']' class Meta: verbose_name_plural = u'InventoryJournal Entries'
class Expense(models.Model): voucher_no = models.PositiveIntegerField(verbose_name=_('Voucher No.')) date = BSDateField(default=today, validators=[validate_in_fy], verbose_name=_('Date')) instance = models.ForeignKey(ItemInstance) types = (('Waive', _('Waive')), ('Handover', _('Handover')), ('Auction', _('Auction'))) type = models.CharField(choices=types, max_length=20, default='Waive', verbose_name=_('Type')) rate = models.FloatField(blank=True, null=True, verbose_name=_('Rate')) objects = FYManager() def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(voucher_no=self.voucher_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(Expense, self).save(*args, **kwargs) @property def fiscal_year(self): return FiscalYear.from_date(self.date) def get_next_voucher_no(self): if not self.pk and not self.voucher_no: return get_next_voucher_no(Expense, 'voucher_no') def __init__(self, *args, **kwargs): super(Expense, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(Expense, 'voucher_no') def save(self, *args, **kwargs): created = False if not self.id: created = True super(Expense, self).save(*args, **kwargs) if created: self.instance.transfer(None, None) set_transactions(self, self.date, ['cr', self.instance.item.account, 1]) def __unicode__(self): ret = _('Expense') if self.pk: ret += ': ' + str(self.voucher_no) return unicode(ret)
class QuotationComparison(models.Model): report_no = models.IntegerField() date = BSDateField(default=today, validators=[validate_in_fy], blank=True, null=True) objects = FYManager() def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(report_no=self.report_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(QuotationComparison, self).save(*args, **kwargs) def __init__(self, *args, **kwargs): super(QuotationComparison, self).__init__(*args, **kwargs) if not self.pk and not self.report_no: self.report_no = get_next_voucher_no_for_fy(self.__class__, 'report_no') @property def fiscal_year(self): return FiscalYear.from_date(self.date)
class InstanceHistory(models.Model): instance = models.ForeignKey(ItemInstance) date = BSDateField(default=today, validators=[validate_in_fy], verbose_name=_('Date')) from_location = models.ForeignKey(ItemLocation, related_name='from_history', verbose_name=_('From Location')) to_location = models.ForeignKey(ItemLocation, related_name='to_history', null=True, verbose_name=_('To Location')) from_user = models.ForeignKey(User, related_name='from_history', null=True, blank=True, verbose_name=_('From User')) to_user = models.ForeignKey(User, related_name='to_history', null=True, blank=True, verbose_name=_('To User')) def save(self, *args, **kwargs): ret = super(InstanceHistory, self).save(*args, **kwargs) self.instance.location_id = self.to_location_id self.instance.user_id = self.to_user_id self.instance.save() return ret def __str__(self): return str(self.instance) class Meta: verbose_name_plural = _('Instance History')
class BankCashDeposit(models.Model): voucher_no = models.IntegerField() date = BSDateField(default=today) bank_account = models.ForeignKey(Account, related_name='cash_deposits') benefactor = models.ForeignKey(Account) amount = models.FloatField() deposited_by = models.CharField(max_length=254, blank=True, null=True) narration = models.TextField(null=True, blank=True) company = models.ForeignKey(Company) def __init__(self, *args, **kwargs): super(BankCashDeposit, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(BankCashDeposit, self.company_id) def get_voucher_no(self): return self.id class Meta: unique_together = ('voucher_no', 'company')
class PurchaseOrder(models.Model): party = models.ForeignKey(Party, blank=True, null=True) voucher_no = models.IntegerField(blank=True, null=True) date = BSDateField(default=today) purchase_agent = models.ForeignKey(User, related_name="purchase_order", blank=True, null=True) trade_expense = GenericRelation(TradeExpense) company = models.ForeignKey(Company) def clean(self): if self.company.settings.unique_voucher_number_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.unique_voucher_number: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) def __init__(self, *args, **kwargs): super(PurchaseOrder, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(PurchaseOrder, self.company_id) def __unicode__(self): return _('Purchase Order') + ' (' + str(self.voucher_no) + ')' @property def total(self): total = 0 for obj in self.rows.all(): total += obj.quantity * obj.rate return total
class Handover(models.Model): voucher_no = models.PositiveIntegerField(blank=True, null=True) addressee = models.CharField(max_length=254) date = BSDateField(default=today, validators=[validate_in_fy]) office = models.CharField(max_length=254) designation = models.CharField(max_length=254) handed_to = models.CharField(max_length=254) due_days = models.PositiveIntegerField(default=7) types = [('Incoming', 'Incoming'), ('Outgoing', 'Outgoing')] type = models.CharField(max_length=9, choices=types, default='Incoming') entry_reports = GenericRelation(EntryReport, content_type_field='source_content_type_id', object_id_field='source_object_id') objects = FYManager() def __init__(self, *args, **kwargs): super(Handover, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no_for_fy(self.__class__, 'voucher_no') def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(voucher_no=self.voucher_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(Handover, self).save(*args, **kwargs) @property def fiscal_year(self): return FiscalYear.from_date(self.date) def get_entry_report(self): entry_reports = self.entry_reports.all() if len(entry_reports): return entry_reports[0] return None def get_absolute_url(self): return reverse('update_handover', kwargs={'id': self.id}) def __unicode__(self): return _('Handover') + ' (' + str(self.voucher_no) + ')'
class JournalEntry(models.Model): date = BSDateField() content_type = models.ForeignKey(ContentType, related_name='inventory_journal_entries') model_id = models.PositiveIntegerField() creator = GenericForeignKey('content_type', 'model_id') # country_of_production = models.CharField(max_length=50, blank=True, null=True) # size = models.CharField(max_length=100, blank=True, null=True) # expected_life = models.CharField(max_length=100, blank=True, null=True) # source = models.CharField(max_length=100, blank=True, null=True) @staticmethod def get_for(source): try: return JournalEntry.objects.get(content_type=ContentType.objects.get_for_model(source), model_id=source.id) except JournalEntry.DoesNotExist: return None def __str__(self): return str(self.content_type) + ': ' + str(self.model_id) + ' [' + str(self.date) + ']' class Meta: verbose_name_plural = u'InventoryJournal Entries'
class StockEntry(models.Model): voucher_no = models.PositiveIntegerField(verbose_name=_('Voucher No.')) date = BSDateField(default=today, validators=[validate_in_fy], blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) objects = FYManager() def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(voucher_no=self.voucher_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(StockEntry, self).save(*args, **kwargs) def __init__(self, *args, **kwargs): super(StockEntry, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(StockEntry, 'voucher_no') def __str__(self): return str(self.voucher_no) class Meta: verbose_name_plural = 'Stock Entries'
class FixedAsset(models.Model): from_account = models.ForeignKey(Account) voucher_no = models.IntegerField() date = BSDateField(default=today) reference = models.CharField(max_length=50, null=True, blank=True) description = models.TextField(blank=True, null=True) company = models.ForeignKey(Company) # statuses = [('Approved', 'Approved'), ('Unapproved', 'Unapproved')] # status = models.CharField(max_length=10, choices=statuses, default='Unapproved') def __init__(self, *args, **kwargs): super(FixedAsset, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(FixedAsset, self.company_id) def clean(self): if self.company.settings.unique_voucher_number_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.unique_voucher_number: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) @property def total(self): grand_total = 0 for obj in self.rows.all(): total = obj.amount grand_total += total return grand_total
class Investment(models.Model): share_holder = models.ForeignKey(ShareHolder) date = BSDateField(default=today) amount = models.FloatField() collection = models.ForeignKey(Collection) company = models.ForeignKey(Company)
class PurchaseVoucher(models.Model): tax_choices = [ ('no', 'No Tax'), ('inclusive', 'Tax Inclusive'), ('exclusive', 'Tax Exclusive'), ] party = models.ForeignKey(Party, blank=True, null=True) voucher_no = models.PositiveIntegerField(blank=True, null=True) credit = models.BooleanField(default=False) date = BSDateField(default=today) tax = models.CharField(max_length=10, choices=tax_choices, default='inclusive', null=True, blank=True) tax_scheme = models.ForeignKey(TaxScheme, blank=True, null=True) due_date = BSDateField(blank=True, null=True) pending_amount = models.FloatField(null=True, blank=True) total_amount = models.FloatField(null=True, blank=True) company = models.ForeignKey(Company) discount = models.CharField(max_length=50, blank=True, null=True) purchase_order = models.ForeignKey(PurchaseOrder, blank=True, null=True, related_name='purchase_voucher') def type(self): if self.credit: return _('Credit') else: return _('Cash') def clean(self): if self.company.settings.enable_purchase_unique_voucher_no_by_fy: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).filter( date__gte=self.company.get_fy_start(self.date), date__lte=self.company.get_fy_end( self.date)).exclude(pk=self.pk): raise ValidationError( _('Voucher no. already exists for the fiscal year!')) if self.company.settings.enable_purchase_unique_voucher_no: if self.__class__.objects.filter( voucher_no=self.voucher_no, company=self.company).exclude(pk=self.pk): raise ValidationError(_('Voucher no. already exists!')) def __init__(self, *args, **kwargs): super(PurchaseVoucher, self).__init__(*args, **kwargs) if not self.pk and not self.voucher_no: self.voucher_no = get_next_voucher_no(PurchaseVoucher, self.company_id) @property def sub_total(self): grand_total = 0 for obj in self.rows.all(): total = obj.quantity * obj.rate discount = get_discount_with_percent(total, obj.discount) grand_total += total - discount return grand_total @property def tax_amount(self): _sum = 0 if self.tax_scheme: _sum = calculate_tax(self.tax, self.sub_total, self.tax_scheme.percent) else: for obj in self.rows.all(): if obj.tax_scheme: total = obj.quantity * obj.rate - float(obj.discount) amount = calculate_tax(self.tax, total, obj.tax_scheme.percent) _sum += amount return _sum @property def total(self): amount = self.sub_total if self.tax == "exclusive": amount = self.sub_total + self.tax_amount if self.discount: discount = get_discount_with_percent(amount, self.discount) amount = amount - discount return amount @property def voucher_type(self): return _('PurchaseVoucher') @property def row_discount_total(self): grand_total = 0 for obj in self.rows.all(): total = obj.quantity * obj.rate discount = get_discount_with_percent(total, obj.discount) grand_total += discount return grand_total def get_absolute_url(self): return reverse_lazy('purchase-edit', kwargs={'pk': self.pk})
class Demand(models.Model): release_no = models.IntegerField() demandee = models.ForeignKey(User, related_name='demands') date = BSDateField(default=today, validators=[validate_in_fy]) purpose = models.CharField(max_length=254) objects = FYManager() def get_voucher_no(self): return self.release_no def __init__(self, *args, **kwargs): super(Demand, self).__init__(*args, **kwargs) if not self.pk and not self.release_no: self.release_no = get_next_voucher_no_for_fy(self.__class__, 'release_no') def save(self, *args, **kwargs): if self.__class__.objects.fiscal_year().filter(release_no=self.release_no).exclude(pk=self.pk): raise ValidationError(_('Voucher no. exists!')) super(Demand, self).save(*args, **kwargs) def __str__(self): return unicode(self.release_no) @property def fiscal_year(self): return FiscalYear.from_date(self.date) @property def status(self): status_hash = { 'Requested': 0, 'Approved': 1, 'Fulfilled': 2, } status_codes = [] rows = self.rows.all() for row in rows: status_codes.append(status_hash[row.status]) if not status_codes: return _('Empty') inv_hash = {v: k for k, v in status_hash.items()} status_text = _(inv_hash[min(status_codes)]) if len(set(status_codes)) > 1: status_text = "%s %s" % (_('Partially'), _(inv_hash[max(status_codes)])) return status_text @property def status_code(self): status_hash = { 'Requested': 0, 'Approved': 1, 'Fulfilled': 2, } status_codes = [] rows = self.rows.all() for row in rows: status_codes.append(status_hash[row.status]) if not status_codes: return None status_code = str(min(status_codes)) if len(set(status_codes)) > 1: status_code = "%s%s" % ('0', str(max(status_codes))) return status_code
class Pin(models.Model): code = models.CharField(max_length=100) date = BSDateField(blank=True, null=True) company = models.ForeignKey(Company, related_name="pin") used_by = models.ForeignKey(Company, related_name="used_pin", blank=True, null=True) def __str__(self): _str = str(self.code) + '-' + self.company.name if self.used_by: _str += '-' + self.used_by.name return _str @staticmethod def generate_pin(company, count=10): pins = Pin.objects.filter(company=company, used_by__isnull=True).count() for i in range(pins, count): Pin.objects.create(company=company) def save(self, *args, **kwargs): if not self.code: self.code = str(self.company.id) + '-' + str( self.get_code(10000, 99999)) if self.used_by: self.date = today() super(Pin, self).save(*args, **kwargs) def get_code(self, range_start, range_end): if not self.code: number_range = range(range_start, range_end) code = random.choice(number_range) return code @classmethod def connect_company(cls, first_company, second_company): code = str(first_company.id) + '-' + str( random.choice(range(10000, 99999))) obj, created = cls.objects.get_or_create(company=first_company, used_by=second_company) if created: obj.code = code obj.save() @staticmethod def validate_pin(pin): try: if not isinstance(pin, str) and not isinstance(pin, unicode): return "Set argument in string" company_id = int(pin.split('-')[0]) get_pin = Pin.objects.get(company=company_id, code=pin) return get_pin.company except Pin.DoesNotExist: return None @staticmethod def companies_list(id): return Company.objects.get(pk=id) @staticmethod def accessible_companies(accessible_by): return map( Pin.companies_list, accessible_by.used_pin.all().values_list('company__id', flat=True)) @staticmethod def connected_companies(company): return map( Pin.companies_list, company.pin.filter(used_by__isnull=False).values_list( 'used_by__id', flat=True)) class Meta: unique_together = ("company", "used_by")