Example #1
0
def handleError(msg, user=None):
    RES.write(
        handy.trim('''
        <html>
        <title>error</title>
        <style type="text/css">
        body, p, table {
            font-family: verdana, arial, helvetica;
            font-size: 10pt;
        }
        body {
            background: #eeeeee;
        }
        h1 {
           font-size: 10pt;
           background: gold;
           padding-left: 10px;
        }
        p { padding-bottom: 10px;
            padding-left: 10px;
            margin: 0px; }
        </style>
        </head>
        <div style="background: white">
          <h1>error</h1>
          <p>%s</p>
          <p style="color: gray">
           An email has been sent to the administrator.<br/>
           Please try back in a little while.
          </p>
        </div>
        ''') % msg)
    trace = "".join(
        traceback.format_exception(sys.exc_type, sys.exc_value,
                                   sys.exc_traceback))
    trace += "\n"
    trace += "query: %s\n" % str(REQ.query)
    trace += "form: %s\n" % str(REQ.form)
    trace += "session: %s\n" % str(SESS)
    if TEST_MODE:
        RES.write("<pre>")
        RES.write(trace)
        RES.write("</pre>")
    RES.write("</html>")
    try:
        uname = getattr(user, "username", "(unknown)")
        handy.sendmail((handy.trim("""
            To: [email protected]
            From: [email protected]
            Subject: error in control panel

            user: %s
            this error was trapped with message:
            %s
            ------------------------------------
            """) % (msg, uname)) + trace)
    except:
        raise
        pass  # oh well.
    raise Finished
Example #2
0
def handleError(msg, user=None):
    RES.write(handy.trim(
        '''
        <html>
        <title>error</title>
        <style type="text/css">
        body, p, table {
            font-family: verdana, arial, helvetica;
            font-size: 10pt;
        }
        body {
            background: #eeeeee;
        }
        h1 {
           font-size: 10pt;
           background: gold;
           padding-left: 10px;
        }
        p { padding-bottom: 10px;
            padding-left: 10px;
            margin: 0px; }
        </style>
        </head>
        <div style="background: white">
          <h1>error</h1>
          <p>%s</p>
          <p style="color: gray">
           An email has been sent to the administrator.<br/>
           Please try back in a little while.
          </p>
        </div>
        ''') % msg)
    trace = "".join(traceback.format_exception(
        sys.exc_type, sys.exc_value, sys.exc_traceback))
    trace += "\n"
    trace += "query: %s\n" % str(REQ.query)
    trace += "form: %s\n" % str(REQ.form)
    trace += "session: %s\n" % str(SESS)
    if TEST_MODE:        
        RES.write("<pre>")
        RES.write(trace)
        RES.write("</pre>")
    RES.write("</html>")
    try:
        uname = getattr(user, "username", "(unknown)")
        handy.sendmail((handy.trim(
            """
            To: [email protected]
            From: [email protected]
            Subject: error in control panel

            user: %s
            this error was trapped with message:
            %s
            ------------------------------------
            """) % (msg, uname)) + trace)
    except:
        raise
        pass # oh well. 
    raise Finished
Example #3
0
def emailCustomer(acc, result, details, lastfour, amount):
    model = {}
    model["email"] = acc.email
    model["fname"] = acc.fname
    model["brand"] = acc.brand
    model["account"] = acc.account
    model["lastfour"] = lastfour
    model["amount"] = amount
    model["result"] = result
    model["details"] = details
    model["signature"] = open("/home/sei/.signature").read()

    model['fromAddr'] = FROM
    message = handy.trim("""
        From: %(fromAddr)s
        To: %(email)s
        BCC: %(fromAddr)s
        Subject: credit card denied

        Hi %(fname)s,

        Your %(brand)s account (username %(account)s)
        is set up for automatic billing, and my system
        just attempted to post a charge of $%(amount)s
        to your credit card - the one with the number
        ending in %(lastfour)s. The bank responded
        with the following error:

            %(result)s
            %(details)s

        Could you please look into this? If you would like
        to use a different means of payment or enter a
        different card, you can do so here:

            http://%(brand)s.com/payment/

        If the only thing that has changed is the expiration
        date on your card, you can just email me the new
        date.

        Thanks!

        %(signature)s
        """) % model

    action = "e"
    while 1:
        if action == "e":
            message = handy.edit(message)
        elif action == "s":
            handy.sendmail(message)
            break
        elif action == "a":
            break
        action = raw_input("[e]dit, [a]bandon, [s]end? ")
