def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) self.fields['my_company'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['my_company'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['default_account'].queryset = Object.filter_permitted(user, Account.objects) # Translation self.fields['default_currency'].label=_('Base Currency') self.fields['my_company'].label=_('My Company') self.fields['default_account'].label=_('Default Account') try: self.fields['default_currency'].widget.attrs.update({'popuplink': reverse('finance_currency_add')}) self.fields['default_currency'].queryset = Currency.objects.all() self.fields['default_currency'].initial = Currency.objects.get(is_default=True) except Exception: pass try: conf = ModuleSetting.get_for_module('treeio.finance', 'my_company')[0] my_company = Contact.objects.get(pk=long(conf.value)) self.fields['my_company'].initial = my_company.id except Exception: pass try: conf = ModuleSetting.get_for_module('treeio.finance', 'default_account')[0] default_account = Account.objects.get(pk=long(conf.value)) self.fields['default_account'].initial = default_account.id except Exception: pass
def queue_delete(request, queue_id, response_format='html'): "Queue delete" queue = get_object_or_404(TicketQueue, pk=queue_id) if not request.user.get_profile().has_permission(queue, mode='w'): return user_denied(request, message="You don't have access to this Queue") if request.POST: if 'delete' in request.POST: if 'trash' in request.POST: queue.trash = True queue.save() else: queue.delete() return HttpResponseRedirect(reverse('services_settings_view')) elif 'cancel' in request.POST: return HttpResponseRedirect(reverse('services_queue_view', args=[queue.id])) query = Q(queue=queue) & Q(status__hidden=False) tickets = Object.filter_by_request(request, Ticket.objects.filter(query)) subqueues = Object.filter_by_request( request, TicketQueue.objects.filter(parent=queue)) context = _get_default_context(request) context.update({'queue': queue, 'subqueues': subqueues, 'tickets': tickets}) return render_to_response('services/queue_delete', context, context_instance=RequestContext(request), response_format=response_format)
def index(request, response_format='html'): "Messaging index page" query = Q(reply_to__isnull=True) streams = False st = MessageStream.objects.all() for row in st: if request.user.get_profile().has_permission(row): if streams: streams = streams | Q(stream=row) else: streams = Q(stream=row) if streams: query = query & streams if request.GET: query = query & _get_filter_query(request.GET) messages = Object.filter_by_request(request, Message.objects.filter(query)) else: messages = Object.filter_by_request(request, Message.objects.filter(query)) filters = FilterForm(request.user.get_profile(), 'title', request.GET) context = _get_default_context(request) context.update({'filters': filters, 'messages': messages}) return render_to_response('messaging/index', context, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, parent=None, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['supplier'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['supplier'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['supplier'].widget.attrs.update({'popuplink': reverse('identities_contact_add')}) self.fields['supplier'].label = _("Supplier") self.fields['active'].initial = True self.fields['active'].label = _("Active") manager = Product.objects.filter(active=True) if 'instance' in kwargs: instance = kwargs['instance'] manager = manager.exclude(Q(parent=instance) & Q(pk=instance.id)) self.fields['parent'].queryset = Object.filter_permitted(user, manager, mode='x') if parent: self.fields['parent'].initial = get_object_or_404(Product, pk=parent) self.fields['parent'].label = _("Parent") self.fields['product_type'].label = _("Product type") self.fields['code'].label = _("Code") self.fields['supplier_code'].label = _("Supplier code") self.fields['buy_price'].label = _("Buy price") self.fields['sell_price'].label = _("Sell price") self.fields['stock_quantity'].label = _("Stock quantity") self.fields['runout_action'].label = _("Runout action") self.fields['details'].label = _("Details")
def __init__(self, user, order, *args, **kwargs): super(OrderedProductForm, self).__init__(*args, **kwargs) self.fields['subscription'].queryset = Object.filter_permitted(user, Subscription.objects) self.fields['subscription'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('sales_ajax_subscription_lookup')}) self.fields['subscription'].widget.attrs.update({'popuplink': reverse('sales_subscription_add')}) self.fields['subscription'].label = _("Subscription") self.fields['product'].queryset = Object.filter_permitted(user, Product.objects.filter(active=True)) if user.is_admin('treeio.sales'): self.fields['product'].widget.attrs.update({'popuplink': reverse('sales_product_add')}) self.fields['product'].label = _("Product") try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_product')[0] # AJAX to set the initial rate as the currency converted value of product sell price self.fields['product'].initial = long(conf.value) except: pass # Tax self.fields['tax'].widget.attrs.update({'popuplink': reverse('finance_tax_add')}) # TODO: rate # self.fields['rate_display'].label = _("Rate") # self.fields['rate_display'].help_text = order.currency.code self.fields['quantity'].label = _("Quantity") self.fields['quantity'].initial = 1 self.fields['discount'].label = _("Discount") self.fields['discount'].help_text = "%"
def queue_view(request, queue_id, response_format='html'): "Queue view" queue = get_object_or_404(TicketQueue, pk=queue_id) if not request.user.get_profile().has_permission(queue): return user_denied(request, message="You don't have access to this Queue") query = Q(queue=queue) if request.GET: if 'status' in request.GET and request.GET['status']: query = query & _get_filter_query(request.GET) else: query = query & Q( status__hidden=False) & _get_filter_query(request.GET) else: query = query & Q(status__hidden=False) tickets = Object.filter_by_request(request, Ticket.objects.filter(query)) filters = FilterForm(request.user.get_profile(), 'queue', request.GET) subqueues = Object.filter_by_request( request, TicketQueue.objects.filter(parent=queue)) context = _get_default_context(request) context.update({'queue': queue, 'subqueues': subqueues, 'filters': filters, 'tickets': tickets}) return render_to_response('services/queue_view', context, context_instance=RequestContext(request), response_format=response_format)
def task_time_slot_add(request, task_id, response_format='html'): "Time slot add to preselected task" task = get_object_or_404(Task, pk=task_id) if not request.user.get_profile().has_permission(task, mode='x'): return user_denied(request, message="You don't have access to this Task") if request.POST: task_time_slot = TaskTimeSlot( task=task, time_to=datetime.now(), user=request.user.get_profile()) form = TaskTimeSlotForm( request.user.get_profile(), task_id, request.POST, instance=task_time_slot) if 'cancel' in request.POST: return HttpResponseRedirect(reverse('projects_task_view', args=[task.id])) elif form.is_valid(): task_time_slot = form.save() task_time_slot.set_user_from_request(request) return HttpResponseRedirect(reverse('projects_task_view', args=[task.id])) else: form = TaskTimeSlotForm(request.user.get_profile(), task_id) subtasks = Object.filter_by_request( request, Task.objects.filter(parent=task)) time_slots = Object.filter_by_request( request, TaskTimeSlot.objects.filter(task=task)) context = _get_default_context(request) context.update({'form': form, 'task': task, 'subtasks': subtasks, 'time_slots': time_slots}) return render_to_response('projects/task_time_add', context, context_instance=RequestContext(request), response_format=response_format)
def task_delete(request, task_id, response_format='html'): "Task delete" task = get_object_or_404(Task, pk=task_id) if not request.user.get_profile().has_permission(task, mode='w'): return user_denied(request, message="You don't have access to this Task") if request.POST: if 'delete' in request.POST: if 'trash' in request.POST: task.trash = True task.save() else: task.delete() return HttpResponseRedirect(reverse('projects_index')) elif 'cancel' in request.POST: return HttpResponseRedirect(reverse('projects_task_view', args=[task.id])) subtasks = Object.filter_by_request( request, Task.objects.filter(parent=task)) time_slots = Object.filter_by_request( request, TaskTimeSlot.objects.filter(task=task)) context = _get_default_context(request) context.update({'task': task, 'subtasks': subtasks, 'time_slots': time_slots}) return render_to_response('projects/task_delete', context, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, project_id, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['parent'].queryset = Object.filter_permitted( user, Project.objects, mode='x') self.fields['parent'].label = _("Parent") if project_id: self.fields['parent'].initial = project_id self.fields['manager'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['manager'].label = _("Manager") self.fields['manager'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['manager'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['client'].label = _("Client") self.fields['client'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['client'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['client'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['details'].label = _("Details")
def index(request, response_format='html'): "Project Management index page" query = Q(parent__isnull=True) if request.GET: if 'status' in request.GET and request.GET['status']: query = query & _get_filter_query(request.GET) else: query = query & Q( status__hidden=False) & _get_filter_query(request.GET) else: query = query & Q(status__hidden=False) tasks = Object.filter_by_request(request, Task.objects.filter(query)) milestones = Object.filter_by_request( request, Milestone.objects.filter(status__hidden=False)) filters = FilterForm(request.user.get_profile(), '', request.GET) context = _get_default_context(request) context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters}) return render_to_response('projects/index', context, context_instance=RequestContext(request), response_format=response_format)
def project_view(request, project_id, response_format='html'): "Single project view page" project = get_object_or_404(Project, pk=project_id) if not request.user.get_profile().has_permission(project): return user_denied(request, message="You don't have access to this Project") query = Q(parent__isnull=True, project=project) if request.GET: if 'status' in request.GET and request.GET['status']: query = query & _get_filter_query(request.GET) else: query = query & Q(status__hidden=False) & _get_filter_query(request.GET) else: query = query & Q(status__hidden=False) if request.user.get_profile().has_permission(project, mode='r'): if request.POST: record = UpdateRecord() record.record_type = 'manual' form = TaskRecordForm(request.user.get_profile(), request.POST, instance=record) if form.is_valid(): record = form.save() record.set_user_from_request(request) record.save() record.about.add(project) project.set_last_updated() return HttpResponseRedirect(reverse('projects_project_view', args=[project.id])) else: form = TaskRecordForm(request.user.get_profile()) else: form = None tasks = Object.filter_by_request(request, Task.objects.filter(query)) tasks_progress = float(0) tasks_progress_query = Object.filter_by_request(request, Task.objects.filter(Q(parent__isnull=True, project=project))) if tasks_progress_query: for task in tasks_progress_query: if not task.status.active: tasks_progress += 1 tasks_progress = (tasks_progress / len(tasks_progress_query)) * 100 tasks_progress = round(tasks_progress, ndigits=1) filters = FilterForm(request.user.get_profile(), 'project', request.GET) milestones = Object.filter_by_request(request, Milestone.objects.filter(project=project).filter(status__hidden=False)) subprojects = Project.objects.filter(parent=project) context = _get_default_context(request) context.update({'project': project, 'milestones': milestones, 'tasks':tasks, 'tasks_progress':tasks_progress, 'record_form':form, 'subprojects':subprojects, 'filters': filters}) return render_to_response('projects/project_view', context, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, skip=[], *args, **kwargs): super(OrderFilterForm, self).__init__(*args, **kwargs) if 'status' in skip: del self.fields['status'] else: self.fields['status'].queryset = Object.filter_permitted(user, SaleStatus.objects.filter(use_sales=True)) self.fields['status'].required = False self.fields['status'].label = _("Status") self.fields['paid'].label = _("Payment Status") self.fields['client'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['client'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['client'].required = False self.fields['client'].label = _("Client") self.fields['source'].queryset = Object.filter_permitted(user, SaleSource.objects.filter(active=True)) self.fields['source'].required = False self.fields['source'].label = _("Source") if 'assigned' in skip: del self.fields['assigned'] else: self.fields['assigned'].label = _("Assigned to") self.fields['assigned'].help_text = "" self.fields['assigned'].required = False self.fields['assigned'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_user_lookup')})
def folder_view(request, folder_id, response_format='html'): "Single folder view page" folder = get_object_or_404(Folder, pk=folder_id) if not request.user.get_profile().has_permission(folder): return user_denied(request, message="You don't have access to this Folder") query = Q( object_type='treeio.documents.models.Document') | Q( object_type='treeio.documents.models.File') | Q( object_type='treeio.documents.models.WebLink') query = query & (Q(document__folder=folder) | Q(file__folder=folder) | Q(weblink__folder=folder)) if request.GET: query = query & _get_filter_query(request.GET) objects = Object.filter_by_request(request, Object.objects.filter(query).order_by('-last_updated')) # objects = objects.order_by('-last_updated') else: objects = Object.filter_by_request(request, Object.objects.filter(query).order_by('-last_updated')) # objects = objects.order_by('-last_updated') subfolders = Folder.objects.filter(parent=folder) filters = FilterForm(request.user.get_profile(), 'title', request.GET) context = _get_default_context(request) context.update({'folder': folder, 'objects':objects, 'subfolders':subfolders, 'filters':filters}) return render_to_response('documents/folder_view', context, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, *args, **kwargs): super(LiabilityForm, self ).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['category'].label = _("Category") self.fields['source'].label = _("Source") self.fields['target'].label = _("Target") self.fields['account'].label = _("Bank Account") self.fields['due_date'].label = _("Due date") self.fields['value_currency'].label = _("Currency") self.fields['value_currency'].widget.attrs.update({'popuplink': reverse('finance_currency_add')}) self.fields['value_currency'].initial = Currency.objects.get(is_default=True) self.fields['value_display'].label = _("Value") self.fields['details'].label = _("Details") self.fields['target'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['target'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['target'].widget.attrs.update({'popuplink': reverse('identities_contact_add')}) self.fields['account'].queryset = Object.filter_permitted(user, Account.objects) try: conf = ModuleSetting.get_for_module('treeio.finance', 'default_account')[0] self.fields['account'].initial = long(conf.value) except Exception: pass self.fields['due_date'].widget.attrs.update({'class': 'datepicker'}) del self.fields['source']
def __init__(self, user, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) del self.fields['cycle_end'] self.fields['product'].queryset = Object.filter_permitted(user, Product.objects) self.fields['product'].label = _("Product") self.fields['client'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['client'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['client'].widget.attrs.update({'popuplink': reverse('identities_contact_add')}) self.fields['client'].label = _("Client") self.fields['start'].widget.attrs.update({'class': 'datepicker'}) self.fields['start'].label = _("Start") self.fields['expiry'].widget.attrs.update({'class': 'datepicker'}) self.fields['expiry'].label = _("Expiry") if 'instance' in kwargs: self.instance = kwargs['instance'] self.fields['start'].widget.attrs['readonly'] = True del kwargs['instance'] self.fields['active'].initial = True self.fields['active'].label = _("Active") self.fields['cycle_period'].label = _("Cycle period") self.fields['details'].label = _("Details")
def __init__(self, user, *args, **kwargs): "Sets allowed values" super(QueueForm, self).__init__(*args, **kwargs) manager = TicketQueue.objects if 'instance' in kwargs: instance = kwargs['instance'] manager = manager.exclude(Q(parent=instance) & Q(pk=instance.id)) self.fields['parent'].queryset = Object.filter_permitted( user, manager, mode='x') self.fields['default_service'].queryset = Object.filter_permitted( user, Service.objects, mode='x') self.fields['waiting_time'].help_text = "seconds" self.fields['name'].label = _("Name") self.fields['active'].label = _("Active") self.fields['parent'].label = _("Parent") self.fields['default_ticket_status'].label = _("Default ticket status") self.fields['default_ticket_priority'].label = _( "Default ticket priority") self.fields['default_service'].label = _("Default service") self.fields['waiting_time'].label = _("Waiting time") self.fields['next_queue'].queryset = Object.filter_permitted( user, TicketQueue.objects, mode='x') self.fields['next_queue'].label = _("Next queue") self.fields['ticket_code'].label = _("Ticket code") self.fields['message_stream'].label = _("Message stream") self.fields['message_stream'].widget.attrs.update( {'popuplink': reverse('messaging_stream_add')}) self.fields['details'].label = _("Details")
def __init__(self, user, *args, **kwargs): super(EquityForm, self).__init__(*args, **kwargs) self.fields['equity_type'].label = _("Equity type") self.fields['issue_price'].label = _("Issue price") self.fields['sell_price'].label = _("Sell price") self.fields['issuer'].label = _("Issuer") self.fields['owner'].label = _("Owner") self.fields['amount'].label = _("Quantity") self.fields['purchase_date'].label = _("Purchase date") self.fields['details'].label = _("Details") self.fields['owner'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['owner'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['owner'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['issuer'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['issuer'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['issuer'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) try: conf = ModuleSetting.get_for_module( 'treeio.finance', 'my_company')[0] self.fields['issuer'].initial = long(conf.value) except Exception: pass self.fields['purchase_date'].widget.attrs.update( {'class': 'datepicker'})
def __init__(self, user, project_id, *args, **kwargs): super(MilestoneForm, self ).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['project'].label = _("Project") self.fields['project'].queryset = Object.filter_permitted(user, Project.objects, mode='x') if project_id: self.fields['project'].initial = project_id self.fields['status'].label = _("Status") self.fields['status'].queryset = Object.filter_permitted(user, TaskStatus.objects, mode='x') try: conf = ModuleSetting.get_for_module('treeio.projects', 'default_task_status')[0] self.fields['status'].initial = long(conf.value) except Exception: pass # Set datepicker self.fields['start_date'].label = _("Start date") self.fields['start_date'].widget.attrs.update({'class': 'datetimepicker'}) self.fields['end_date'].label = _("End date") self.fields['end_date'].widget.attrs.update({'class': 'datetimepicker'}) if 'instance' in kwargs: instance = kwargs['instance'] if instance.start_date: self.fields['start_date'].widget.attrs.update({'initial': instance.start_date.strftime('%s')}) if instance.end_date: self.fields['end_date'].widget.attrs.update({'initial': instance.end_date.strftime('%s')}) self.fields['details'].label = _("Details")
def get_events(request): "Return a list of EventRenderers from available Tasks and Milestones" events = [] query = (Q(start_date__isnull=False) | Q(end_date__isnull=False)) & Q( status__hidden=False) tasks = Object.filter_by_request( request, manager=Task.objects.filter(query)) for task in tasks: if task.end_date: event = EventRenderer( task.name, task.start_date, task.end_date, task.get_absolute_url()) else: event = EventRenderer( task.name, None, task.start_date, task.get_absolute_url()) event.css_class += " projects-calendar-task" events.append(event) query = (Q(start_date__isnull=False) | Q(end_date__isnull=False)) & Q( status__hidden=False) milestones = Object.filter_by_request( request, manager=Milestone.objects.filter(query)) for milestone in milestones: name = " " + milestone.name if milestone.end_date: event = EventRenderer(name, milestone.start_date, milestone.end_date, milestone.get_absolute_url()) else: event = EventRenderer( name, None, milestone.start_date, milestone.get_absolute_url()) event.css_class += " projects-calendar-milestone" events.append(event) return events
def __init__(self, user, skip=[], *args, **kwargs): super(LeadFilterForm, self).__init__(*args, **kwargs) self.fields['contact'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['contact'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['contact'].required = False self.fields['contact'].label = _("Contact") self.fields['products_interested'].queryset = Object.filter_permitted(user, Product.objects) self.fields['products_interested'].required = False self.fields['products_interested'].help_text = "" self.fields['products_interested'].label = _("Products interested") self.fields['source'].queryset = Object.filter_permitted(user, SaleSource.objects.filter(active=True)) self.fields['source'].required = False self.fields['source'].label = _("Source") self.fields['status'].queryset = Object.filter_permitted(user, SaleStatus.objects.filter(use_leads=True)) self.fields['status'].required = False self.fields['status'].label = _("Status") self.fields['contact_method'].required = False self.fields['contact_method'].label = _("Contact method")
def contact_view(request, contact_id, attribute='', response_format='html'): "Contact view" contact = get_object_or_404(Contact, pk=contact_id) if not request.user.get_profile().has_permission(contact): return user_denied(request, message="You don't have access to this Contact") types = Object.filter_by_request(request, ContactType.objects.order_by('name')) subcontacts = Object.filter_by_request(request, contact.child_set) contact_values = contact.contactvalue_set.order_by('field__name') objects = get_contact_objects(request.user.get_profile(), contact, preformat=True) module = None for key in objects: if not attribute: if objects[key]['count']: #attribute = objects[key]['objects'].keys()[0] module = objects[key]['module'] else: if attribute in objects[key]['objects'].keys(): module = objects[key]['module'] break return render_to_response('identities/contact_view', {'contact': contact, 'subcontacts': subcontacts, 'objects': objects, 'current_module': module, 'attribute': attribute, 'types': types, 'contact_values': contact_values}, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, skip=[], *args, **kwargs): super(FilterForm, self).__init__(*args, **kwargs) if 'title' in skip: del self.fields['title'] else: self.fields['title'].required = False self.fields['title'].label = _("Title") if 'stream' in skip: del self.fields['stream'] else: self.fields['stream'].queryset = Object.filter_permitted( user, MessageStream.objects, mode='x') self.fields['stream'].required = False self.fields['stream'].label = _("Stream") if 'author' in skip: del self.fields['author'] else: self.fields['author'].required = False self.fields['author'].label = _("Author") self.fields['author'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['author'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')})
def index_by_status(request, status_id, response_format='html'): "Sort tasks by status" status = get_object_or_404(TaskStatus, pk=status_id) if not request.user.get_profile().has_permission(status): return user_denied(request, message="You don't have access to this Task Status") query = Q(parent__isnull=True, status=status) if request.GET: query = query & _get_filter_query(request.GET) tasks = Object.filter_by_request(request, Task.objects.filter(query)) milestones = Object.filter_by_request( request, Milestone.objects.filter(task__status=status).distinct()) filters = FilterForm(request.user.get_profile(), 'status', request.GET) context = _get_default_context(request) context.update({'milestones': milestones, 'tasks': tasks, 'status': status, 'filters': filters}) return render_to_response('projects/index_by_status', context, context_instance=RequestContext(request), response_format=response_format)
def index_in_progress(request, response_format='html'): "A page with a list of tasks in progress" query = Q(parent__isnull=True) if request.GET: query = query & Q( status__hidden=False) & _get_filter_query(request.GET) else: query = query & Q(status__hidden=False) tasks = Object.filter_by_request(request, Task.objects.filter(query)) milestones = Object.filter_by_request( request, Milestone.objects.filter(status__hidden=False)) filters = FilterForm(request.user.get_profile(), 'status', request.GET) time_slots = Object.filter_by_request( request, TaskTimeSlot.objects.filter(time_from__isnull=False, time_to__isnull=True)) context = _get_default_context(request) context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters, 'time_slots': time_slots}) return render_to_response('projects/index_in_progress', context, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, skip=[], *args, **kwargs): super(LiabilityFilterForm, self).__init__(*args, **kwargs) if 'due_date_from' in skip: del self.fields['due_date_from'] else: self.fields['due_date_from'] = forms.DateField( label=_("Due Date From:"), required=False) self.fields['due_date_from'].widget.attrs.update( {'class': 'datepicker'}) if 'due_date_to' in skip: del self.fields['due_date_to'] else: self.fields['due_date_to'] = forms.DateField( label=_("Due Date To:"), required=False) self.fields['due_date_to'].widget.attrs.update( {'class': 'datepicker'}) if 'category' in skip: del self.fields['category'] else: self.fields['category'].queryset = Object.filter_permitted( user, Category.objects) self.fields['category'].label = _("Category") self.fields['category'].help_text = "" self.fields['category'].required = False if 'source' in skip: del self.fields['source'] else: self.fields['source'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['source'].label = _("Source") self.fields['source'].help_text = "" self.fields['source'].required = False self.fields['source'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) if 'target' in skip: del self.fields['target'] else: self.fields['target'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['target'].required = False self.fields['target'].label = _("Target") self.fields['target'].help_text = "" self.fields['target'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) if 'account' in skip: del self.fields['account'] else: self.fields['account'].queryset = Object.filter_permitted( user, Account.objects) self.fields['account'].required = False self.fields['account'].label = _("Account") self.fields['account'].help_text = ""
def __init__(self, user, lead, *args, **kwargs): super(OpportunityForm, self).__init__(*args, **kwargs) self.fields['lead'].queryset = Object.filter_permitted(user, Lead.objects) self.fields['contact'].queryset = Object.filter_permitted(user, Contact.objects) self.fields['contact'].widget.attrs.update({'popuplink': reverse('identities_contact_add')}) self.fields['contact'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')}) self.fields['products_interested'].queryset = Object.filter_permitted(user, Product.objects) self.fields['products_interested'].widget.attrs.update({'popuplink': reverse('sales_product_add')}) try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_product')[0] self.fields['products_interested'].initial = [long(conf.value)] except: pass self.fields['source'].queryset = Object.filter_permitted(user, SaleSource.objects.filter(active=True)) self.fields['status'].queryset = Object.filter_permitted(user, SaleStatus.objects.filter(use_opportunities=True)) self.fields['assigned'].widget.attrs.update({'class': 'multicomplete', 'callback': reverse('identities_ajax_user_lookup')}) try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_opportunity_status')[0] self.fields['status'].initial = long(conf.value) except: pass if lead: self.fields['lead'].initial = lead.id self.fields['contact'].initial = lead.contact_id self.fields['products_interested'].initial = [i.id for i in lead.products_interested.only('id')] self.fields['source'].initial = lead.source_id self.fields['assigned'].initial = [i.id for i in lead.assigned.only('id')] else: del self.fields['lead'] self.fields['products_interested'].help_text = "" self.fields['assigned'].help_text = "" self.fields['expected_date'].widget.attrs.update({'class': 'datepicker'}) self.fields['closed_date'].widget.attrs.update({'class': 'datepicker'}) self.fields['contact'].label = _("Contact") self.fields['products_interested'].label = _("Products interested") self.fields['source'].label = _("Source") self.fields['expected_date'].label = _("Expected date") self.fields['closed_date'].label = _("Closed date") self.fields['assigned'].label = _("Assigned to") self.fields['amount_display'].label = _("Amount") self.fields['amount_currency'].label = _("Currency") self.fields['amount_currency'].widget.attrs.update({'popuplink': reverse('finance_currency_add')}) self.fields['amount_currency'].initial = Currency.objects.get(is_default=True) self.fields['probability'].label = _("Probability") self.fields['status'].label = _("Status") self.fields['details'].label = _("Details")
def _find_duplicates(resource_id, item, user): "Finds matching items" dups = [] item_id = None if 'id' in item.raw: item_id = item.id.raw # Finding previously syncd items if item_id: key = '#' + unicode(resource_id) + '.' + unicode(item_id) + '#' dups = Object.filter_permitted(user, Contact.objects).filter( nuvius_resource__contains=key) if dups: return dups # Finding equivalent items # If name and (email or phone) are the same - it's same person if item.name: candidates = Object.filter_permitted( user, Contact.objects).filter(name=item.name.raw).distinct() dups = [] if candidates and (item.email or item.phone): for candidate in candidates: matching_emails = [] emails = candidate.contactvalue_set.filter( field__field_type='email') if item.email.raw and emails: matching_emails = emails.filter(value__in=item.email.raw) phones = candidate.contactvalue_set.filter( field__field_type='phone') matching_phones = [] if item.phone.raw and phones: matching_phones = phones.filter(value__in=item.phone.raw) # If anything matches or if we have no emails or no phones at # all - add to duplicates if matching_emails or matching_phones or (not emails and not phones): dups.append(candidate) elif not candidates and (item.email or item.phone): query = Q() if item.email: query = query & Q(contactvalue__value__in=item.email.raw) if item.phone: query = query | Q(contactvalue__value__in=item.phone.raw) dups = Object.filter_permitted( user, Contact.objects).filter(query).distinct() else: dups = candidates elif item.email or item.phone: query = Q() if item.email: query = query & Q(contactvalue__value__in=item.email.raw) if item.phone: query = query & Q(contactvalue__value__in=item.phone.raw) dups = Object.filter_permitted(user, Contact.objects).filter(query) return dups
def _get_default_context(request): "Returns default context as a dict()" projects = Object.filter_by_request(request, Project.objects) statuses = Object.filter_by_request(request, TaskStatus.objects) massform = MassActionForm(request.user.get_profile()) context = {'projects': projects, 'statuses': statuses, 'massform': massform} return context
def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) # Translate self.fields['default_ticket_status'].label = _('Default Ticket Status') self.fields['default_ticket_queue'].label = _('Default Queue') self.fields['send_email_to_caller'].label = _( "Notify Caller By E-mail") self.fields['send_email_template'].label = _("E-mail Template") self.fields['default_ticket_status'].queryset = Object.filter_permitted( user, TicketStatus.objects, mode='x') self.fields['default_ticket_queue'].queryset = Object.filter_permitted( user, TicketQueue.objects, mode='x') try: conf = ModuleSetting.get_for_module( 'treeio.services', 'default_ticket_status')[0] default_ticket_status = TicketStatus.objects.get( pk=long(conf.value)) self.fields[ 'default_ticket_status'].initial = default_ticket_status.id except Exception: pass try: conf = ModuleSetting.get_for_module( 'treeio.services', 'default_ticket_queue')[0] default_ticket_queue = TicketQueue.objects.get(pk=long(conf.value)) self.fields[ 'default_ticket_queue'].initial = default_ticket_queue.id except Exception: pass try: conf = ModuleSetting.get_for_module( 'treeio.services', 'send_email_to_caller')[0] self.fields['send_email_to_caller'].initial = conf.value except: self.fields[ 'send_email_to_caller'].initial = settings.HARDTREE_SEND_EMAIL_TO_CALLER # notification template try: conf = ModuleSetting.get_for_module( 'treeio.services', 'send_email_template')[0] self.fields['send_email_template'].initial = conf.value except Exception: self.fields['send_email_template'].initial = get_template_source( 'services/emails/notify_caller.html')
def __init__(self, user, *args, **kwargs): super(ItemTypeForm, self).__init__(*args, **kwargs) self.fields["name"].label = _("Name") self.fields["parent"].label = _("Parent") self.fields["fields"].label = _("Fields") self.fields["details"].label = _("Details") self.fields["fields"].queryset = Object.filter_permitted(user, ItemField.objects.all(), mode="x") self.fields["fields"].help_text = "" self.fields["parent"].queryset = Object.filter_permitted( user, ItemType.objects.all().exclude(pk=self.instance.id), mode="x" )
def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) self.fields['default_lead_status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_leads=True)) self.fields[ 'default_opportunity_status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_opportunities=True)) self.fields['default_order_status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_sales=True)) self.fields['default_order_source'].queryset = Object.filter_permitted( user, SaleSource.objects.all()) self.fields['order_fulfil_status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_sales=True)) self.fields[ 'default_order_product'].queryset = Object.filter_permitted( user, Product.objects.filter(active=True)) # Translation self.fields['default_currency'].label = _('Base Currency') self.fields['default_lead_status'].label = _('Default Lead Status') self.fields['default_opportunity_status'].label = _( 'Default Opportunity Status') self.fields['default_order_status'].label = _('Default Order Status') self.fields['default_order_source'].label = _('Default Order Source') self.fields['default_order_product'].label = _('Default Order Product') self.fields['order_fulfil_status'].label = _('Order Fulfilment Status') try: self.fields['default_currency'].queryset = Currency.objects self.fields['default_currency'].initial = Currency.objects.get( is_default__exact=True) self.fields['default_currency'].widget.attrs.update( {'popuplink': reverse('sales_currency_add')}) except: pass try: conf = ModuleSetting.get_for_module( 'treeio.sales', 'default_opportunity_status')[0] default_opportunity_status = SaleStatus.objects.get( pk=long(conf.value)) self.fields[ 'default_opportunity_status'].initial = default_opportunity_status.id except: pass try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_lead_status')[0] default_lead_status = SaleStatus.objects.get(pk=long(conf.value)) self.fields['default_lead_status'].initial = default_lead_status.id except: pass try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_status')[0] default_order_status = SaleStatus.objects.get(pk=long(conf.value)) self.fields[ 'default_order_status'].initial = default_order_status.id except: pass try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_source')[0] default_order_source = SaleSource.objects.get(pk=long(conf.value)) self.fields[ 'default_order_source'].initial = default_order_source.id except: pass try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_product')[0] default_order_product = Product.objects.get(pk=long(conf.value)) self.fields[ 'default_order_product'].initial = default_order_product.id except: pass try: conf = ModuleSetting.get_for_module('treeio.sales', 'order_fulfil_status')[0] order_fulfil_status = SaleStatus.objects.get(pk=long(conf.value)) self.fields['order_fulfil_status'].initial = order_fulfil_status.id except: pass
def __init__(self, user, lead, *args, **kwargs): super(OpportunityForm, self).__init__(*args, **kwargs) self.fields['lead'].queryset = Object.filter_permitted( user, Lead.objects) self.fields['contact'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['contact'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['contact'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['products_interested'].queryset = Object.filter_permitted( user, Product.objects) self.fields['products_interested'].widget.attrs.update( {'popuplink': reverse('sales_product_add')}) try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_product')[0] self.fields['products_interested'].initial = [long(conf.value)] except: pass self.fields['source'].queryset = Object.filter_permitted( user, SaleSource.objects.filter(active=True)) self.fields['status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_opportunities=True)) self.fields['assigned'].widget.attrs.update({ 'class': 'multicomplete', 'callback': reverse('identities_ajax_user_lookup') }) try: conf = ModuleSetting.get_for_module( 'treeio.sales', 'default_opportunity_status')[0] self.fields['status'].initial = long(conf.value) except: pass if lead: self.fields['lead'].initial = lead.id self.fields['contact'].initial = lead.contact_id self.fields['products_interested'].initial = [ i.id for i in lead.products_interested.only('id') ] self.fields['source'].initial = lead.source_id self.fields['assigned'].initial = [ i.id for i in lead.assigned.only('id') ] else: del self.fields['lead'] self.fields['products_interested'].help_text = "" self.fields['assigned'].help_text = "" self.fields['expected_date'].widget.attrs.update( {'class': 'datepicker'}) self.fields['closed_date'].widget.attrs.update({'class': 'datepicker'}) self.fields['contact'].label = _("Contact") self.fields['products_interested'].label = _("Products interested") self.fields['source'].label = _("Source") self.fields['expected_date'].label = _("Expected date") self.fields['closed_date'].label = _("Closed date") self.fields['assigned'].label = _("Assigned to") self.fields['amount_display'].label = _("Amount") self.fields['amount_currency'].label = _("Currency") self.fields['amount_currency'].widget.attrs.update( {'popuplink': reverse('finance_currency_add')}) self.fields['amount_currency'].initial = Currency.objects.get( is_default=True) self.fields['probability'].label = _("Probability") self.fields['status'].label = _("Status") self.fields['details'].label = _("Details")
def widget_week_view(request, response_format='html'): "Week view - each slot represents an hour" events = Object.filter_by_request(request, Event.objects) date_current = now = datetime.now() istoday = True gotoform = GoToDateForm(now, request.GET) if request.GET: if 'date_year' in request.GET and 'date_month' in request.GET and 'date_day' in request.GET: try: day = int(request.GET['date_day']) year = int(request.GET['date_year']) month = int(request.GET['date_month']) if year >= 1900 and month >= 1 and month <= 12 and day >= 1 and day <= 31: date_current = datetime(year, month, day) istoday = date_current == now except Exception: pass if gotoform.is_valid() and gotoform.cleaned_data['goto']: date_current = gotoform.cleaned_data['goto'] istoday = date_current == now date_current = now = datetime(date_current.year, date_current.month, date_current.day) date_previous = date_current - relativedelta(weeks=+1) date_next = date_current + relativedelta(weeks=+1) weeks = calendar.Calendar().monthdatescalendar(date_current.year, date_current.month) current_week = [] for week in weeks: if date_current.date() in week: current_week = week break wrapped_events = EventCollection(events, START_HOUR, END_HOUR) wrapped_events.collect_events(request) dates = calendar.Calendar().monthdatescalendar(date_current.year, date_current.month) wrapped_events = EventCollection(events) wrapped_events.collect_events(request) return render_to_response('events/widgets/week_view', { 'events': wrapped_events, 'dates': dates, 'week': current_week, 'date_previous': date_previous, 'date_next': date_next, 'start_date': current_week[0], 'end_date': current_week[6], 'date_current': date_current, 'gotoform': gotoform.as_ul(), 'istoday': istoday, 'now': now }, context_instance=RequestContext(request), response_format=response_format)
def __init__(self, user, liability_id=None, order_id=None, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Description") self.fields['category'].label = _("Category") self.fields['source'].label = _("Source") self.fields['target'].label = _("Target") self.fields['account'].label = _("Bank Account") self.fields['datetime'].label = _("Date & Time") self.fields['value_currency'].label = _("Currency") self.fields['value_currency'].widget.attrs.update( {'popuplink': reverse('finance_currency_add')}) self.fields['value_currency'].initial = Currency.objects.get( is_default=True) self.fields['value_display'].label = _("Value") self.fields['details'].label = _("Details") self.fields['source'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['target'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['source'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['target'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['source'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['target'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['datetime'].widget.attrs.update( {'class': 'datetimepicker'}) self.fields['account'].queryset = Object.filter_permitted( user, Account.objects) try: conf = ModuleSetting.get_for_module('treeio.finance', 'default_account')[0] self.fields['account'].initial = long(conf.value) except Exception: pass self.fields['liability'].queryset = Object.filter_permitted( user, Liability.objects) self.fields['liability'].label = _("Liability / Receivable") if order_id: order = get_object_or_404(SaleOrder, pk=order_id) self.fields['name'].initial = order.reference if order.client: self.fields['source'].initial = order.client # default company try: conf = ModuleSetting.get_for_module('treeio.finance', 'my_company')[0] self.fields['target'].initial = Contact.objects.get( pk=long(conf.value)) except Exception: pass self.fields['details'].initial = order.details self.fields['value_display'].initial = order.balance_due() self.fields['value_currency'].initial = order.currency if liability_id: self.fields['liability'].initial = liability_id liability = get_object_or_404(Liability, pk=liability_id) self.fields['name'].initial = liability.name self.fields['source'].initial = liability.source self.fields['target'].initial = liability.target self.fields['details'].initial = liability.details self.fields['category'].initial = liability.category self.fields['account'].initial = liability.account self.fields['value_display'].initial = liability.value_display self.fields['value_currency'].initial = liability.value_currency
def __init__(self, user, skip=[], *args, **kwargs): super(LiabilityFilterForm, self).__init__(*args, **kwargs) if 'due_date_from' in skip: del self.fields['due_date_from'] else: self.fields['due_date_from'] = forms.DateField( label=_("Due Date From:"), required=False) self.fields['due_date_from'].widget.attrs.update( {'class': 'datepicker'}) if 'due_date_to' in skip: del self.fields['due_date_to'] else: self.fields['due_date_to'] = forms.DateField( label=_("Due Date To:"), required=False) self.fields['due_date_to'].widget.attrs.update( {'class': 'datepicker'}) if 'category' in skip: del self.fields['category'] else: self.fields['category'].queryset = Object.filter_permitted( user, Category.objects) self.fields['category'].label = _("Category") self.fields['category'].help_text = "" self.fields['category'].required = False if 'source' in skip: del self.fields['source'] else: self.fields['source'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['source'].label = _("Source") self.fields['source'].help_text = "" self.fields['source'].required = False self.fields['source'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) if 'target' in skip: del self.fields['target'] else: self.fields['target'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['target'].required = False self.fields['target'].label = _("Target") self.fields['target'].help_text = "" self.fields['target'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) if 'account' in skip: del self.fields['account'] else: self.fields['account'].queryset = Object.filter_permitted( user, Account.objects) self.fields['account'].required = False self.fields['account'].label = _("Account") self.fields['account'].help_text = ""
def __init__(self, user=None, contact_type=None, *args, **kwargs): "Populates form with fields from given ContactType" if 'instance' in kwargs: self.instance = kwargs['instance'] values = self.instance.contactvalue_set.all() del kwargs['instance'] super(ContactForm, self).__init__(*args, **kwargs) self.fields['parent'] = forms.ModelChoiceField(label='Parent', queryset=[], required=False) self.fields['parent'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['parent'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['parent'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['parent'].label = _('Parent') self.fields['name'].label = _('Name') if 'files' in kwargs: self.files = kwargs['files'] for field in contact_type.fields.all(): if self.instance: initial_field_name = self._get_free_field_name(field) self.fields[initial_field_name] = self._get_form_field(field) for value in values: if value.field == field: field_name = self._get_free_field_name(field) self.fields[field_name] = self._get_form_field( field, value) if initial_field_name in self.fields: del self.fields[initial_field_name] else: field_name = self._get_free_field_name(field) self.fields[field_name] = self._get_form_field(field) if user.is_admin('treeio.identities'): self.fields['related_user'] = forms.ModelChoiceField( label=_('Attach to User'), queryset=[], required=False) self.fields['related_user'].queryset = AccessEntity.objects.all() self.fields['related_user'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_access_lookup') }) self.fields['related_user'].label = _('Related user') if self.instance: self.fields['name'].initial = self.instance.name self.fields['parent'].initial = self.instance.parent_id if 'related_user' in self.fields: self.fields[ 'related_user'].initial = self.instance.related_user_id
def __init__(self, user, item_type, *args, **kwargs): "Populates form with fields from given AssetType" self.item_type = item_type if 'instance' in kwargs: self.instance = kwargs['instance'] values = self.instance.itemvalue_set.all() del kwargs['instance'] super(ItemForm, self).__init__(*args, **kwargs) if 'files' in kwargs: self.files = kwargs['files'] # Model fields self.fields['name'] = forms.CharField( max_length=512, widget=forms.TextInput(attrs={'size': '50'})) self.fields['name'].label = _("Name") self.fields['parent'] = forms.ModelChoiceField(label=_('Parent'), queryset=[], required=False) self.fields['status'] = forms.ModelChoiceField(label=_('Status'), queryset=[], required=True) self.fields['manufacturer'] = forms.ModelChoiceField( label=_('Manufacturer'), queryset=[], required=False) self.fields['supplier'] = forms.ModelChoiceField(label=_('Supplier'), queryset=[], required=False) self.fields['owner'] = forms.ModelChoiceField(label=_('Owner'), queryset=[], required=False) self.fields['location'] = forms.ModelChoiceField(label=_('Location'), queryset=[], required=False) self.fields['asset'] = forms.ModelChoiceField(label=_('Asset Record'), queryset=[], required=False) self.fields['parent'].queryset = Object.filter_permitted(user, Item.objects, mode='x') self.fields['status'].queryset = Object.filter_permitted( user, ItemStatus.objects, mode='x') self.fields['manufacturer'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['supplier'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['owner'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') self.fields['location'].queryset = Object.filter_permitted( user, Location.objects, mode='x') self.fields['asset'].queryset = Object.filter_permitted(user, Asset.objects, mode='x') self.fields['manufacturer'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['manufacturer'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['supplier'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['supplier'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['owner'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['owner'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) #self.fields['asset'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('finance_ajax_asset_lookup')}) self.fields['location'].widget.attrs.update( {'popuplink': reverse('infrastructure_location_add')}) self.fields['location'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_location_lookup') }) self.fields['asset'].widget.attrs.update( {'popuplink': reverse('finance_asset_add')}) try: conf = ModuleSetting.get_for_module('treeio.infrastructure', 'default_item_status')[0] default_item_status = ItemStatus.objects.get(pk=long(conf.value), trash=False) self.fields['status'].initial = default_item_status.id except Exception: pass if self.instance: self.fields['name'].initial = self.instance.name self.fields['status'].initial = self.instance.status_id self.fields['parent'].initial = self.instance.parent_id self.fields['manufacturer'].initial = self.instance.manufacturer_id self.fields['supplier'].initial = self.instance.supplier_id self.fields['owner'].initial = self.instance.owner_id self.fields['location'].initial = self.instance.location_id self.fields['asset'].initial = self.instance.asset_id # AssetField <-> AssetValue fields for field in item_type.fields.all(): if self.instance: initial_field_name = self._get_free_field_name(field) self.fields[initial_field_name] = self._get_form_field(field) for value in values: if value.field == field: field_name = self._get_free_field_name(field) self.fields[field_name] = self._get_form_field( field, value) if initial_field_name in self.fields: del self.fields[initial_field_name] else: field_name = self._get_free_field_name(field) self.fields[field_name] = self._get_form_field(field)
def _get_report_content(report, request=None): model = loads(report.model) object = model.name object = object.split('.') module_name = object[0] + '.' + object[1] + '.' + object[2] import_name = object[3] module = __import__(module_name, globals(), locals(), [import_name], -1) classobj = getattr(module, import_name) if request: unfiltered_set = Object.filter_by_request(request, classobj.objects) else: unfiltered_set = classobj.objects.exclude(trash=True) # construct filter filters = {} excludes = {} for field in model.fields: for filter in field.filters: if filter['operand'] == 'is': filters.setdefault(field.name + '__in', []).append(filter['choice']) elif filter['operand'] == 'not': excludes.setdefault(field.name + '__in', []).append(filter['choice']) elif filter['operand'] == 'beforedate': filters[field.name + '__gte'] = datetime.date( datetime.strptime(filter['choice'], '%m/%d/%Y')) elif filter['operand'] == 'afterdate': filters[field.name + '__lte'] = datetime.date( datetime.strptime(filter['choice'], '%m/%d/%Y')) elif filter['operand'] == 'beforedatetime': filters[field.name + '__gte'] = datetime.strptime( filter['choice'], '%m/%d/%Y %H:%M') elif filter['operand'] == 'afterdatetime': filters[field.name + '__lte'] = datetime.strptime( filter['choice'], '%m/%d/%Y %H:%M') elif filter['operand'] == 'on': filters.setdefault(field.name + '__in', []).append( datetime.strptime(filter['choice'], '%m/%d/%Y')) set = unfiltered_set.filter(**filters).exclude(**excludes) # Check for group groupname = None groups = None for field in model.fields: if field.groupby == 1: groupname = field.name if groupname: xfield = classobj._meta.get_field_by_name(groupname)[0] xtype = xfield.get_internal_type() if xtype == 'ManyToManyField': set = sorted( set, key=lambda item: (", ".join( [unicode(i) for i in getattr(item, groupname).all()])), reverse=True) groups, groupnames = [], [] for obj in set: for n in getattr(obj, groupname).all(): if n not in groupnames: groupnames.append(n) for n in groupnames: l = [] for obj in set: if n in getattr(obj, groupname).all(): l.append(obj) groups.append((unicode(n), l)) elif xtype == ('DateTimeField' or 'DateField'): set = set.order_by(groupname) #set = sorted(set, key = lambda item: getattr(item,groupname)) #TODO: Fix this sort groups, groupnames, l, ng = [], [], [], [] n = None if xtype == 'DateTimeField': def dt(ob): return getattr(ob, groupname).date() else: def dt(ob): return getattr(ob, groupname) for x in set: n = dt(x) if n: break if n: for obj in set: if getattr(obj, groupname): if dt(obj) == n: l.append(obj) else: groups.append((unicode(n), l)) l = [] n = dt(obj) l.append(obj) else: ng.append(obj) if ng: groups.append(('None', ng)) else: set = sorted( set, key=lambda item: unicode(item.get_field_value(groupname)), reverse=True) groups = [] for g, ks in groupby( set, key=lambda item: unicode(item.get_field_value(groupname))): groups.append((g, list(ks))) xfield = set[0]._meta.get_field_by_name(groupname)[0] # Count aggregate functions agg_funcs = {} for field in model.fields: # get fields and aggregate functions for them if field.display and getattr(field, 'aggregation', None): xfield = classobj._meta.get_field_by_name(field.name)[0] if number_field_regex.match(xfield.get_internal_type()) \ and aggregate_functions.has_key(field.aggregation): agg_funcs[field.name] = aggregate_functions[ field.aggregation]['function'] aggregations = {} if agg_funcs: for grouper, ls in groups if groups else (('set', set), ): data = {} for s in ls: for key in agg_funcs: data.setdefault(key, []).append(getattr(s, key, 0)) aggrs = {} for key, func in agg_funcs.items(): aggrs[key] = func(data.get(key, [ 0, ])) aggregations[grouper] = aggrs return { 'model': model, 'set': set, 'groups': groups, 'groupname': groupname, 'aggregations': aggregations }
def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) self.fields['default_perspective'].label = _("Default Perspective") self.fields['language'].label = _("Language") self.fields['default_timezone'].label = _("Time Zone") self.fields['email_notifications'].label = _("E-mail Notifications") self.user = user self.fields['default_perspective'].queryset = Object.filter_permitted( user, Perspective.objects) try: conf = ModuleSetting.get_for_module('treeio.core', 'default_perspective', user=self.user)[0] default_perspective = Perspective.objects.get(pk=long(conf.value)) self.fields['default_perspective'].initial = default_perspective.id except: pass self.fields['default_timezone'].choices = getattr( settings, 'HARDTREE_SERVER_TIMEZONE') timezone = settings.HARDTREE_SERVER_DEFAULT_TIMEZONE try: conf = ModuleSetting.get('default_timezone', user=user)[0] timezone = conf.value except: pass self.fields['default_timezone'].initial = timezone self.fields['language'].choices = getattr(settings, 'HARDTREE_LANGUAGES', [('en', 'English')]) language = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', '') try: conf = ModuleSetting.get('language', user=user)[0] language = conf.value except IndexError: pass self.fields['language'].initial = language try: conf = ModuleSetting.get('email_notifications', user=user)[0] self.fields['email_notifications'].initial = conf.value except: self.fields[ 'email_notifications'].initial = settings.HARDTREE_ALLOW_EMAIL_NOTIFICATIONS perspective = user.get_perspective() modules = perspective.modules.filter(display=True).order_by('title') if not modules: modules = Module.objects.filter(display=True).order_by('title') self.fields['notifications_for_modules'].choices = [ (module.pk, module.title) for module in modules ] try: modules = NotificationSetting.objects.get( owner=self.user).modules.all() self.fields['notifications_for_modules'].initial = [ m.pk for m in modules ] except (NotificationSetting.DoesNotExist, NotificationSetting.MultipleObjectsReturned): pass
def link_block(context, object): "Block with objects links" request = context['request'] response_format = 'html' if 'response_format' in context: response_format = context['response_format'] response_format_tags = response_format if 'response_format_tags' in context: response_format_tags = context['response_format_tags'] if request.GET and 'link_add' in request.GET: if request.POST: if 'cancel' in request.POST: links = Object.filter_by_request(context['request'], object.links) return Markup( render_to_string('core/tags/link_block', { 'object': object, 'links': links, 'request': request, 'path': request.path }, context_instance=RequestContext(request), response_format=response_format)) form = ObjectLinksForm(request.user.get_profile(), response_format_tags, object, request.POST) if form.is_valid() and request.user.get_profile().has_permission( object, mode='w'): object.links.add(form.cleaned_data['links']) links = Object.filter_by_request(context['request'], object.links) return Markup( render_to_string('core/tags/link_block', { 'object': object, 'links': links, 'request': request, 'path': request.path }, context_instance=RequestContext(request), response_format=response_format)) links = Object.filter_by_request(context['request'], object.links) form = ObjectLinksForm(request.user.get_profile(), response_format_tags, instance=object) context = { 'object': object, 'path': request.path, 'form': form, 'links': links } if 'ajax' in response_format_tags: context = converter.preprocess_context(context) rendered_string = render_to_string( 'core/tags/link_block_edit', context, context_instance=RequestContext(request), response_format=response_format) return Markup(rendered_string) elif request.GET and 'link_delete' in request.GET: if request.user.get_profile().has_permission(object, mode='w'): try: link = Object.objects.get(pk=request.GET['link_delete']) object.links.remove(link) except Exception: pass links = Object.filter_by_request(context['request'], object.links) return Markup( render_to_string('core/tags/link_block', { 'object': object, 'links': links, 'request': request, 'path': request.path }, context_instance=RequestContext(request), response_format=response_format))
def __init__(self, user, queue, agent, *args, **kwargs): "Sets allowed values" super(TicketForm, self).__init__(*args, **kwargs) # Filter allowed selections for TicketForm self.fields['reference'].required = False self.fields['reference'].label = _("Reference") self.fields['caller'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['caller'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['caller'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['caller'].label = _("Caller") self.fields['assigned'].queryset = Object.filter_permitted( user, ServiceAgent.objects, mode='x') self.fields['assigned'].label = _("Assigned to") self.fields['assigned'].help_text = "" self.fields['assigned'].widget.attrs.update({ 'class': 'multicomplete', 'callback': reverse('services_ajax_agent_lookup') }) self.fields['assigned'].widget.attrs.update( {'popuplink': reverse('services_agent_add')}) self.fields['status'].queryset = Object.filter_permitted( user, TicketStatus.objects, mode='x') self.fields['status'].label = _("Status") self.fields['service'].queryset = Object.filter_permitted( user, Service.objects, mode='x') self.fields['service'].label = _("Service") self.fields['queue'].queryset = Object.filter_permitted( user, TicketQueue.objects, mode='x') self.fields['queue'].label = _("Queue") self.fields['sla'].queryset = Object.filter_permitted( user, ServiceLevelAgreement.objects, mode='x') self.fields['sla'].label = _("Service Level Agreement") self.fields['resolution'].label = _("Resolution") # Set default values if not editing if not 'instance' in kwargs: try: self.fields['caller'].initial = user.get_contact().id except Exception: pass if queue: self.fields['queue'].initial = queue.id if queue.default_ticket_status and queue.default_ticket_status in self.fields[ 'status'].queryset: self.fields[ 'status'].initial = queue.default_ticket_status_id else: try: conf = ModuleSetting.get_for_module( 'treeio.services', 'default_ticket_status')[0] self.fields['status'].initial = long(conf.value) except: pass if queue.default_ticket_priority: self.fields[ 'priority'].initial = queue.default_ticket_priority if queue.default_service: self.fields['service'].initial = queue.default_service_id try: default_sla = ServiceLevelAgreement.objects.get( service=queue.default_service, default=True) if default_sla: self.fields['sla'].initial = default_sla.id except: pass else: try: conf = ModuleSetting.get_for_module( 'treeio.services', 'default_ticket_status')[0] self.fields['status'].initial = long(conf.value) except: pass try: conf = ModuleSetting.get_for_module( 'treeio.services', 'default_ticket_queue')[0] self.fields['queue'].initial = long(conf.value) except: pass self.fields['name'].label = _("Name") self.fields['name'].widget.attrs.update({ 'class': 'duplicates', 'callback': reverse('services_ajax_ticket_lookup') }) self.fields['priority'].label = _("Priority") self.fields['priority'].choices = ((5, _('Highest')), (4, _('High')), (3, _('Normal')), (2, _('Low')), (1, _('Lowest'))) self.fields['urgency'].label = _("Urgency") self.fields['urgency'].choices = ((5, _('Highest')), (4, _('High')), (3, _('Normal')), (2, _('Low')), (1, _('Lowest'))) self.fields['details'].label = _("Details") if not agent: del self.fields['caller'] del self.fields['reference'] del self.fields['priority'] del self.fields['status'] del self.fields['queue'] del self.fields['sla'] del self.fields['assigned'] del self.fields['resolution']
def __init__(self, user, parent, project_id, milestone_id, *args, **kwargs): "Populates form with fields from given Project" super(TaskForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].widget.attrs.update({ 'class': 'duplicates', 'callback': reverse('projects_ajax_task_lookup') }) self.fields['status'].label = _("Status") self.fields['status'].queryset = Object.filter_permitted( user, TaskStatus.objects, mode='x') try: conf = ModuleSetting.get_for_module('treeio.projects', 'default_task_status')[0] self.fields['status'].initial = long(conf.value) except Exception: pass self.user = user self.fields['assigned'].label = _("Assigned") self.fields['assigned'].help_text = "" self.fields['assigned'].widget.attrs.update({ 'class': 'multicomplete', 'callback': reverse('identities_ajax_user_lookup') }) self.fields['caller'].label = _("Caller") self.fields['caller'].queryset = Object.filter_permitted( user, Contact.objects, mode='x') if not self.instance.id: contact = user.get_contact() if contact: self.fields['caller'].initial = contact.id self.instance.caller = contact self.fields['caller'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['caller'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['project'].label = _("Project") self.fields['project'].queryset = Object.filter_permitted( user, Project.objects, mode='x') if project_id: self.fields['project'].initial = project_id self.fields['milestone'].label = _("Milestone") self.fields['milestone'].queryset = Object.filter_permitted( user, Milestone.objects, mode='x') if milestone_id: self.fields['milestone'].initial = milestone_id self.fields['parent'].label = _("Parent") self.fields['parent'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('projects_ajax_task_lookup') }) self.fields['depends'].label = _("Depends on") self.fields['depends'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('projects_ajax_task_lookup') }) self.fields['milestone'].queryset = Object.filter_permitted( user, Milestone.objects, mode='x') self.fields['parent'].queryset = Object.filter_permitted(user, Task.objects, mode='x') self.fields['priority'].label = _("Priority") self.fields['priority'].initial = 3 self.fields['priority'].choices = ((5, _('Highest')), (4, _('High')), (3, _('Normal')), (2, _('Low')), (1, _('Lowest'))) self.fields['parent'].queryset = Object.filter_permitted(user, Task.objects, mode='x') if parent: self.fields['parent'].initial = parent.id self.fields['project'].initial = parent.project_id if parent.milestone_id: self.fields['milestone'].initial = parent.milestone_id # Set datepicker self.fields['start_date'].label = _("Start date") self.fields['start_date'].widget.attrs.update( {'class': 'datetimepicker'}) self.fields['end_date'].label = _("End date") self.fields['end_date'].widget.attrs.update( {'class': 'datetimepicker'}) if 'instance' in kwargs: instance = kwargs['instance'] if instance.start_date: self.fields['start_date'].widget.attrs.update( {'initial': instance.start_date.strftime('%s')}) if instance.end_date: self.fields['end_date'].widget.attrs.update( {'initial': instance.end_date.strftime('%s')}) self.fields['details'].label = _("Details") self.fields['details'].widget.attrs.update({'class': 'full-editor'}) self.fields['estimated_time'].label = _("Estimated time") self.fields['estimated_time'].help_text = _("minutes")
def __init__(self, user, lead=None, opportunity=None, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['reference'].required = False self.fields['reference'].label = _("Reference") if hasattr(self, 'instance') and not self.instance.reference: next_ref = self.instance.get_next_reference() if next_ref: self.fields['reference'].initial = next_ref self.fields['client'].queryset = Object.filter_permitted( user, Contact.objects) self.fields['client'].widget.attrs.update({ 'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup') }) self.fields['client'].widget.attrs.update( {'popuplink': reverse('identities_contact_add')}) self.fields['client'].label = _("Client") self.fields['source'].queryset = Object.filter_permitted( user, SaleSource.objects.filter(active=True)) self.fields['source'].label = _("Source") # Currency self.fields['currency'].label = _('Currency') instance = getattr(self, 'instance', None) if instance and instance.id: del self.fields['currency'] else: self.fields['currency'].widget.attrs.update( {'popuplink': reverse('finance_currency_add')}) self.fields['currency'].initial = Currency.objects.get( is_default=True) try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_source')[0] self.fields['source'].initial = long(conf.value) except: pass self.fields['status'].queryset = Object.filter_permitted( user, SaleStatus.objects.filter(use_sales=True)) self.fields['status'].label = _("Status") try: conf = ModuleSetting.get_for_module('treeio.sales', 'default_order_status')[0] self.fields['status'].initial = long(conf.value) except: pass if opportunity: self.fields['opportunity'].queryset = Object.filter_permitted( user, Opportunity.objects) self.fields['opportunity'].label = _("Opportunity") self.fields['opportunity'].initial = opportunity.id self.fields['client'].initial = opportunity.contact_id self.fields['source'].initial = opportunity.source_id self.fields['assigned'].initial = [ i.id for i in opportunity.assigned.only('id') ] else: del self.fields['opportunity'] if lead: self.fields['client'].initial = lead.contact_id self.fields['source'].initial = lead.source_id self.fields['assigned'].initial = [ i.id for i in lead.assigned.only('id') ] self.fields['assigned'].help_text = "" self.fields['assigned'].label = _("Assigned to") self.fields['assigned'].widget.attrs.update({ 'class': 'multicomplete', 'callback': reverse('identities_ajax_user_lookup') }) self.fields['datetime'].label = _("Date") self.fields['datetime'].widget.attrs.update( {'class': 'datetimepicker'}) self.fields['details'].label = _("Details")
def stream_view(request, stream_id, response_format='html'): "Stream view page" user = request.user.get_profile() stream = get_object_or_404(MessageStream, pk=stream_id) if not request.user.get_profile().has_permission(stream): return user_denied(request, message="You don't have access to this Stream", response_format=response_format) if request.user.get_profile().has_permission(stream, mode='x'): if request.POST: message = Message() message.author = user.get_contact() if not message.author: return user_denied( request, message= "You can't send message without a Contact Card assigned to you.", response_format=response_format) form = MessageForm(request.user.get_profile(), None, None, request.POST, instance=message) if form.is_valid(): message = form.save() message.recipients.add(user.get_contact()) message.set_user_from_request(request) message.read_by.add(user) try: # if email entered create contact and add to recipients if 'multicomplete_recipients' in request.POST and request.POST[ 'multicomplete_recipients']: try: conf = ModuleSetting.get_for_module( 'treeio.messaging', 'default_contact_type')[0] default_contact_type = ContactType.objects.get( pk=long(conf.value)) except Exception: default_contact_type = None emails = request.POST[ 'multicomplete_recipients'].split(',') for email in emails: emailstr = unicode(email).strip() if re.match( '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr): contact, created = Contact.get_or_create_by_email( emailstr, contact_type=default_contact_type) message.recipients.add(contact) if created: contact.set_user_from_request(request) except: pass # send email to all recipients message.send_email() return HttpResponseRedirect( reverse('messaging_stream_view', args=[stream.id])) else: form = MessageForm(request.user.get_profile(), stream_id) else: form = None objects = Object.filter_by_request( request, Message.objects.filter(reply_to__isnull=True, stream=stream).order_by('-date_created')) context = _get_default_context(request) context.update({'messages': objects, 'form': form, 'stream': stream}) return render_to_response('messaging/stream_view', context, context_instance=RequestContext(request), response_format=response_format)
def messaging_view(request, message_id, response_format='html'): "Single message page" message = get_object_or_404(Message, pk=message_id) user = request.user.get_profile() if not user.has_permission(message): return user_denied(request, message="You don't have access to this Message", response_format=response_format) message.read_by.add(user) if request.POST and request.POST.get('body', False): "Unread message" reply = Message() reply.author = user.get_contact() if not reply.author: return user_denied( request, message= "You can't send message without a Contact Card assigned to you.", response_format=response_format) reply.reply_to = message form = MessageReplyForm(user, message.stream_id, message, request.POST, instance=reply) if form.is_valid(): reply = form.save() reply.set_user_from_request(request) # Add author to recipients reply.recipients.add(reply.author) message.read_by.clear() try: # if email entered create contact and add to recipients if 'multicomplete_recipients' in request.POST and request.POST[ 'multicomplete_recipients']: try: conf = ModuleSetting.get_for_module( 'treeio.messaging', 'default_contact_type')[0] default_contact_type = ContactType.objects.get( pk=long(conf.value)) except Exception: default_contact_type = None emails = request.POST['multicomplete_recipients'].split( ',') for email in emails: emailstr = unicode(email).strip() if re.match( '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr): contact, created = Contact.get_or_create_by_email( emailstr, contact_type=default_contact_type) reply.recipients.add(contact) if created: contact.set_user_from_request(request) except: pass # Add each recipient of the reply to the original message for recipient in reply.recipients.all(): message.recipients.add(recipient) # send email to all recipients reply.send_email() return HttpResponseRedirect( reverse('messaging_message_view', args=[message.id])) else: form = MessageReplyForm(request.user.get_profile(), message.stream_id, message) replies = Object.filter_by_request( request, Message.objects.filter(reply_to=message).order_by('date_created')) context = _get_default_context(request) context.update({'message': message, 'messages': replies, 'form': form}) return render_to_response('messaging/message_view', context, context_instance=RequestContext(request), response_format=response_format)
def settings_view(request, response_format='html'): "Settings" if not request.user.get_profile().is_admin('treeio.services'): return user_denied( request, message= "You don't have administrator access to the Service Support module" ) # default ticket status try: conf = ModuleSetting.get_for_module('treeio.services', 'default_ticket_status')[0] default_ticket_status = TicketStatus.objects.get(pk=long(conf.value)) except Exception: default_ticket_status = None # default queue try: conf = ModuleSetting.get_for_module('treeio.services', 'default_ticket_queue')[0] default_ticket_queue = TicketQueue.objects.get(pk=long(conf.value)) except Exception: default_ticket_queue = None # notify ticket caller by email try: conf = ModuleSetting.get_for_module('treeio.services', 'send_email_to_caller')[0] send_email_to_caller = conf.value except Exception: send_email_to_caller = settings.HARDTREE_SEND_EMAIL_TO_CALLER # notification template send_email_example = '' try: conf = ModuleSetting.get_for_module('treeio.services', 'send_email_template')[0] send_email_template = conf.value except Exception: send_email_template = None queues = TicketQueue.objects.filter(trash=False, parent__isnull=True) statuses = TicketStatus.objects.filter(trash=False) if send_email_to_caller: # Render example e-mail try: ticket = Object.filter_by_request( request, Ticket.objects.filter(status__hidden=False, caller__isnull=False))[0] except IndexError: ticket = Ticket(reference='REF123', name='New request') if not ticket.caller: try: caller = Object.filter_by_request(request, Contact.objects)[0] except IndexError: caller = Contact(name='John Smith') ticket.caller = caller try: ticket.status except: ticket.status = None if not ticket.status: try: ticket.status = statuses[0] except IndexError: ticket.status = TicketStatus(name='Open') if send_email_template: try: send_email_example = render_string_template( send_email_template, {'ticket': ticket}) except: send_email_example = render_to_string( 'services/emails/notify_caller', {'ticket': ticket}, response_format='html') else: send_email_example = render_to_string( 'services/emails/notify_caller', {'ticket': ticket}, response_format='html') context = _get_default_context(request) context.update({ 'settings_queues': queues, 'settings_statuses': statuses, 'default_ticket_status': default_ticket_status, 'default_ticket_queue': default_ticket_queue, 'send_email_to_caller': send_email_to_caller, 'send_email_example': send_email_example }) return render_to_response('services/settings_view', context, context_instance=RequestContext(request), response_format=response_format)
#!/usr/bin/python OBJECTS_NUM = 100 # setup environment import sys import os sys.path.append('../') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.core.management import setup_environ from treeio import settings from treeio.core.models import Object, User from treeio.projects.models import Project setup_environ(settings) user = User.objects.all()[0] for i in range(0, OBJECTS_NUM): project = Project(name='test' + unicode(i)) project.set_user(user) project.save() objects = Object.filter_permitted(user, Project.objects) allowed = 0 for obj in objects: if user.has_permission(obj): allowed += 1 print len(list(objects)), ':', allowed