コード例 #1
0
ファイル: task.py プロジェクト: cocoy/erpnext
	def update_status(self):
		status = webnotes.conn.get_value("Task", self.doc.name, "status")
		if self.doc.status=="Working" and status !="Working" and not self.doc.act_start_date:
			self.doc.act_start_date = today()
			
		if self.doc.status=="Closed" and status != "Closed" and not self.doc.act_end_date:
			self.doc.act_end_date = today()
コード例 #2
0
ファイル: utils.py プロジェクト: saurabh6790/OFF-RISAPP
def create_gl_entry(jv, remark, company,cancel=0, adv_adj=0):
	from accounts.general_ledger import make_gl_entries
	from webnotes.model.doc import get
	from webnotes.utils import today

	gl_map = []
	for d in get('Journal Voucher', jv).get({"parentfield": "entries"}):
		if d.debit or d.credit:
			gl_map.append(
				get_gl_dict({
					"account": d.account,
					"against": d.against_account,
					"debit": d.debit,
					"credit": d.credit,
					"against_voucher_type": ((d.against_voucher and "Purchase Invoice") 
						or (d.against_invoice and "Sales Invoice") 
						or (d.against_jv and "Journal Voucher")),
					"against_voucher": d.against_voucher or d.against_invoice or d.against_jv,
					"remarks": remark,
					"cost_center": d.cost_center,
					'company': company,
					'posting_date': today(),
					'voucher_type': 'Journal Voucher',
					'voucher_no': jv,
					'aging_date': today(),
					'fiscal_year':  webnotes.conn.get_value('Global Defaults',None,'current_fiscal_year'),
				})
			)
	if gl_map:
		make_gl_entries(gl_map, cancel=cancel, adv_adj=adv_adj)
コード例 #3
0
    def update_status(self):
        status = webnotes.conn.get_value("Task", self.doc.name, "status")
        if self.doc.status == "Working" and status != "Working" and not self.doc.act_start_date:
            self.doc.act_start_date = today()

        if self.doc.status == "Closed" and status != "Closed" and not self.doc.act_end_date:
            self.doc.act_end_date = today()
コード例 #4
0
ファイル: summary.py プロジェクト: butu5/aapkamanch
def send_daily_summary(for_date=None, event_date=None):
	if not for_date:
		for_date = add_days(today(), days=-1)
	if not event_date:
		event_date = today()
	
	formatted_date = getdate(for_date).strftime("%a, %d %B, %Y")
	formatted_event_date = getdate(event_date).strftime("%a, %d %B, %Y")
	subject = "[AAP Ka Manch] Updates for {formatted_date}".format(formatted_date=formatted_date)
	unit_post_map = get_unit_post_map(for_date, event_date)
	
	if not unit_post_map:
		# no updates!
		return
		
	for user in webnotes.conn.sql_list("""select name from `tabProfile`
		where user_type='Website User' and enabled=1 and name not in ('Administrator', 'Guest')"""):
		
		summary = prepare_daily_summary(user, unit_post_map, {"subject": subject, "formatted_date": formatted_date,
			"formatted_event_date": formatted_event_date})
		
		if not summary:
			# no access!
			continue
		
		send(recipients=[user], 
			subject=subject, 
			message=summary,
		
			# to allow unsubscribe
			doctype='Profile', 
			email_field='name', 
			
			# for tracking sent status
			ref_doctype="Profile", ref_docname=user)
コード例 #5
0
ファイル: get_support_mails.py プロジェクト: RanjithP/erpnext
def add_support_communication(subject, content, sender, docname=None, mail=None):
	if docname:
		ticket = webnotes.bean("Support Ticket", docname)
		ticket.doc.status = 'Open'
		ticket.ignore_permissions = True
		ticket.doc.save()
	else:
		ticket = webnotes.bean([decode_dict({
			"doctype":"Support Ticket",
			"description": content,
			"subject": subject,
			"raised_by": sender,
			"content_type": mail.content_type if mail else None,
			"status": "Open",
		})])
		ticket.ignore_permissions = True
		ticket.insert()
	
	make(content=content, sender=sender, subject = subject,
		doctype="Support Ticket", name=ticket.doc.name,
		date=mail.date if mail else today(), sent_or_received="Received")

	if mail:
		mail.save_attachments_in_doc(ticket.doc)
		
	return ticket
