def refund_kwh(self, cursor, uid,
                   contract_id, first_date, last_date, fare_id, period_id, kwh,
                   partner_id, context=None):
        """Refunds the indicated kwh, marking them as available again, for the
           contract, date interval, fare and period and returns the ones
           efectively used.
        """
        logger = netsvc.Logger()

        fare, period = self.get_fare_name_by_id(cursor, uid, fare_id, period_id)

        partner2member = dict(self.get_members_by_partners(cursor, uid, [partner_id], context=context))
        try:
            member_id = partner2member[partner_id]
        except KeyError:
            return 0

        txt = (u'{kwh} Generation kwh of member {member} to {contract} '
               u'for period {period} between {start} and {end}').format(
             contract=contract_id,
             period=period,
             start=first_date,
             end=last_date,
             member=member_id,
             kwh=kwh
        )
        logger.notifyChannel('gkwh_dealer REFUND', netsvc.LOG_INFO, txt)

        dealer = self._createDealer(cursor, uid, context)
        res = dealer.refund_kwh(
            contract_id,
            isodate(first_date),
            isodate(last_date),
            fare, period, kwh, member_id)
        return int(res)
    def retrieveMeasuresFromPlants(self, cursor, uid, pid, start, end, context=None):
        logger = netsvc.Logger()
        productionLoader = self._createProductionLoader(cursor, uid, pid, context)
        productionLoader.retrieveMeasuresFromPlants(isodate(start), isodate(end))

        logger.notifyChannel('gkwh_productionLoader UPDATE', netsvc.LOG_INFO,
                'Retrieve measurements from plant')
 def rights_per_share(self, cursor, uid,
         nshares, firstDate, lastDate,
         context=None):
     rights = RightsPerShare(mdbpool.get_db())
     return list(int(i) for i in rights.rightsPerShare(nshares,
             isodate(firstDate),
             isodate(lastDate)
             ))
 def member_shares(self, cursor, uid, member, start, stop, context=None):
     investment = InvestmentProvider(self, cursor, uid, context)
     memberActiveShares = MemberSharesCurve(investment)
     return [ int(num) for num in memberActiveShares.hourly(
         isodate(start),
         isodate(stop),
         member,
         )]