Example #4
0
    def act_send(self):
        msg_from = self.input["from"]
        msg_to = self.input["to"]
        msg = self.input["message"]
        cc = self.input["cc"]
        bcc = self.input["bcc"]
        subject = self.input["subject"]

        sendmail("From: %s\nTo: %s\nCC: %s\nBCC: %s\nSubject: %s\n%s" \
                 % (msg_from, msg_to, cc, bcc, subject, msg))

        print >> self, "message sent!"
Example #5
0
    def act_send(self):
        msg_from = self.input["from"]
        msg_to = self.input["to"]
        msg = self.input["message"]
        cc = self.input["cc"]
        bcc = self.input["bcc"]
        subject = self.input["subject"]

        sendmail("From: %s\nTo: %s\nCC: %s\nBCC: %s\nSubject: %s\n%s" \
                 % (msg_from, msg_to, cc, bcc, subject, msg))

        print >> self, "message sent!"
Example #6
0
    def sendError(self):
        SITE_MAIL = self.eng.globals["SITE_MAIL"]
        SITE_NAME = self.eng.globals["SITE_NAME"]
        assert SITE_MAIL is not None, "must define SITE_MAIL first!"
        hr = "-" * 50 + "\n"
        msg = trim(
            """
            To: %s
            From: cgi <%s>
            Subject: uncaught exception in %s

            """ % (SITE_MAIL, SITE_MAIL, SITE_NAME))
        msg += "uncaught exception in %s\n\n" % self.eng.request.pathInfo
        msg += hr
        msg += str(self.eng.error)
        msg += hr
        msg += "FORM: %s\n"  % self.eng.request.form
        msg += "QUERYSTRING: %s\n" % self.eng.request.query.string
        msg += "COOKIE: %s\n" % self.eng.request.cookie

        if hasattr(self, "sess"):
            msg += "SESSION DATA:\n"
            for item in self.eng.sess.keys():
                msg += item + ': '
                try:
                    msg += self.eng.sess[item] + "\n"
                except:
                    msg += "(can't unpickle)\n"
        else:
            msg += "NO SESSION DATA\n"
        msg += hr
        msg += "OUTPUT:\n\n"
        msg += self.eng.response.getHeaders() + "\n"
        msg += self.eng.response.buffer + "\n"
        msg += hr

        msg.encode("utf-8")

        sendmail(msg)
Example #7
0
    def sendError(self):
        SITE_MAIL = self.eng.globals["SITE_MAIL"]
        SITE_NAME = self.eng.globals["SITE_NAME"]
        assert SITE_MAIL is not None, "must define SITE_MAIL first!"
        hr = "-" * 50 + "\n"
        msg = trim("""
            To: %s
            From: cgi <%s>
            Subject: uncaught exception in %s

            """ % (SITE_MAIL, SITE_MAIL, SITE_NAME))
        msg += "uncaught exception in %s\n\n" % self.eng.request.pathInfo
        msg += hr
        msg += str(self.eng.error)
        msg += hr
        msg += "FORM: %s\n" % self.eng.request.form
        msg += "QUERYSTRING: %s\n" % self.eng.request.query.string
        msg += "COOKIE: %s\n" % self.eng.request.cookie

        if hasattr(self, "sess"):
            msg = msg + "SESSION DATA:\n"
            for item in self.eng.sess.keys():
                msg += item + ': '
                try:
                    msg += self.eng.sess[item] + "\n"
                except:
                    msg += "(can't unpickle)\n"
        else:
            msg += "NO SESSION DATA\n"
        msg += hr
        msg += "OUTPUT:\n\n"
        msg += self.eng.response.getHeaders() + "\n"
        msg += self.eng.response.buffer + "\n"
        msg += hr

        msg.encode("utf-8")

        sendmail(msg)