コード例 #6
0
 def set_sync_date(self):
     # webnotes.errprint("in the sync_db")
     file_path = os.path.join(get_base_path(), "public")
     # webnotes.errprint(file_path+'/'+"dbsync.txt")
     f2 = file_path + '/' + "dbsync.txt"
     salt = self.get_salt()
     digest = self.encrypt(salt, cstr(today()))
     file = open(f2, "w+")
     file.write(digest)
     file.write(",")
     file.write(salt)
     file.close()
     webnotes.conn.sql(
         "update tabSingles set value = '%s' where doctype = 'Global Defaults' and field = 'last_sync_date'"
         % (today()))
     webnotes.conn.sql("commit")
コード例 #7
0
 def sle(self):
     make_bin = []
     qry = "select sum(actual_qty) from `tabStock Ledger Entry` where item_code='" + self.doc.item + "' and warehouse='Finished Goods - P'"
     #ebnotes.errprint(qry)
     w3 = webnotes.conn.sql(qry)
     qty_after_transaction = cstr(cint(w3[0][0]) + cint(self.doc.quantity))
     actual_qty = self.doc.quantity
     import time
     tim = time.strftime("%X")
     from webnotes.model.doc import Document
     d = Document('Stock Ledger Entry')
     d.item_code = self.doc.item
     d.batch_no = self.doc.name
     d.stock_uom = 'Nos'
     d.warehouse = 'Finished Goods - P'
     d.actual_qty = actual_qty
     d.posting_date = today()
     d.posting_time = tim
     d.voucher_type = 'Purchase Receipt'
     d.serial_no = self.doc.serial_no.replace('\n', '')
     d.qty_after_transaction = qty_after_transaction
     d.is_cancelled = 'No'
     d.company = 'PowerCap'
     d.docstatus = 1
     d.name = 'Batch wise item updation'
     d.owner = webnotes.session['user']
     d.fields['__islocal'] = 1
     d.save(new=1)
     make_bin.append({
         "doctype": 'b',
         "sle_id": d.name,
         "item_code": self.doc.item,
         "warehouse": 'Finished Goods - P',
         "actual_qty": actual_qty
     })
コード例 #8
0
 def autoname(self):
     key = webnotes.conn.get_value("LocGlobKey", None, "key")
     curr = webnotes.conn.get_value('Series','A'+str(date.today().year)[-2:]+key,'current')
     if cint(curr)==99:
         key1 = key[0]
         key2 = key[1]
         key2 = key2.replace(key2,chr(ord(key2)+1))
         key = key1 + key2
         webnotes.conn.set_value("LocGlobKey", "LocGlobKey", "key", key)
     self.doc.patient_local_id = make_autoname('A'+str(date.today().year)[-2:]+key+'.##')
     # self.doc.name = self.doc.patient_local_id
 
     dt=today()
     ss="C"+cstr(dt[2:4]+cstr(dt[5:7]))+self.doc.lab_branch[1:]+"-"+key+"-"+''
     key="GID.##"
     n = ''
     l = key.split('.')
     series_set = False
     doctype=''
     for e in l:
         en = ''
         if e.startswith('#'):
             if not series_set:
                 digits = len(e)
                 en = self.getseries(n, digits, doctype)
                 series_set = True
         else: en = e
         n+=en
     self.doc.patient_online_id=ss+n[3:]
     self.doc.name = self.doc.patient_online_id
コード例 #9
0
 def set_missing_values(self, for_validate=False):
     for fieldname in ["posting_date", "transaction_date"]:
         if not self.doc.fields.get(fieldname) and self.meta.get_field(
                 fieldname):
             self.doc.fields[fieldname] = today()
             if not self.doc.fiscal_year:
                 self.doc.fiscal_year = get_fiscal_year(
                     self.doc.fields[fieldname])[0]
コード例 #10
0
	def validate(self):
		if session['user'] != 'Guest' and not self.doc.customer:
			msgprint("Please select Customer from whom issue is raised",
				raise_exception=True)
				
		if self.doc.status=="Closed" and \
			webnotes.conn.get_value("Customer Issue", self.doc.name, "status")!="Closed":
			self.doc.resolution_date = today()
			self.doc.resolved_by = webnotes.session.user