def listactive(nshares=None,start=None,end=None):
    genkwh_obj = c.model('generationkwh.testhelper')
    rights = genkwh_obj.rights_per_share(nshares, start, end)
    start=isodate(start)
    end=isodate(end)
    ndays=(end-start).days+1
    rights=np.reshape(rights,(ndays,25))
    dates=datespan(start,end)
    for _date,_rights in zip(dates,rights):
        print _date,_rights
 def usage(self, cursor, uid,
         member_id, first_date, last_date,
         context=None):
     rightsUsage = MemberRightsUsage(mdbpool.get_db())
     result = list(int(i) for i in rightsUsage.usage(
         member_id,
         isodate(first_date),
         isodate(last_date)
         ))
     return result
 def setup_rights_per_share(self, cursor, uid,
         nshares, firstDate, data,
         context=None):
     rightsPerShare = RightsPerShare(mdbpool.get_db())
     rightsPerShare.updateRightsPerShare(nshares, isodate(firstDate), data)
     remainders = RemainderProvider(self, cursor, uid, context)
     lastDate = isodate(firstDate) + datetime.timedelta(days=(len(data)+24)%25)
     remainders.updateRemainders([
         (nshares, isodate(firstDate), 0),
         (nshares, lastDate, 0),
         ])
    def dealer_is_active(self, cursor, uid,
            contract_id, start, stop,
            context=None):

        GenerationkWhDealer = self.pool.get('generationkwh.dealer')
        dealer = GenerationkWhDealer._createDealer(cursor, uid, context)
        result = dealer.is_active(
            contract_id,
            isodate(start),
            isodate(stop),
            )
        return result
 def unassignedInvestors(self, cursor, uid, effectiveOn, purchasedUntil, force, insist, context=None):
     """
         Returns all the members that have investments but no assignment
         has been made.
     """
     cursor.execute("""
         SELECT
             investment.member_id AS id
         FROM
             generationkwh_investment AS investment
         JOIN
             somenergia_soci as member
             ON member.id = investment.member_id
         LEFT JOIN
             generationkwh_assignment AS assignment
             ON assignment.member_id = investment.member_id
         WHERE
             -- Investment is active
             investment.active AND
             -- Has no assigment (unless forced)
             (
                 %(force)s IS NOT NULL OR
                 assignment.id IS NULL
             ) AND
             -- Has not been notified of an assigment (unless 'insisted')
             (
                 %(insist)s IS NOT NULL OR
                 NOT member.gkwh_assignment_notified
             ) AND
             -- Purchased not after lastPurchaseDate
             (
                 %(lastPurchaseDate)s IS NULL OR
                 investment.purchase_date <= %(lastPurchaseDate)s
             ) AND
             -- First effective date not after lastFirstEffectiveDate
             (
                 %(lastFirstEffectiveDate)s IS NULL OR
                 investment.first_effective_date <= %(lastFirstEffectiveDate)s
             ) AND
             TRUE
         GROUP BY
             investment.member_id
         ORDER BY
             investment.member_id
         """, dict(
             force = force or None,
             insist = insist or None,
             lastPurchaseDate = purchasedUntil and isodate(purchasedUntil),
             lastFirstEffectiveDate = effectiveOn and isodate(effectiveOn),
         ))
     result = [ id for id, in cursor.fetchall() ]
     return result
    def usagetracker_available_kwh(self, cursor, uid,
            member, start, stop, fare, period,
            context=None):

        GenerationkWhDealer = self.pool.get('generationkwh.dealer')
        usageTracker = GenerationkWhDealer._createTracker(cursor, uid, context)
        result = usageTracker.available_kwh(
            member,
            isodate(start),
            isodate(stop),
            fare,
            period
            )
        return result
    def effective_investments(self, cursor, uid,
            member, start, end,
            context=None):

        return [
            ns(
                member=member,
                firstEffectiveDate=first and isodate(first),
                lastEffectiveDate=last and isodate(last),
                shares=shares,
            )
            for member, first, last, shares
            in self.effective_investments_tuple(cursor, uid, member, start, end, context)
        ]
    def dealer_use_kwh(self, cursor, uid,
            contract, start, stop, fare, period, kwh,
            context=None):

        GenerationkWhDealer = self.pool.get('generationkwh.dealer')
        dealer = GenerationkWhDealer._createDealer(cursor, uid, context)
        result = dealer.use_kwh(
            contract,
            isodate(start),
            isodate(stop),
            fare,
            period,
            kwh,
            )
        return result
    def is_active(self, cursor, uid,
                  contract_id, first_date, last_date,
                  context=None):
        """ Returns True if contract_id has generation kwh activated
            during the period"""
        dealer = self._createDealer(cursor, uid, context)

        if type(first_date) != datetime.date:
            first_date = isodate(first_date)

        if type(last_date) != datetime.date:
            last_date = isodate(last_date)

        return dealer.is_active(
            contract_id, first_date, last_date)
 def rights_kwh(self, cursor, uid, member, start, stop, context=None):
     investment = InvestmentProvider(self, cursor, uid, context)
     memberActiveShares = MemberSharesCurve(investment)
     rightsPerShare = RightsPerShare(mdbpool.get_db())
     remainders = RemainderProvider(self, cursor, uid, context)
     generatedRights = MemberRightsCurve(
         activeShares=memberActiveShares,
         rightsPerShare=rightsPerShare,
         remainders=remainders,
         eager=True,
         )
     return [ int(num) for num in generatedRights.rights_kwh(member,
         isodate(start),
         isodate(stop),
         )]
    def dealer_refund_kwh(self, cursor, uid,
            contract_id, start, stop, fare, period, kwh, member,
            context=None):

        GenerationkWhDealer = self.pool.get('generationkwh.dealer')
        dealer = GenerationkWhDealer._createDealer(cursor, uid, context)
        result = dealer.refund_kwh(
            contract_id,
            isodate(start),
            isodate(stop),
            fare,
            period,
            kwh,
            member,
            )
        return int(result)
    def set_effective(self, cursor, uid,
            start, stop, waitingDays, expirationYears, force,
            context=None):
        """
            Makes effective the investments purchased between start and stop
            included for the period waitingDays from the purchase date
            for expirationYears.
            If force is not active, already effective investments are
            ignored.
        """
        criteria = []
        if not force: criteria.append(('first_effective_date', '=', False))
        if stop: criteria.append(('purchase_date', '<=', str(stop)))
        if start: criteria.append(('purchase_date', '>=', str(start)))

        investments_id = self.search(cursor, uid, criteria, context=context)
        investments = self.read(
            cursor, uid, investments_id, ['purchase_date'], context=context
        )

        for investment in investments:

            first,last = self._effectivePeriod(
                isodate(investment['purchase_date']),
                waitingDays, expirationYears)

            self.write(
                cursor, uid, investment['id'], dict(
                    first_effective_date = first,
                    last_effective_date = last,
                ), context=context
            )
 def memberrightsusage_update(self, cursor, uid,
         member,start,data,
         context=None):
     usage_provider = MemberRightsUsage(mdbpool.get_db())
     usage_provider.updateUsage(
         member=member,
         start=isodate(start),
         data=data
         )
    def get(self, start, stop):
        """Returns the holidays to be considering by fares
        between start and stop date including both.
        """

        Holidays = self.erp.pool.get("giscedata.dfestius")
        ids = Holidays.search(
            self.cursor, self.uid, [("name", ">=", start), ("name", "<=", stop)], 0, None, "name desc", self.context
        )
        return [isodate(h["name"]) for h in Holidays.read(self.cursor, self.uid, ids, ["name"], self.context)]
    def use_kwh(self, cursor, uid,
                contract_id, first_date, last_date, fare_id, period_id, kwh,
                context=None):
        """Marks the indicated kwh as used, if available, for the contract,
           date interval, fare and period and returns the ones efectively used.
        """

        logger = netsvc.Logger()

        dealer = self._createDealer(cursor, uid, context)

        fare, period = self.get_fare_name_by_id(cursor, uid, fare_id, period_id)

        res = dealer.use_kwh(
            contract_id, isodate(first_date), isodate(last_date), fare, period, kwh)

        socis = [ line['member_id'] for line in res ]
        members2partners = dict(self.get_partners_by_members(cursor, uid, socis, context=context))

        def soci2partner(soci):
            return members2partners[soci]

        for line in res:
            txt = (u'{kwh} Generation kwh of member {member} to {contract} '
                   u'for period {period} between {start} and {end}').format(
                    kwh=line['kwh'],
                    member=line['member_id'],
                    contract=contract_id,
                    period=period,
                    start=first_date,
                    end=last_date,
            )
            logger.notifyChannel('gkwh_dealer USE', netsvc.LOG_INFO, txt)

        return [
            dict(
                member_id = soci2partner(line['member_id']),
                kwh = line['kwh'],
                )
            for line in res
        ]
 def contractSources(self, contract_id):
     """
         Returns the sources available GenkWh rights sources for a contract
         and the earliest date you can use rights from it.
     """
     Assignment = self.erp.pool.get('generationkwh.assignment')
     return [
         ns(
             member_id=member_id,
             last_usable_date=isodate(last_usable_date),
         )
         for member_id, last_usable_date
         in Assignment.contractSources(
             self.cursor, self.uid,
             contract_id,
             context=self.context)
         ]
    def lastRemainders(self, cr, uid, context=None):
        "Returns the latest remainder for each number of shares."""

        cr.execute("""
            SELECT r.n_shares,r.target_day,r.remainder_wh
                FROM generationkwh_remainder AS r
                LEFT JOIN generationkwh_remainder AS r2
                    ON r.n_shares=r2.n_shares
                    AND r.target_day < r2.target_day
                WHERE r2.target_day IS NULL
            """)
        result = [
            (
                n_shares,
                isodate(target_day),
                remainder_wh,
            ) for n_shares, target_day, remainder_wh in cr.fetchall()
        ]
        return result
    def trace_rigths_compilation(self, cursor, uid,
            member, start, stop, fare, period,
            context=None):
        """
            Helper function to show data related to computation of available
            rights.
        """
        print "Dropping results for", member, start, stop, fare, period

        investment = InvestmentProvider(self, cursor, uid, context)
        memberActiveShares = MemberSharesCurve(investment)
        rightsPerShare = RightsPerShare(mdbpool.get_db())
        remainders = RemainderProvider(self, cursor, uid, context)

        generatedRights = MemberRightsCurve(
            activeShares=memberActiveShares,
            rightsPerShare=rightsPerShare,
            remainders=remainders,
            eager=True,
            )
        rightsUsage = MemberRightsUsage(mdbpool.get_db())
        holidays = HolidaysProvider(self, cursor, uid, context)
        farePeriod = FarePeriodCurve(holidays)

        print 'remainders', remainders.lastRemainders()
        print 'investment', investment.effectiveInvestments(
            start=isodate(start),
            end=isodate(stop),
            member=member)
        print 'active', memberActiveShares.hourly(
            isodate(start),
            isodate(stop),
            member)
        for nshares in set(memberActiveShares.hourly(
            isodate(start),
            isodate(stop),
            member)):
            print 'rightsPerShare', nshares, rightsPerShare.rightsPerShare(nshares,
                isodate(start),
                isodate(stop),
                )
        print 'rights', generatedRights.rights_kwh(member,
            isodate(start),
            isodate(stop),
            )

        print 'periodmask', farePeriod.periodMask(
            fare, period,
            isodate(start),
            isodate(stop),
            )
    def create_from_accounting(self, cursor, uid,
            member_id, start, stop, waitingDays, expirationYears,
            context=None):
        """
            Takes accounting information and generates GenkWh investments
            purchased among start and stop dates for the indicated member.
            If waitingDays is not None, activation date is set those
            days after the purchase date.
            If expirationYears is not None, expiration date is set, those
            years after the activation date.
        """

        Account = self.pool.get('account.account')
        MoveLine = self.pool.get('account.move.line')
        Member = self.pool.get('somenergia.soci')
        generationAccountPrefix = '163500'

        if member_id is None:
            accountDomain = [('code','ilike',generationAccountPrefix+'%')]
        else:
            member_ids = [member_id] if type(member_id) is int else member_id
            memberCodes = Member.read(cursor, uid, member_ids, ['ref'])
            accountCodes = [
                generationAccountPrefix + memberCode['ref'][1:]
                for memberCode in memberCodes
                ]

            accountDomain = [ ('code','in',accountCodes)]
        accountIds = Account.search(cursor, uid, accountDomain)

        criteria = [('account_id','in',accountIds)]
        if stop: criteria.append(('date_created', '<=', str(stop)))
        if start: criteria.append(('date_created', '>=', str(start)))

        movelinesids = MoveLine.search(
            cursor, uid, criteria,
            order='date_created asc, id asc',
            context=context
            )

        for line in MoveLine.browse(cursor, uid, movelinesids, context):
            # Filter out already converted move lines
            if self.search(cursor, uid,
                [('move_line_id','=',line.id)],
                context=dict(context or {}, active_test=False),
            ):
                continue

            partnerid = line.partner_id.id
            if not partnerid:
                # Handle cases with no partner_id
                membercode = int(line.account_id.code[4:])
                domain = [('ref', 'ilike', '%'+str(membercode).zfill(6))]
            else:
                domain = [('partner_id', '=', partnerid)]

            # partner to member conversion
            # ctx = dict(context)
            # ctx.update({'active_test': False})
            
            members = Member.search(cursor, uid, domain, context)
            if not members:
                print (
                    "No existeix el soci de la linia comptable {}, {}"
                    .format(line, domain))
                continue

            member_id = members[0]

            activation, lastDateEffective = self._effectivePeriod(
                isodate(line.date_created),
                waitingDays, expirationYears)

            self.create(cursor, uid, dict(
                member_id=member_id,
                nshares=(line.credit-line.debit)//100,
                purchase_date=line.date_created,
                first_effective_date=activation,
                last_effective_date=lastDateEffective,
                move_line_id=line.id,
                ))