Example #8
0
    boxes_to_restart = {}

    for acc in r.dueAccounts():
        if (acc.account in GRACED) or (acc.graced):
            continue

        # still here, so:
        due45, due30, due15, due0 = r.separate_ages(acc.aging())
        pastdue = due45 + due30 + due15
        total = pastdue + due0
        if due45:

            if acc.status == 'active':
                mail = makemail(acc.account, acc.email, acc.fname, acc.lname,
                                total, pastdue, acc.brand)
                handy.sendmail(mail)
                acc.status = 'warned'
                acc.warned = Date("today")
                clerk.store(acc)
                print "warned account %s" % acc.account

            elif acc.status == 'warned':
                if acc.warned < Date("today") - 2:
                    acc.status = 'locked'
                    clerk.store(acc)
                    print "locked account %s" % acc.account
                    try:
                        user = uclerk.match(User, username=acc.account)[0]
                        user.status = 'locked'
                        boxes_to_restart[user.server.name] = 1
                        uclerk.store(user)
Example #9
0
 def sendCurrentStatement(self):
     sendmail(zebra.fetch("statement", self.currentStatement()))
Example #10
0
 def sendCurrentStatement(self):
     sendmail(zebra.fetch("statement", self.currentStatement()))
Example #11
0
def sendStatement(acc):
    fromAddr = FROM
    fname, name, email, stmt, grand = makeStatement(acc)
    #if acc.company:
    #    fname = acc.company
    pastDue = acc.amountPastDue(lastDue)
    brand = acc.brand.title().replace('Dcd', 'DCD')
    if brand == 'DCD hosting': pastDue = None # TODO: fix this!
    header =[trim(
        """
        From: %(fromAddr)s
        To: %(name)s <%(email)s>
        """ % locals())]
    if acc.email2:
        header.append("CC: %s\n" % acc.email2)
    header.append(trim(
        """
        Subject: %(brand)s statement [$%(grand)s]
        """ % locals()))
    header = "".join(header)

    if grand <= 0:
        grand_msg = "You owe nothing at this time.\n"
    else:
        if pastDue:
            grand_msg = trim(
                """
                Amount Due: $%s.

                ** NOTE: YOUR ACCOUNT IS PAST DUE.
                ** PLEASE PAY YOUR BILL IMMEDIATELY.

                """ % (grand))
        elif acc.autobill and acc.lastfour:
            grand_msg = trim(
                """
                Amount Due: $%s.

                This amount will be charged to your credit
                card after 48 hours. The card we have on
                file for you ends with %s.

                """) % (grand, acc.lastfour)
        else:
            grand_msg = trim(
                """
                Amount Due: $%s.

                Please pay this amount by %s.

                """)  % (grand, nextDue)

        ## now cap it off:
        brand = acc.brand
        if brand == 'DCD hosting': brand='cornerhost'
        grand_msg += trim(
            """
            You may pay via credit card, PayPal, check
            or money order. For details, visit:

                http://www.%s.com/payment/

            Remember, you can pay by the month *or* by the
            year. If you would like to change your billing
            cycle, just drop me a note when you pay your bill.
            """ % brand)


    #@TODO: strip out my name. get this whole thing into genshi or something.
    msg = trim(
        """
        =============================================================

        Hello %s,

        This is your statement for %s.

        %s
        Thanks!

        Michal J Wallace
        http://www.%s.com/

        =============================================================
        """) % (fname, acc.brand, grand_msg, acc.brand.replace(' ',''))


    if (grand <= 0) and acc.statementStrategy=="ifBalance":
        print "no statement sent for %s (%s) : no balance due" % (name, acc.account)
    else:
        print "sending statement for %s (%s): $%s" % (name, acc.account, grand)
        sys.stdout.flush()
        #print header + msg + stmt
        sendmail(header + msg + stmt)