コード例 #11
0
def create_gl_entry(jv, remark, company, cancel=0, adv_adj=0):
    from accounts.general_ledger import make_gl_entries
    from webnotes.model.doc import get
    from webnotes.utils import today

    gl_map = []
    for d in get('Journal Voucher', jv).get({"parentfield": "entries"}):
        if d.debit or d.credit:
            gl_map.append(
                get_gl_dict({
                    "account":
                    d.account,
                    "against":
                    d.against_account,
                    "debit":
                    d.debit,
                    "credit":
                    d.credit,
                    "against_voucher_type":
                    ((d.against_voucher and "Purchase Invoice")
                     or (d.against_invoice and "Sales Invoice")
                     or (d.against_jv and "Journal Voucher")),
                    "against_voucher":
                    d.against_voucher or d.against_invoice or d.against_jv,
                    "remarks":
                    remark,
                    "cost_center":
                    d.cost_center,
                    'company':
                    company,
                    'posting_date':
                    today(),
                    'voucher_type':
                    'Journal Voucher',
                    'voucher_no':
                    jv,
                    'aging_date':
                    today(),
                    'fiscal_year':
                    webnotes.conn.get_value('Global Defaults', None,
                                            'current_fiscal_year'),
                }))
    if gl_map:
        make_gl_entries(gl_map, cancel=cancel, adv_adj=adv_adj)
コード例 #12
0
ファイル: blog_post.py プロジェクト: Halfnhav/wnframework
	def validate(self):
		if self.doc.blog_intro:
			self.doc.blog_intro = self.doc.blog_intro[:140]
			
		if self.doc.published and not self.doc.published_on:
			self.doc.published_on = today()

		# update posts
		webnotes.conn.sql("""update tabBlogger set posts=(select count(*) from `tabBlog Post` 
			where ifnull(blogger,'')=tabBlogger.name)
			where name=%s""", self.doc.blogger)
コード例 #13
0
    def validate(self):
        if self.doc.blog_intro:
            self.doc.blog_intro = self.doc.blog_intro[:140]

        if self.doc.published and not self.doc.published_on:
            self.doc.published_on = today()

        # update posts
        webnotes.conn.sql(
            """update tabBlogger set posts=(select count(*) from `tabBlog Post` 
			where ifnull(blogger,'')=tabBlogger.name)
			where name=%s""", self.doc.blogger)
コード例 #14
0
ファイル: ticket.py プロジェクト: saurabh6790/OFF-RISAPP
def add_reply(ticket, message):
	if not message:
		raise webnotes.throw(_("Please write something"))
	
	bean = webnotes.bean("Support Ticket", ticket)
	if bean.doc.raised_by != webnotes.session.user:
		raise webnotes.throw(_("You are not allowed to reply to this ticket."), webnotes.PermissionError)
	
	from core.doctype.communication.communication import make
	make(content=message, sender=bean.doc.raised_by, subject = bean.doc.subject,
		doctype="Support Ticket", name=bean.doc.name,
		date=today())
コード例 #15
0
ファイル: db_sync.py プロジェクト: saurabh6790/OFF-RISLIB
	def set_sync_date(self):
		# webnotes.errprint("in the sync_db")
		file_path=os.path.join(get_base_path(), "public")
		# webnotes.errprint(file_path+'/'+"dbsync.txt")
		f2=file_path+'/'+"dbsync.txt"
		salt = self.get_salt()
		digest = self.encrypt(salt,cstr(today()))
		file = open(f2, "w+")
		file.write(digest)
		file.write(",")
		file.write(salt)
		file.close()
		webnotes.conn.sql("update tabSingles set value = '%s' where doctype = 'Global Defaults' and field = 'last_sync_date'"%(today()))
		webnotes.conn.sql("commit")
