Esempio n. 1
0
        def on_update(self):
                patient_id = None
                from datetime import datetime

                s1=(self.doc.start_time).split(':')
                s2=(self.doc.end_time).split(':')
                # date_a=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(s1[0]+":"+s1[1],'%H:%M').time()))
                # date_b=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(s2[0]+":"+s2[1],'%H:%M').time()))
                #webnotes.errprint(self.doc.entry_in_child)
                if self.doc.new_user == 1 and not self.doc.new_patient:
                        patient_id = self.make_patient()
                        self.doc.new_patient=patient_id
                        self.create_new_contact()
                        self.create_customer(patient_id)
                        self.create_account_head(patient_id)
                        self.doc.save()
                if self.doc.entry_in_child == 'False':
                        self.make_child_entry(patient_id)
                        #self.make_event()

                if not self.doc.eventid:
                        self.create_child()
                else:
                        webnotes.conn.sql("update `tabSlot Child` set slot='"+self.doc.appointment_slot+"', start_time='"+cstr(datetime.strptime(date_a,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"', end_time='"+cstr(datetime.strptime(date_b,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"' where encounter='"+self.doc.name+"'")
                        webnotes.errprint(date_a)
                        webnotes.conn.sql("update `tabEvent` set starts_on='"+cstr(datetime.strptime(date_a,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"', ends_on='"+cstr(datetime.strptime(date_b,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"' where name='"+self.doc.eventid+"'",debug=1)

                if cint(self.doc.checked_in)==1: pass
Esempio n. 2
0
def get_cols():
	filters = webnotes.form_dict.get('doctype')
	cols = webnotes.conn.sql("select columns from `tabReport Column` where name = '%s' "%(webnotes.form_dict.get('doctype')),as_list=1)
	webnotes.errprint(cols)
	if cols and cols[0][0]:
		columns = form_cols_list(cols[0][0].split(','))
	return columns
Esempio n. 3
0
def reconcile_against_document(args):
    """
		Cancel JV, Update aginst document, split if required and resubmit jv
	"""
    for d in args:
        check_if_jv_modified(d)

        against_fld = {
            'Journal Voucher': 'against_jv',
            'Sales Invoice': 'against_invoice',
            'Purchase Invoice': 'against_voucher'
        }

        d['against_fld'] = against_fld[d['against_voucher_type']]

        # cancel JV
        webnotes.errprint(d)
        jv_obj = webnotes.get_obj('Journal Voucher',
                                  d['voucher_no'],
                                  with_children=1)
        jv_obj.make_gl_entries(cancel=1, adv_adj=1)

        # update ref in JV Detail
        update_against_doc(d, jv_obj)

        # re-submit JV
        jv_obj = webnotes.get_obj('Journal Voucher',
                                  d['voucher_no'],
                                  with_children=1)
        jv_obj.make_gl_entries(cancel=0, adv_adj=1)
Esempio n. 4
0
def get_events(start, end, doctype,op,filters=None):
        webnotes.errprint(['hello',doctype, op])
        cnd =''
        if op:
                cnd = "and encounter = '%(pros)s'"%{"pros":op}

        from webnotes.widgets.reportview import build_match_conditions
        #if not webnotes.has_permission("Task"):
        #        webnotes.msgprint(_("No Permission"), raise_exception=1)

        conditions = build_match_conditions("Task")
        conditions and (" and " + conditions) or ""
        
        if filters:
                filters = json.loads(filters)
                for key in filters:
                        if filters[key]:
                                conditions += " and " + key + ' = "' + filters[key].replace('"', '\"') + '"'
        
        data = webnotes.conn.sql("""select name, start_time, end_time, 
                study, status,encounter from `tabPatient Encounter Entry`
                where  ((start_time between '%(start)s' and '%(end)s') \
                        or (end_time between '%(start)s' and '%(end)s')) %(cnd)s 
                %(conditions)s""" % {
                        "start": start,
                        "end": end,
                        "conditions": conditions,
                        "cnd":cnd
                }, as_dict=True, update={"allDay": 0},debug=1)

        return data
Esempio n. 5
0
def upload():
    from webnotes.utils.datautils import read_csv_content_from_uploaded_file
    from webnotes.modules import scrub

    rows = read_csv_content_from_uploaded_file()
    if not rows:
        msg = [_("Please select a csv file")]
        return {"messages": msg, "error": msg}
    columns = [scrub(f) for f in rows[4]]
    columns[0] = "name"
    columns[3] = "att_date"
    ret = []
    error = False

    from webnotes.utils.datautils import check_record, import_doc
    doctype_dl = webnotes.get_doctype("Attendance")

    for i, row in enumerate(rows[5:]):
        if not row: continue
        row_idx = i + 5
        d = webnotes._dict(zip(columns, row))
        d["doctype"] = "Attendance"
        if d.name:
            d["docstatus"] = webnotes.conn.get_value("Attendance", d.name,
                                                     "docstatus")

        try:
            check_record(d, doctype_dl=doctype_dl)
            ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True))
        except Exception, e:
            error = True
            ret.append('Error for row (#%d) %s : %s' %
                       (row_idx, len(row) > 1 and row[1] or "", cstr(e)))
            webnotes.errprint(webnotes.getTraceback())
Esempio n. 6
0
    def create_account_head(self):
        webnotes.errprint(
            [self.doc.company, self.doc.master_type, self.doc.account_type])
        if self.doc.company:
            abbr = self.get_company_abbr()
            if not webnotes.conn.exists("Account",
                                        (self.doc.name + " - " + abbr)):
                parent_account = self.get_receivables_group()
                # create
                ac_bean = webnotes.bean({
                    "doctype": "Account",
                    'account_name': self.doc.name,
                    'parent_account': parent_account,
                    'group_or_ledger': 'Ledger',
                    'company': self.doc.company,
                    'master_type': self.doc.master_type,
                    'master_name': self.doc.name,
                    "freeze_account": "No"
                })
                ac_bean.ignore_permissions = True
                ac_bean.insert()

                msgprint(
                    _("Account Head") + ": " + ac_bean.doc.name +
                    _(" created"))
        else:
            msgprint(
                _("Please Select Company under which you want to create account head"
                  ))
def get_events(start, end, doctype,op,filters=None):
        webnotes.errprint(['hello',doctype, op])
        cnd =''
        if op:
                cnd = "and encounter = '%(pros)s'"%{"pros":op}

        from webnotes.widgets.reportview import build_match_conditions
        #if not webnotes.has_permission("Task"):
        #        webnotes.msgprint(_("No Permission"), raise_exception=1)
        conditions = ''
        # conditions = build_match_conditions("Patient Encounter Entry")
        # conditions and (" and " + conditions) or ""
        
        if filters:
                filters = json.loads(filters)
                for key in filters:
                        if filters[key]:
                                conditions += " and " + key + ' = "' + filters[key].replace('"', '\"') + '"'
        
        data = webnotes.conn.sql("""select name, start_time, end_time, 
                study, status,encounter from `tabPatient Encounter Entry`
                where  ((start_time between '%(start)s' and '%(end)s') \
                        or (end_time between '%(start)s' and '%(end)s')) %(cnd)s 
                %(conditions)s""" % {
                        "start": start,
                        "end": end,
                        "conditions": conditions,
                        "cnd":cnd
                }, as_dict=True, update={"allDay": 0},debug=1)

        return data
Esempio n. 8
0
 def ledger_sync(self):
     unique_id = webnotes.conn.get_value("Global Defaults", None,
                                         "branch_id")
     acc_tables = [
         'tabCompany', 'tabFiscal Year', 'tabAccount', 'tabGL Entry'
     ]
     for table in acc_tables:
         if table == 'tabGL Entry':
             import MySQLdb
             db = MySQLdb.connect(self.doc.host_id, self.doc.remote_dbuser,
                                  self.doc.remote_dbuserpassword,
                                  self.doc.remote_dbname)
             cursor = db.cursor()
             webnotes.errprint(
                 "delete from `%(table)s` where name like '%(unique_id)s'" %
                 {
                     'table': table,
                     "unique_id": '%%%s%%' % unique_id
                 })
             cursor.execute(
                 "delete from `%(table)s` where name like '%(unique_id)s'" %
                 {
                     'table': table,
                     "unique_id": '%%%s%%' % unique_id
                 })
             cursor.execute("commit")
         self.local_to_remote(table)
Esempio n. 9
0
	def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0, 
		debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0, update=None):
		"""
		      * Execute a `query`, with given `values`
		      * returns as a dictionary if as_dict = 1
		      * returns as a list of lists (with cleaned up dates) if as_list = 1
		"""
		# in transaction validations
		self.check_transaction_status(query)
		
		# autocommit
		if auto_commit and self.in_transaction: self.commit()
		if auto_commit: self.begin()
			
		# execute
		try:
			if values!=():
				if isinstance(values, dict):
					values = dict(values)
				if debug: webnotes.errprint(query % values)
				self._cursor.execute(query, values)
				
			else:
				if debug: webnotes.errprint(query)
				self._cursor.execute(query)	
		except Exception, e:
			# ignore data definition errors
			if ignore_ddl and e.args[0] in (1146,1054,1091):
				pass
			else:
				raise e
Esempio n. 10
0
def savedocs():
    try:
        from webnotes.model.doclist import DocList
        form = webnotes.form_dict

        doclist = DocList()
        doclist.from_compressed(form.get('docs'), form.get('docname'))

        # action
        action = form.get('action')

        if action == 'Update': action = 'update_after_submit'

        getattr(doclist, action.lower())()

        # update recent documents
        webnotes.user.update_recent(doclist.doc.doctype, doclist.doc.name)

        # send updated docs
        webnotes.response['saved'] = '1'
        webnotes.response['main_doc_name'] = doclist.doc.name
        webnotes.response['docname'] = doclist.doc.name
        webnotes.response['docs'] = [doclist.doc] + doclist.children

    except Exception, e:
        webnotes.msgprint('Did not save')
        webnotes.errprint(webnotes.utils.getTraceback())
        raise e
Esempio n. 11
0
    def validate_incoming(self):
        """
			Checks support ticket email settings
		"""
        if self.doc.sync_support_mails and self.doc.support_host:
            from webnotes.utils.email_lib.receive import POP3Mailbox
            from webnotes.model.doc import Document
            import _socket, poplib

            inc_email = Document('Incoming Email Settings')
            inc_email.encode()
            inc_email.host = self.doc.support_host
            inc_email.use_ssl = self.doc.support_use_ssl
            try:
                err_msg = 'User Name or Support Password missing. Please enter and try again.'
                if not (self.doc.support_username
                        and self.doc.support_password):
                    raise AttributeError, err_msg
                inc_email.username = self.doc.support_username
                inc_email.password = self.doc.support_password
            except AttributeError, e:
                webnotes.msgprint(err_msg)
                raise
            webnotes.errprint("entrng pop3mailbox")
            pop_mb = POP3Mailbox(inc_email)
            webnotes.errprint(pop_mb)
            try:
                pop_mb.connect()
            except _socket.error, e:
                # Invalid mail server -- due to refusing connection
                webnotes.msgprint(
                    'Invalid POP3 Mail Server. Please rectify and try again.')
                raise
Esempio n. 12
0
def add_accounts(accounts_to_add, check_fn=None):
    for company, abbr in webnotes.conn.sql(
            """select name, abbr from `tabCompany`"""):
        count = webnotes.conn.sql(
            """select count(name) from `tabAccount`
			where company=%s and ifnull(parent_account, '')=''""", company)[0][0]

        if count > 4:
            webnotes.errprint(
                "Company" + company +
                "has more than 4 root accounts. cannot apply patch to this company."
            )
            continue

        for account_name, parent_account_name, group_or_ledger, account_type in accounts_to_add:
            if not webnotes.conn.sql(
                    """select name from `tabAccount` where account_name = %s 
					and company = %s""", (account_name, company)):
                parent_account = "%s - %s" % (parent_account_name, abbr)
                if check_fn:
                    parent_account = check_fn(parent_account, company)
                account = webnotes.bean({
                    "doctype": "Account",
                    "account_name": account_name,
                    "parent_account": parent_account,
                    "group_or_ledger": group_or_ledger,
                    "account_type": account_type,
                    "company": company
                })
                account.insert()
Esempio n. 13
0
def getdoc(doctype, name, user=None):
	"""
	Loads a doclist for a given document. This method is called directly from the client.
	Requries "doctype", "name" as form variables.
	Will also call the "onload" method on the document.
	"""

	import webnotes
	
	if not (doctype and name):
		raise Exception, 'doctype and name required!'
	
	if not name: 
		name = doctype

	if not webnotes.conn.exists(doctype, name):
		return []

	try:
		bean = webnotes.bean(doctype, name)
		bean.run_method("onload")

		doclist = bean.doclist

		# add file list
		set_docinfo(doctype, name)
		
	except Exception, e:
		webnotes.errprint(webnotes.utils.getTraceback())
		webnotes.msgprint('Did not load.')
		raise e
Esempio n. 14
0
def get_detail1(serial_no=None):
    if serial_no:
        #webnotes.errprint(serial_no)
        txt = serial_no
        check_data = webnotes.conn.sql(
            "select a.customer_name,a.phone_number from `tabCustomer Details` a,`tabCustomer Data` b  where b.serial_no='"
            + txt + "' and b.parent=a.name",
            as_list=1,
            debug=1)
        if check_data:
            detls = webnotes.conn.sql(
                "select item_code,warranty_expiry_date from `tabSerial No` where name='"
                + txt + "' ",
                as_list=1)
            return "Customer", check_data[0][0], check_data[0][1], detls[0][
                0], detls[0][1]
        else:
            data = webnotes.conn.sql(
                "select case when status='Delivered' then customer else warehouse end as data,status from `tabSerial No` where name='%s'"
                % (txt),
                as_dict=1,
                debug=1)
            webnotes.errprint(data)
            if data:
                if data[0]['status'] == 'Delivered':
                    ltq = "select lat,lon from `tabSub Franchise` where name='" + cstr(
                        data[0]['data']) + "'"
                    latlong = webnotes.conn.sql(
                        "select lat,lon from `tabSub Franchise` where name='" +
                        data[0]['data'] + "'",
                        as_dict=1)
                    #webnotes.errprint(ltq)
                    #webnotes.errprint(data[0]['data'])
                    #webnotes.errprint(latlong)
                    if latlong:
                        return 'sub franchise', data[0]['data'], latlong[0][
                            'lat'], latlong[0]['lon']
                    else:
                        return 'Customer', data[0]['data'], ''
                elif data[0]['status'] == 'Available' and data[0][
                        'data'] == 'Finished Goods - P':
                    return 'admin', data[0]['data']
                else:
                    #webnotes.errprint("else")
                    rs = webnotes.conn.sql(
                        "select account_id, password from tabFranchise where account_id='"
                        + data[0]['data'] + "'",
                        as_list=1)
                    #webnotes.errprint(data[0]['data'])
                    device_id = webnotes.conn.sql(
                        """select deviceID from Device where accountID = '%s'"""
                        % data[0]['data'],
                        as_list=1)
                    #if device_id:
                    webnotes.errprint(device_id[0][0])
                return 'usr', rs, device_id[0][0]
            else:
                return 'Not'
    else:
        return "Not"
Esempio n. 15
0
def get_modules(for_module=None):
    import importlib
    docs = {"_label": "Modules"}
    if for_module:
        modules = [for_module]
    else:
        modules = webnotes.conn.sql_list(
            "select name from `tabModule Def` order by name")

    docs["_toc"] = ["docs.dev.modules." + d for d in modules]
    for m in modules:
        prefix = "docs.dev.modules." + m
        mydocs = docs[m] = {
            "_icon": "th",
            "_label": m,
            "_toc":
            [prefix + ".doctype", prefix + ".page", prefix + ".py_modules"],
            "doctype": get_doctypes(m),
            "page": get_pages(m),
            #"report": {},
            "py_modules": {
                "_label": "Independent Python Modules for " + m,
                "_toc": []
            }
        }

        # add stand alone modules
        module_path = get_module_path(m)
        prefix = prefix + ".py_modules."
        for basepath, folders, files in os.walk(module_path):
            for f in files:
                f = cstr(f)
                if f.endswith(".py") and \
                 (not f.split(".")[0] in os.path.split(basepath)) and \
                 (not f.startswith("__")):

                    module_name = ".".join(
                        os.path.relpath(os.path.join(basepath, f),
                                        "../app").split(os.path.sep))[:-3]

                    # import module
                    try:
                        module = importlib.import_module(module_name)
                        # create a new namespace for the module
                        module_docs = mydocs["py_modules"][f.split(".")
                                                           [0]] = {}

                        # add to toc
                        mydocs["py_modules"]["_toc"].append(prefix +
                                                            f.split(".")[0])

                        inspect_object_and_update_docs(module_docs, module)
                    except TypeError, e:
                        webnotes.errprint("TypeError in importing " +
                                          module_name)
                    except IndentationError, e:
                        continue

                    module_docs["_label"] = module_name
                    module_docs["_function_namespace"] = module_name
Esempio n. 16
0
def getdoc(doctype, name, user=None):
    """
	Loads a doclist for a given document. This method is called directly from the client.
	Requries "doctype", "name" as form variables.
	Will also call the "onload" method on the document.
	"""

    import webnotes

    if not (doctype and name):
        raise Exception, 'doctype and name required!'

    if not name:
        name = doctype

    if not webnotes.conn.exists(doctype, name):
        return []

    try:
        bean = webnotes.bean(doctype, name)
        bean.run_method("onload")

        doclist = bean.doclist

        # add file list
        set_docinfo(doctype, name)

    except Exception, e:
        webnotes.errprint(webnotes.utils.getTraceback())
        webnotes.msgprint('Did not load.')
        raise e
Esempio n. 17
0
    def create_receiver_list(self):
        rec, where_clause = '', ''
        if self.doc.send_to == 'All Customer Contact':
            where_clause = self.doc.customer and " and customer = '%s'" % self.doc.customer or " and ifnull(customer, '') != ''"
        if self.doc.send_to == 'All Supplier Contact':
            where_clause = self.doc.supplier and " and ifnull(is_supplier, 0) = 1 and supplier = '%s'" % self.doc.supplier or " and ifnull(supplier, '') != ''"
        if self.doc.send_to == 'All Sales Partner Contact':
            where_clause = self.doc.sales_partner and " and ifnull(is_sales_partner, 0) = 1 and sales_partner = '%s'" % self.doc.sales_partner or " and ifnull(sales_partner, '') != ''"

        if self.doc.send_to in [
                'All Contact', 'All Customer Contact', 'All Supplier Contact',
                'All Sales Partner Contact'
        ]:
            rec = sql(
                "select CONCAT(ifnull(first_name,''),'',ifnull(last_name,'')), mobile_no from `tabContact` where ifnull(mobile_no,'')!='' and docstatus != 2 %s"
                % where_clause)
        elif self.doc.send_to == 'All Lead (Open)':
            rec = sql(
                "select lead_name, mobile_no from tabLead where ifnull(mobile_no,'')!='' and docstatus != 2 and status = 'Open'"
            )
        elif self.doc.send_to == 'All Employee (Active)':
            where_clause = self.doc.department and " and department = '%s'" % self.doc.department or ""
            where_clause += self.doc.branch and " and branch = '%s'" % self.doc.branch or ""
            rec = sql(
                "select employee_name, cell_number from `tabEmployee` where status = 'Active' and docstatus < 2 and ifnull(cell_number,'')!='' %s"
                % where_clause)
        elif self.doc.send_to == 'All Sales Person':
            rec = sql(
                "select sales_person_name, mobile_no from `tabSales Person` where docstatus != 2 and ifnull(mobile_no,'')!=''"
            )
        rec_list = ''
        for d in rec:
            rec_list += d[0] + ' - ' + d[1] + '\n'
        self.doc.receiver_list = rec_list
        webnotes.errprint(rec_list)
        def on_update(self):
                patient_id = None
                from datetime import datetime

                if self.doc.status == 'Canceled':
                        webnotes.conn.sql("update `tabPatient Encounter Entry` set docstatus = '1' where name = '%s'"%(self.doc.name))

                s1=(self.doc.start_time).split(':')
                s2=(self.doc.end_time).split(':')
                # date_a=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(s1[0]+":"+s1[1],'%H:%M').time()))
                # date_b=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(s2[0]+":"+s2[1],'%H:%M').time()))
                #webnotes.errprint(self.doc.entry_in_child)
                if self.doc.new_user == 1 and not self.doc.new_patient:
                        patient_id = self.make_patient()
                        self.doc.new_patient=patient_id
                        self.create_new_contact()
                        self.create_customer(patient_id)
                        self.create_account_head(patient_id)
                        self.doc.save()
                if self.doc.entry_in_child == 'False':
                        self.make_child_entry(patient_id)
                        #self.make_event()

                if not self.doc.eventid:
                        self.create_child()
                else:
                        webnotes.conn.sql("update `tabSlot Child` set slot='"+self.doc.appointment_slot+"', start_time='"+cstr(datetime.strptime(date_a,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"', end_time='"+cstr(datetime.strptime(date_b,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"' where encounter='"+self.doc.name+"'")
                        webnotes.errprint(date_a)
                        webnotes.conn.sql("update `tabEvent` set starts_on='"+cstr(datetime.strptime(date_a,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"', ends_on='"+cstr(datetime.strptime(date_b,'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M'))+"' where name='"+self.doc.eventid+"'",debug=1)

                if cint(self.doc.checked_in)==1: pass
Esempio n. 19
0
	def on_update(self):
	
		#webnotes.errprint(" in on_update")
		qry=webnotes.conn.sql(""" select event_type from tabEvent where starts_on>='%s' and
			ends_on<='%s' and service='%s' """%(self.doc.starts_on,self.doc.ends_on,self.doc.service),as_list=1)
              
		#t=[self.doc.event_type]
		#webnotes.errprint(t)
          	#webnotes.errprint(qry.count(t)==1)
		if self.doc.event_type=='Cancel':
			webnotes.conn.sql("update `tabSlot Child` set status='Cancel' where name='"+self.doc.slot+"'")

		for i in qry:
			
			if i==[self.doc.event_type]:
				
				if self.doc.event_type=='Confirm':
					t=qry.count([self.doc.event_type])
					if t==2:
						webnotes.msgprint("Sorry...!!One event is already confirmed for the given schedule",raise_exception=1)
					#break
				if self.doc.event_type=='Waiting':
					p=qry.count([self.doc.event_type])
					if p==1:
						webnotes.errprint("One Event is already  waiting for the given schedule")
					if p==3:
						
						webnotes.msgprint("Sorry..!!Already two event are waiting for the given schedule",raise_exception=1)
Esempio n. 20
0
def add_aii_cost_center():
    for company, abbr in webnotes.conn.sql(
            """select name, abbr from `tabCompany`"""):
        if not webnotes.conn.sql(
                """select name from `tabCost Center` where cost_center_name = 
				'Auto Inventory Accounting' and company_name = %s""", company):
            parent_cost_center = webnotes.conn.get_value(
                "Cost Center", {
                    "parent_cost_center['']": '',
                    "company_name": company
                })

            if not parent_cost_center:
                webnotes.errprint("Company " + company +
                                  "does not have a root cost center")
                continue

            cc = webnotes.bean({
                "doctype": "Cost Center",
                "cost_center_name": "Auto Inventory Accounting",
                "parent_cost_center": parent_cost_center,
                "group_or_ledger": "Ledger",
                "company_name": company
            })
            cc.insert()
Esempio n. 21
0
    def on_update(self):
        #lag = webnotes.conn.sql("select ifnull(name,'') from tabProfile where name='"+self.doc.email+"'",as_list=1,debug=1)
        self.check_valid_priority()

        check_name = webnotes.conn.sql(
            "select name from `tabCustomer` where name='" + self.doc.name +
            "'",
            as_list=1,
            debug=1)
        webnotes.errprint(['name', check_name])

        if not check_name:
            self.doc.master_type = "Patient Register"
            cust = self.create_customer()
            self.create_account_head(cust)
            #self.create_customer()

        if self.doc.flag == 'false':
            self.create_profile()
            self.generate_barcode()
            #self.validate()

            self.create_new_contact()
            a = webnotes.conn.sql(
                "select name from `tabEncounter` where parent='" +
                self.doc.name + "'",
                as_list=1)
            if not a:
                webnotes.errprint("hii uygsiuc sdfuksghfui")
                self.create_patient_encounter_entry()
            self.doc.flag = 'True'
            self.doc.save()
Esempio n. 22
0
    def send(self):
        """
			* Execute get method
			* Send email to recipients
		"""
        if not self.doc.recipient_list: return

        self.sending = True
        result, email_body = self.get()

        recipient_list = self.doc.recipient_list.split("\n")

        # before sending, check if user is disabled or not
        # do not send if disabled
        profile_list = webnotes.conn.sql(
            "SELECT name, enabled FROM tabProfile", as_dict=1)
        for profile in profile_list:
            if profile['name'] in recipient_list and profile['enabled'] == 0:
                del recipient_list[recipient_list.index(profile['name'])]

        from webnotes.utils.email_lib import sendmail
        try:
            #webnotes.msgprint('in send')
            sendmail(recipients=recipient_list,
                     sender='*****@*****.**',
                     reply_to='*****@*****.**',
                     subject=self.doc.frequency + ' Digest',
                     msg=email_body,
                     from_defs=1)
        except Exception, e:
            webnotes.msgprint(
                'There was a problem in sending your email. Please contact [email protected]'
            )
            webnotes.errprint(webnotes.getTraceback())
Esempio n. 23
0
	def validate_userid_and_franchise(self):
		franchise=webnotes.conn.sql("select name from `tabFranchise` where account_id='%s' and user_id='%s'"%(self.doc.account_id,self.doc.user_id),as_list=1)
		webnotes.errprint(franchise)
		if franchise:
			webnotes.errprint(franchise[0][0])
			if franchise[0][0]!=self.doc.name:
				msgprint("This UserID and Franchise used in another territory..Record not save.",raise_exception=1)
Esempio n. 24
0
 def create_receiver_list(self):
   rec, where_clause = '', ''   
   if self.doc.cus == 'All Customer Contact':
     where_clause = self.doc.customer and " and customer = '%s'" % self.doc.customer or " and ifnull(is_customer, 0) = 1"
   if self.doc.cus == 'All Supplier Contact':
     where_clause = self.doc.supplier and "  and supplier = '%s'" % self.doc.supplier or " and ifnull(is_supplier, 0) = 1"
   if self.doc.cus == 'All Sales Partner Contact':
     where_clause = self.doc.sales_partner and "  and sales_partner = '%s'" % self.doc.sales_partner or " and ifnull(is_sales_partner, 0) = 1"
   if self.doc.cus in ['All Customer Contact', 'All Supplier Contact', 'All Sales Partner Contact']:
     rec = sql("select CONCAT(ifnull(first_name,''),' ',ifnull(last_name,'')), mobile_no from `tabContact` where ifnull(mobile_no,'')!='' and docstatus != 2 %s" % where_clause)
   elif self.doc.cus == 'All Lead (Open)':
     rec = sql("select lead_name, mobile_no from tabLead where ifnull(mobile_no,'')!='' and docstatus != 2 and status = 'Open'")
   elif self.doc.cus == 'All Employee (Active)':
     where_clause = self.doc.department and " and department = '%s'" % self.doc.department or ""
     where_clause += self.doc.branch and " and branch = '%s'" % self.doc.branch or ""
     rec = sql("select employee_name, cell_number from `tabEmployee` where status = 'Active' and docstatus < 2 and ifnull(cell_number,'')!='' %s" % where_clause)
   elif self.doc.cus == 'All Sales Person':
     rec = sql("select sales_person_name, mobile_no from `tabSales Person` where docstatus != 2 and ifnull(mobile_no,'')!=''")
   elif self.doc.cus == 'All Contact':
     rec = sql("select first_name,mobile_no from `tabContact` where ifnull(mobile_no,'')!=''")
   else:
     rec=sql("select cont_name,ph_no from `tabSub Contact` where parent='"+self.doc.cus+"'")
   rec_list = ''
   for d in rec:
     rec_list += d[0] + ' - ' + d[1] + '\n'
   self.doc.receiver_list = rec_list
   webnotes.errprint(rec_list)
Esempio n. 25
0
        def get_weekly_off_date_list(self, year_start_date, year_end_date):
                from webnotes.utils import getdate
                year_start_date, year_end_date = getdate(year_start_date), getdate(year_end_date)

                from dateutil import relativedelta
                from datetime import timedelta
                import calendar

                date_list = []
                date_list1 = []
                if self.doc.weekly_off=='3rd Saturday':
                        webnotes.errprint(self.doc.weekly_off)
                        weekday = getattr(calendar, ('Saturday').upper())
                        reference_date = year_start_date + relativedelta.relativedelta(weekday=weekday)
                        while reference_date <= year_end_date:
                                date_list1.append(reference_date)
                                reference_date += timedelta(days=7)
                        for dt in date_list1:
                                if dt.day>14 :
                                        if dt.day <22:
                                                #webnotes.errprint(dt)
                                                ch = addchild(self.doc, 'holiday_list_details', 'Holiday', self.doclist)
                                                ch.description = self.doc.weekly_off
                                                ch.holiday_date = dt
                        return date_list
                else:
                        weekday = getattr(calendar, (self.doc.weekly_off).upper())
                        reference_date = year_start_date + relativedelta.relativedelta(weekday=weekday)
                        while reference_date <= year_end_date:
                                date_list.append(reference_date)
                                reference_date += timedelta(days=7)
                        return date_list
Esempio n. 26
0
	def send(self):
		"""
			* Execute get method
			* Send email to recipients
		"""
		if not self.doc.recipient_list: return

		self.sending = True
		result, email_body = self.get()
		
		recipient_list = self.doc.recipient_list.split("\n")

		# before sending, check if user is disabled or not
		# do not send if disabled
		profile_list = webnotes.conn.sql("SELECT name, enabled FROM tabProfile", as_dict=1)
		for profile in profile_list:
			if profile['name'] in recipient_list and profile['enabled'] == 0:
				del recipient_list[recipient_list.index(profile['name'])]

		from webnotes.utils.email_lib import sendmail
		try:
			#webnotes.msgprint('in send')
			sendmail(
				recipients=recipient_list,
				sender='*****@*****.**',
				reply_to='*****@*****.**',
				subject=self.doc.frequency + ' Digest',
				msg=email_body,
				from_defs=1
			)
		except Exception, e:
			webnotes.msgprint('There was a problem in sending your email. Please contact [email protected]')
			webnotes.errprint(webnotes.getTraceback())
Esempio n. 27
0
	def on_update(self):
		webnotes.errprint("Hiii...")
		a=webnotes.conn.sql("select device_id from tabVehicle where account_id='"+self.doc.account_id+"'")
		webnotes.errprint(a)
		self.doc.device_id = a
		ss=get_sub_franchise()
		b=get_date_details()
		self.generate_visiting_schedule(b,ss)
Esempio n. 28
0
 def run_trigger(self, method='on_login'):
     try:
         from startup import event_handlers
         if hasattr(event_handlers, method):
             getattr(event_handlers, method)(self)
         return
     except ImportError, e:
         webnotes.errprint(str(e))
	def create_customer(self):
		webnotes.errprint('customer creation starts')
		from webnotes.model.doc import Document
		d = Document('Customer')
		d.customer_name = self.doc.name
		d.gender = self.doc.gender
		d.full_name = self.doc.customer_name	
		d.save()
		webnotes.errprint(d.name)
Esempio n. 30
0
	def validate_master_name(self):
		"""Remind to add master name"""
		webnotes.errprint([self.doc.company,self.doc.master_type, self.doc.account_type])
		if self.doc.master_type in ('Customer', 'Supplier') or self.doc.account_type == "Warehouse":
			if not self.doc.master_name:
				msgprint(_("Please enter Master Name once the account is created."))
			elif not webnotes.conn.exists(self.doc.master_type or self.doc.account_type, 
					self.doc.master_name):
				webnotes.throw(_("Invalid Master Name"))
Esempio n. 31
0
def get_study_time(study, modality):
    res = webnotes.conn.sql(
        "select time from `tabModality Mapper` where parent ='%s' and modality= '%s'"
        % (study, modality),
        as_dict=1,
        debug=1)
    if res[0]['time']:
        webnotes.errprint(res)
        return cint(res[0]['time'])
Esempio n. 32
0
 def fetch_details(self):
     webnotes.errprint("server")
     res = webnotes.conn.sql(
         "select city,pin_code from `tabPin Codes` where name=%s",
         self.doc.city_pin_code,
         debug=1)
     webnotes.errprint(res)
     ret = {'city': res and res[0][0], 'pin_code': res and res[0][1]}
     return ret
Esempio n. 33
0
 def get_item(self, item):
     webnotes.errprint("in item")
     qry = webnotes.conn.sql(
         "select description from `tabItem` where name=%s", item, as_list=1)
     qr = webnotes.conn.sql(
         "select default_warehouse from `tabItem` where name=%s",
         item,
         as_list=1)
     return {'description': qry[0][0], 'warehouse': qr[0][0]}
Esempio n. 34
0
    def add_to_hosts(self, site_name):
        webnotes.errprint("host")
        with open('/etc/hosts', 'rt') as f:
            s = f.read() + '\n' + '127.0.0.1\t\t\t %s \n' % site_name
            with open('hosts', 'wt') as outf:
                outf.write(s)

        os.system(
            'echo MedSynaptic | sudo -S mv {path}/hosts /etc/hosts'.format(
                path=get_base_path()))
Esempio n. 35
0
def cancel(doctype=None, name=None):
    """cancel a doclist"""
    try:
        wrapper = webnotes.bean(doctype, name)
        wrapper.cancel()
        send_updated_docs(wrapper)

    except Exception, e:
        webnotes.errprint(webnotes.utils.getTraceback())
        webnotes.msgprint(webnotes._("Did not cancel"))
        raise
Esempio n. 36
0
	def save_main(self):
		try:
			self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
		except NameError, e:
			webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))

			# prompt if cancelled
			if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
				webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
			webnotes.errprint(webnotes.utils.getTraceback())
			raise e