Example #12
0
def main():
    opts, args = parseCommandLine()

    clerk = duckbill.config.makeClerk()
    dbc = clerk.storage.dbc

    accts = getAccountsToBill(Receivables(dbc, clerk))
    #accts = clerk.match(Account, account="ftempy")
    total = sum([a.balance() for a in accts])
    count = len(accts)

    if count == 0:
        sys.exit()

    if opts.notify:
        detail = "\n".join(
            ["    %s : %s" % (a.account, a.balance()) for a in accts])
        handy.sendmail(
            handy.trim("""
            To: %s
            From: %s
            Subject: time to run cards
            
            you have %s account(s), worth %s ready for autobill

            %s
            """) % (FROM, FROM, count, total, detail))
    else:
        # get passphrase and decrypt the cards:
        while True:
            phrase = getpass.getpass("passphrase: ")
            try:
                for acc in accts:
                    #print acc.account,
                    #print acc.cardinfo.isEncrypted()
                    acc.cardinfo.decrypt(phrase)
                break
            except ValueError, e:
                if str(e).count("I/O operation on closed file"):
                    print "nope"
                else:
                    raise

        ## @TODO: this has to come after gpg stuff because otherwise
        ## duckpag changes os.environ["GNUPG"] -- but WHY?!?!
        import os
        tmp = os.environ.get("GNUPGHOME")
        import duckpay
        if tmp:
            os.environ["GNUPGHOME"] = tmp
        else:
            del os.environ["GNUPGHOME"]

        ## @TODO: clean this mess up!! #########################
        sys.path.insert(0, "/home/sei/lib/ensemble")
        import ensemble
        perl = ensemble.Director("/home/sei/lib/ensemble/ensemble.pl")
        perl.loadModule("CyberSourceAuth", "cybs")
        assert perl.cybs.okay(), "didn't load okay"
        ########################################################

        import reasons

        # now charge them:
        for acc in accts:

            amount = acc.balance()
            if amount == 0: continue
            print "%s ($%s):" % (acc.account, amount),
            sys.stdout.flush()
            if not opts.batch:
                if raw_input("[yes|no]").lower() not in ["y", "yes"]:
                    continue

            # this is basically stolen from process.cgi:
            if " " not in acc.cardinfo.owner:
                print "bad card owner: %s" % acc.cardinfo.owner
                owner = raw_input("enter new name: ")
                if not owner.strip():
                    print "skipping..."
                else:
                    acc.cardinfo.owner = owner.strip()
                    acc.cardinfo.encrypt()
                    #@TODO: touching cardinfo should make acc.isDirty=True
                    acc.private.isDirty = True
                    clerk.store(acc)
                    print "updated...",
                print "will try again next time"
                continue

            fname, lname = acc.cardinfo.owner.split(" ", 1)
            orderid = handy.uid()
            request = {
                "ccAuthService_run": "true",
                "merchantReferenceCode": orderid,
                "billTo_firstName": fname,
                "billTo_lastName": lname,
                "card_expirationMonth": acc.cardinfo.expire.m,
                "card_expirationYear": acc.cardinfo.expire.y,
                "billTo_street1": acc.address1,
                "billTo_city": acc.city,
                "billTo_state": acc.state,
                "billTo_postalCode": acc.postal,
                "billTo_country": acc.countryCD,
                "billTo_email": acc.email,
                "card_accountNumber": acc.cardinfo.number,
                "sei_userid": acc.account,
                "purchaseTotals_currency": "USD",
                "purchaseTotals_grandTotalAmount": str(amount),
            }

            # do it:
            status, reply = perl.cybs.auth(request)

            if status != 0:
                print "SYSTEM ERROR"
                pprint.pprint(reply)

            elif reply["decision"] in ["ERROR", "REJECT"]:
                pprint.pprint(request)
                pprint.pprint(reply)
                reason = str(reasons.code[int(reply["reasonCode"])][0])
                print "###", reason, "#####"
                if opts.batch: continue
                if raw_input("send email? ").lower() in ("y", "yes"):
                    emailCustomer(acc, reply["decision"],
                                  (reason + "\n" + pprint.pformat(reply)),
                                  acc.cardinfo.number[-4:], amount)
            else:
                print reply["decision"], amount, orderid
                duckpay.post("bofa",
                             acc.account,
                             amount,
                             orderid,
                             note="autopayment - thank you!")
Example #13
0
    for acc in r.dueAccounts():
        if (acc.account in GRACED) or (acc.graced):
            continue
        
        # still here, so:
        due45, due30, due15, due0 = r.separate_ages(acc.aging())        
        pastdue = due45 + due30 + due15
        total = pastdue + due0
        if due45:

            if acc.status =='active':
                mail = makemail(acc.account, acc.email,
                                acc.fname, acc.lname,
                                total, pastdue, acc.brand)
                handy.sendmail(mail)
                acc.status = 'warned'
                acc.warned = Date("today")
                clerk.store(acc)
                print "warned account %s" % acc.account


            elif acc.status =='warned':
                if acc.warned < Date("today") - 2:
                    acc.status = 'locked'
                    clerk.store(acc)
                    print "locked account %s" % acc.account
                    try:
                        user = uclerk.match(User, username=acc.account)[0]
                        user.status='locked'
                        boxes_to_restart[user.server.name] = 1