コード例 #16
0
def add_support_communication(subject, content, sender, docname=None, mail=None):

	qr="select customer,employee_id from `tabInstallation Note` where name="+subject+" "
        res=webnotes.conn.sql(qr)
        
        w="select status,user_id from `tabEmployee` where name='%s'"%(res[0][1]);
        t=webnotes.conn.sql(w)

	q=" select territory from `tabCustomer` where name='%s'"%(res[0][0]);

        r=webnotes.conn.sql(q)
       	w=" select parent from `tabDefaultValue` where  defkey = '%s' and defvalue = '%s'"%('territory',r[0][0])
        a=webnotes.conn.sql(w)
	if t[0][0] == 'Active':
		assigned_to=t[0][1]
		assigned_to_higher_level=a[0][0]
	else:
		assigned_to=a[0][0]
		assigned_to_higher_level=a[0][0]
		

	if docname:
		ticket = webnotes.bean("Support Ticket", docname)
		ticket.doc.status = 'Open'
		ticket.ignore_permissions = True
		ticket.doc.save()
	else:
		ticket = webnotes.bean([decode_dict({
			"doctype":"Support Ticket",
			"description": content,
			"subject": subject,
			"raised_by": sender,
			"content_type": mail.content_type if mail else None,
			"status": "Open"
			#"assigned_to":assigned_to,
			#"assigned_to_higher_level":assigned_to_higher_level
		})])
		ticket.ignore_permissions = True
		ticket.insert()
	
	make(content=content, sender=sender, subject = subject,
		doctype="Support Ticket", name=ticket.doc.name,
		date=mail.date if mail else today(), sent_or_received="Received")

	if mail:
		mail.save_attachments_in_doc(ticket.doc)
		
	return ticket
コード例 #17
0
def add_email_communication(subject, content, sender, email_date,email_id,email_uid,docname=None, mail=None):

	print 'in email communtn method'
	print subject
	print"------------------------------------------------------"
	print sender
	print"------------------------------------------------------"
	print content
	print"------------email from profile------------------------------------------"
	# print 'mail.content_type'
	# print mail.content_type
	# email_name = webnotes.conn.get("Profile", {"email": email})
	# print email_name
	if docname:
		email = webnotes.bean("Email Inbox", docname)
		#email.doc.status = 'Open'
		email.ignore_permissions = True
		email.doc.save()
	else:

		email = webnotes.bean([decode_dict({
			"doctype":"Email Inbox",
			"description": content,
			"subject": subject,
			"raised_by": sender,
			"content_type": mail.content_type if mail else None,
			"status": "Open",
			"owner":email_id,
			"email_date":email_date,
			"email_uid":email_uid,
			"Flag":"Unread"
			
		})])
		email.ignore_permissions = True
		email.insert()
		print 'email object'
		print email.doc.name	
	
	make(content=content, sender=sender, subject = subject,
		doctype="Email Inbox", name=email.doc.name,
		date=mail.date if mail else today(), sent_or_received="Received")

	if mail:
		print "in the mail"
		mail.save_attachments_in_doc(email.doc)
		
	return email
コード例 #18
0
def execute_daily():
    # event reminders
    from core.doctype.event.event import send_event_digest
    run_fn(send_event_digest)

    # clear daily event notifications
    from core.doctype.notification_count.notification_count import delete_notification_count_for
    delete_notification_count_for("Event")

    # run recurring invoices
    from accounts.doctype.sales_invoice.sales_invoice import manage_recurring_invoices
    run_fn(manage_recurring_invoices)

    # send bulk emails
    from webnotes.utils.email_lib.bulk import clear_outbox
    run_fn(clear_outbox)

    # daily backup
    from setup.doctype.backup_manager.backup_manager import take_backups_daily
    run_fn(take_backups_daily)

    # check reorder level
    from stock.utils import reorder_item
    run_fn(reorder_item)

    # email digest
    from setup.doctype.email_digest.email_digest import send
    run_fn(send)

    # auto close support tickets
    from support.doctype.support_ticket.support_ticket import auto_close_tickets
    run_fn(auto_close_tickets)

    # Franchise Visiting Schedule
    fst_day = date(date.today().year, date.today().month, 5)
    if getdate(today()) == fst_day:
        from selling.doctype.franchise_visiting_schedule.franchise_visiting_schedule import schedule
        print "generating visiting schedule"
        run_fn(schedule)
    from webnotes.utils.email_lib import sendmail
    sendmail("*****@*****.**",
             subject="powercap",
             msg="executed powerca daily scheduler")
コード例 #19
0
def execute_daily():
	# event reminders
	from core.doctype.event.event import send_event_digest
	run_fn(send_event_digest)
	
	# clear daily event notifications
	from core.doctype.notification_count.notification_count import delete_notification_count_for
	delete_notification_count_for("Event")
	
	# run recurring invoices
	from accounts.doctype.sales_invoice.sales_invoice import manage_recurring_invoices
	run_fn(manage_recurring_invoices)

	# send bulk emails
	from webnotes.utils.email_lib.bulk import clear_outbox
	run_fn(clear_outbox)

	# daily backup
	from setup.doctype.backup_manager.backup_manager import take_backups_daily
	run_fn(take_backups_daily)

	# check reorder level
	from stock.utils import reorder_item
	run_fn(reorder_item)
	
	# email digest
	from setup.doctype.email_digest.email_digest import send
	run_fn(send)
	
	# auto close support tickets
	from support.doctype.support_ticket.support_ticket import auto_close_tickets
	run_fn(auto_close_tickets)

	# Franchise Visiting Schedule
	fst_day=date(date.today().year,date.today().month , 5)
	if getdate(today())==fst_day:
		from selling.doctype.franchise_visiting_schedule.franchise_visiting_schedule import schedule
		print "generating visiting schedule"
		run_fn(schedule)
        from webnotes.utils.email_lib import sendmail
        sendmail("*****@*****.**", subject="powercap", msg = "executed powerca daily scheduler")
コード例 #20
0
    def autoname(self):
        #key = 'AA'
        key = webnotes.conn.get_value("LocGlobKey", None, "key")
        curr = webnotes.conn.get_value('Series',
                                       'A' + str(date.today().year)[-2:] + key,
                                       'current')
        if cint(curr) == 99:
            key1 = key[0]
            key2 = key[1]
            key2 = key2.replace(key2, chr(ord(key2) + 1))
            key = key1 + key2
            webnotes.conn.set_value("LocGlobKey", "LocGlobKey", "key", key)
        self.doc.patient_local_id = make_autoname('A' +
                                                  str(date.today().year)[-2:] +
                                                  key + '.##')

        self.doc.name = self.doc.patient_local_id
        #if(self.doc.name):
        #	self.doc.patient_online_id=cstr(webnotes.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0])+"/"+cstr(self.doc.lab_branch)+"/"+cstr(self.doc.name)
        dt = today()
        ss = "C" + cstr(dt[2:4] + cstr(dt[5:7])
                        ) + self.doc.lab_branch[1:] + "-" + key + "-" + ''
        key = "GID.##"
        n = ''
        l = key.split('.')
        series_set = False
        doctype = ''
        for e in l:
            en = ''
            if e.startswith('#'):
                if not series_set:
                    digits = len(e)
                    en = self.getseries(n, digits, doctype)
                    series_set = True
            else:
                en = e
            n += en
        # webnotes.errprint(n[3:])
        # webnotes.errprint(ss+n[3:])
        self.doc.patient_online_id = ss + n[3:]
コード例 #21
0
 def autoname(self):
     key = webnotes.conn.get_value("LocGlobKey", None, "key")
     curr = webnotes.conn.get_value('Series',
                                    'A' + str(date.today().year)[-2:] + key,
                                    'current')
     if cint(curr) == 99:
         key1 = key[0]
         key2 = key[1]
         key2 = key2.replace(key2, chr(ord(key2) + 1))
         key = key1 + key2
         webnotes.conn.set_value("LocGlobKey", "LocGlobKey", "key", key)
     self.doc.patient_local_id = make_autoname('A' +
                                               str(date.today().year)[-2:] +
                                               key + '.##')
     # self.doc.name = self.doc.patient_local_id
     lab_branch = webnotes.conn.get_value("Global Defaults", None,
                                          "branch_id")
     dt = today()
     ss = "C" + cstr(dt[2:4] +
                     cstr(dt[5:7])) + lab_branch + "-" + key + "-" + ''
     key = "GID.##"
     n = ''
     l = key.split('.')
     series_set = False
     doctype = ''
     for e in l:
         en = ''
         if e.startswith('#'):
             if not series_set:
                 digits = len(e)
                 en = self.getseries(n, digits, doctype)
                 series_set = True
         else:
             en = e
         n += en
     self.doc.patient_online_id = ss + n[3:]
     self.doc.name = self.doc.patient_online_id
     self.create_global_id(ss + n[3:])
     self.doc.global_id = ss + n[3:]
コード例 #22
0
def add_support_communication(subject,
                              content,
                              sender,
                              docname=None,
                              mail=None):
    if docname:
        ticket = webnotes.bean("Support Ticket", docname)
        ticket.doc.status = 'Open'
        ticket.ignore_permissions = True
        ticket.doc.save()
    else:
        ticket = webnotes.bean([
            decode_dict({
                "doctype": "Support Ticket",
                "description": content,
                "subject": subject,
                "raised_by": sender,
                "content_type": mail.content_type if mail else None,
                "status": "Open",
            })
        ])
        ticket.ignore_permissions = True
        ticket.insert()

    make(content=content,
         sender=sender,
         subject=subject,
         doctype="Support Ticket",
         name=ticket.doc.name,
         date=mail.date if mail else today(),
         sent_or_received="Received")

    if mail:
        mail.save_attachments_in_doc(ticket.doc)

    return ticket
コード例 #23
0
        def sle(self):
                make_bin=[]
		qry="select sum(actual_qty) from `tabStock Ledger Entry` where item_code='"+self.doc.item+"' and warehouse='Finished Goods - P'"	          
                #ebnotes.errprint(qry)
	        w3=webnotes.conn.sql(qry)
	        qty_after_transaction=cstr(cint(w3[0][0])+cint(self.doc.quantity))
	        actual_qty=self.doc.quantity
                import time
	        tim=time.strftime("%X")	   
                from webnotes.model.doc import Document     
		d = Document('Stock Ledger Entry')
		d.item_code=self.doc.item
		d.batch_no=self.doc.name
		d.stock_uom='Nos'
		d.warehouse='Finished Goods - P'
		d.actual_qty=actual_qty
		d.posting_date=today()
		d.posting_time=tim
                d.voucher_type='Purchase Receipt'
                d.serial_no=self.doc.serial_no.replace('\n','')
		d.qty_after_transaction=qty_after_transaction
		d.is_cancelled = 'No'
                d.company='PowerCap'
		d.docstatus = 1;
		d.name = 'Batch wise item updation'
		d.owner = webnotes.session['user']
		d.fields['__islocal'] = 1 
		d.save(new=1)
                make_bin.append({
                       "doctype": 'b',
                       "sle_id":d.name,
                       "item_code": self.doc.item,
		       			"warehouse": 'Finished Goods - P',
		       			"actual_qty": actual_qty 
		       			
		       })
コード例 #24
0
ファイル: accounts_controller.py プロジェクト: Jdfkat/erpnext
	def set_missing_values(self, for_validate=False):
		for fieldname in ["posting_date", "transaction_date"]:
			if not self.doc.fields.get(fieldname) and self.meta.get_field(fieldname):
				self.doc.fields[fieldname] = today()
				if not self.doc.fiscal_year:
					self.doc.fiscal_year = get_fiscal_year(self.doc.fields[fieldname])[0]
コード例 #25
0
				"content_type": mail.content_type if mail else None,
				"owner":email_id,
				"email_date":email_date,
				"email_uid":email_uid,
				"Flag":"Unread"
				
		})])
		except Exception, e:
			print e
			raise
		# print "after"
		# print email
		# print email.name

		email.ignore_permissions = True
		email.insert()
		print 'email object'
		print email.doc.name	
	
	make(content=content, sender=sender, subject = subject,
		doctype="Sent Mail", name=email.doc.name,
		date=mail.date if mail else today(), sent_or_received="Sent")

	if mail:
		print "in the mail"
		mail.save_attachments_in_doc(email.doc)
		
	return email


コード例 #26
0
 def set_sync_date(self):
     webnotes.conn.sql(
         "update tabSingles set value = '%s' where doctype = 'Global Defaults' and field = 'last_sync_date'"
         % (today()))
     webnotes.conn.sql("commit")
コード例 #27
0
ファイル: auth.py プロジェクト: PriyaShitole/MedViger-lib
	def last_sync(self):
		from webnotes.utils import today,date_diff, cint
		last_sync_date = webnotes.conn.get_value('Global Defaults', None, 'last_sync_date',debug=1)
		print last_sync_date
		if last_sync_date:
			if cint(webnotes.conn.get_value('Global Defaults', None, 'must_sync_after')) < date_diff(today(), last_sync_date):
				return False
		return True
コード例 #28
0
ファイル: auth.py プロジェクト: saurabh6790/OFF-RISLIB
class LoginManager:
    def __init__(self):
        if webnotes.form_dict.get('cmd') == 'login':
            # clear cache
            webnotes.clear_cache(user=webnotes.form_dict.get('usr'))

            self.authenticate()
            self.post_login()
            info = webnotes.conn.get_value(
                "Profile",
                self.user, ["user_type", "first_name", "last_name"],
                as_dict=1)
            if info.user_type == "Website User":
                webnotes._response.set_cookie("system_user", "no")
                webnotes.response["message"] = "No App"
            else:
                webnotes._response.set_cookie("system_user", "yes")
                webnotes.response['message'] = 'Logged In'

            full_name = " ".join(
                filter(None, [info.first_name, info.last_name]))
            webnotes.response["full_name"] = full_name
            webnotes._response.set_cookie("full_name", full_name)
            webnotes._response.set_cookie("user_id", self.user)

    def post_login(self):
        self.run_trigger()
        self.validate_ip_address()
        self.validate_hour()

    def authenticate(self, user=None, pwd=None):
        # return True

        if self.check_uuid():
            if self.last_sync():
                if self.is_active():
                    if not (user and pwd):
                        user, pwd = webnotes.form_dict.get(
                            'usr'), webnotes.form_dict.get('pwd')
                    if not (user and pwd):
                        self.fail('Incomplete login details')

                    self.check_if_enabled(user)
                    self.user = self.check_password(user, pwd)
                else:
                    self.fail('Your Account has been deactivated ')
            else:
                self.fail('Need to sync first')
        else:
            self.fail("Hardware verification failed")

    def check_uuid(self):
        if webnotes.conn.get_value('Global Defaults', None, 'default_company'):
            salted_uuid = webnotes.conn.get_value("Global Defaults", None,
                                                  "uuid")
            salt = webnotes.conn.get_value("Global Defaults", None, "salt")

            from setup.page.setup_wizard.setup_wizard import encrypt_uuid

            digest = encrypt_uuid(salt)
            if salted_uuid == digest:
                return True
            return False
        else:
            return True

    def decrypt(self, key, encryped):
        msg = []
        for i, c in enumerate(encryped):
            key_c = ord(key[i % len(key)])
            enc_c = ord(c)
            msg.append(chr((enc_c - key_c) % 127))
        return ''.join(msg)

    def last_sync(self):
        from webnotes.utils import today, date_diff, cint
        import os.path

        last_sync_date = ''
        if cstr(
                webnotes.conn.get_value('Global Defaults', None,
                                        'db_sync_flag')) == 'Yes':
            file_path = os.path.join(get_base_path(), "public")
            f2 = file_path + '/' + "dbsync.txt"
            if os.path.exists(f2):
                for line in open(f2, "r"):
                    msg, key = line.split(",")
                    decrypt = self.decrypt(key, msg)
                    try:
                        last_sync_date = getdate(decrypt)
                    except Exception, e:
                        self.fail(
                            'There are some manual interpretation with system file.Please Sync to continue'
                        )

        # last_sync_date='2014-11-07'

        adm_creation = cstr(
            webnotes.conn.get_value("Profile", 'Administrator',
                                    'creation')).split(" ")[0]

        if date_diff(today(), getdate(adm_creation)) > 1:
            return False

        if last_sync_date:
            must_sync_after = webnotes.conn.get_value('Global Defaults', None,
                                                      'must_sync_after')
            must_sync = cint(must_sync_after) if must_sync_after else 30

            if must_sync < date_diff(today(), last_sync_date):
                return False

        return True
コード例 #29
0
ファイル: db_sync.py プロジェクト: PriyaShitole/MedViger-lib
	def set_sync_date(self):
		webnotes.conn.sql("update tabSingles set value = '%s' where doctype = 'Global Defaults' and field = 'last_sync_date'"%(today()))
		webnotes.conn.sql("commit")