<commit_before>const config = require('../../knexfile').migrations
const knex = require('knex')(config)

// TODO extract sample data into separate object so you can retrieve it and use in tests, so if it is updated it won't break tests
module.exports.insertTestData = function (reference, date, status, visitDate, increment, paymentStatus = null) {
  const idIncrement = increment || 0
  // Generate unique Integer for Ids using timestamp in tenth of seconds
  const uniqueId = Math.floor(Date.now() / 100) - 14000000000 + idIncrement

  return this.insertTestDataForIds(reference, date, status, visitDate, uniqueId, uniqueId + 1, uniqueId + 2, uniqueId + 3, paymentStatus)
}

module.exports.insertTestDataForIds = function (reference, date, status, visitDate, uniqueId, uniqueId2, uniqueId3, uniqueId4, paymentStatus) {
  const data = this.getTestData(reference, status)

  const ids = {}
  return knex('IntSchema.Eligibility')
    .insert({
      EligibilityId: uniqueId,
      Reference: reference,
      DateCreated: date,
      DateSubmitted: date,
      Status: status
    })
    .returning('EligibilityId')
    .then(function (result) {
      ids.eligibilityId = result[0]
      return knex('IntSchema.Prisoner')
        .returning('PrisonerId')
        .insert({
          PrisonerId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          FirstName: data.Prisoner.FirstName,
          LastName: data.Prisoner.LastName,
          DateOfBirth: date,
          PrisonNumber: data.Prisoner.PrisonNumber,
          NameOfPrison: data.Prisoner.NameOfPrison
        })
        .then(function (result) {
          ids.prisonerId = result[0]
          return ids.prisonerId
        })
    })
    .then(function () {
      return knex('IntSchema.Visitor')
        .returning('VisitorId')
        .insert({
          VisitorId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          FirstName: data.Visitor.FirstName,
          LastName: data.Visitor.LastName,
          NationalInsuranceNumber: data.Visitor.NationalInsuranceNumber,
          HouseNumberAndStreet: data.Visitor.HouseNumberAndStreet,
          Town: data.Visitor.Town,
          County: data.Visitor.County,
          PostCode: data.Visitor.PostCode,
          Country: data.Visitor.Country,
          EmailAddress: data.Visitor.EmailAddress,
          PhoneNumber: data.Visitor.PhoneNumber,
          DateOfBirth: date,
          Relationship: data.Visitor.Relationship,
          Benefit: data.Visitor.Benefit,
          DWPBenefitCheckerResult: data.Visitor.DWPBenefitCheckerResult
        })
        .then(function (result) {
          ids.visitorId = result[0]
          return ids.visitorId
        })
    })
    .then(function () {
      return knex('IntSchema.Claim')
        .returning(['ClaimId', 'LastUpdated'])
        .insert({
          ClaimId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DateOfJourney: visitDate || date,
          DateCreated: date,
          DateSubmitted: date,
          ClaimType: data.Claim.ClaimType,
          IsAdvanceClaim: data.Claim.IsAdvanceClaim,
          IsOverpaid: data.Claim.IsOverpaid,
          OverpaymentAmount: data.Claim.OverpaymentAmount,
          Status: status,
          PaymentMethod: data.Claim.PaymentMethod,
          AssignedTo: data.Claim.AssignedTo,
          AssignmentExpiry: new Date(date.getTime() + 300000), // current time + 5 minutes
          PaymentStatus: paymentStatus
        })
    })
    .then(function (result) {
      ids.claimId = result[0].ClaimId
      ids.lastUpdated = result[0].LastUpdated
    })
    .then(function () {
      return knex('IntSchema.ClaimExpense')
        .returning('ClaimExpenseId')
        .insert({
          ClaimExpenseId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          ExpenseType: data.ClaimExpenses[0].ExpenseType,
          Cost: data.ClaimExpenses[0].Cost,
          From: data.ClaimExpenses[0].From,
          To: data.ClaimExpenses[0].To,
          IsReturn: data.ClaimExpenses[0].IsReturn,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.expenseId1 = result[0]
      return knex('IntSchema.ClaimExpense')
        .returning('ClaimExpenseId')
        .insert({
          ClaimExpenseId: uniqueId2,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          ExpenseType: data.ClaimExpenses[1].ExpenseType,
          Cost: data.ClaimExpenses[1].Cost,
          DurationOfTravel: data.ClaimExpenses[1].DurationOfTravel,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.expenseId2 = result[0]
      return knex('IntSchema.ClaimChild')
        .returning('ClaimChildId')
        .insert({
          ClaimChildId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          FirstName: data.ClaimChild[0].FirstName,
          LastName: data.ClaimChild[0].LastName,
          DateOfBirth: date,
          Relationship: data.ClaimChild[0].Relationship,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.childId1 = result[0]
      return knex('IntSchema.ClaimChild')
        .returning('ClaimChildId')
        .insert({
          ClaimChildId: uniqueId2,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          FirstName: data.ClaimChild[1].FirstName,
          LastName: data.ClaimChild[1].LastName,
          DateOfBirth: date,
          Relationship: data.ClaimChild[1].Relationship,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.childId2 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument['visit-confirmation'].DocumentType,
          DocumentStatus: data.ClaimDocument['visit-confirmation'].DocumentStatus,
          Filepath: '/example/path/1',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument['visit-confirmation'].IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId1 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId2,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.benefit.DocumentType,
          DocumentStatus: data.ClaimDocument.benefit.DocumentStatus,
          Filepath: '/example/path/2',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.benefit.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId2 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId3,
          ClaimExpenseId: uniqueId,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.expense.DocumentType,
          DocumentStatus: data.ClaimDocument.expense.DocumentStatus,
          Filepath: '/example/path/3',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.expense.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId3 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId4,
          ClaimExpenseId: uniqueId2,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.expense.DocumentType,
          DocumentStatus: data.ClaimDocument.expense.DocumentStatus,
          Filepath: '/example/path/4',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.expense.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId4 = result[0]
      return knex('IntSchema.ClaimEvent')
        .returning('ClaimEventId')
        .insert({
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: uniqueId,
          DateAdded: date,
          Event: 'An event',
          AdditionalData: 'Additional stuff',
          Note: 'A note',
          Caseworker: 'Joe Bloggs',
          IsInternal: true
        })
    })
    .then(function (result) {
      ids.claimEventId1 = result[0]
      return knex('IntSchema.ClaimEvent')
        .returning('ClaimEventId')
        .insert({
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: uniqueId,
          DateAdded: date,
          Event: 'Another event',
          AdditionalData: 'More additional stuff',
          Note: 'Another note',
          Caseworker: 'Jane Bloggs',
          IsInternal: false
        })
    })
    .then(function (result) {
      ids.claimEventId2 = result[0]
      return insertClaimDeduction(uniqueId, reference, ids.eligibilityId, data.ClaimDeduction.hc3.DeductionType, data.ClaimDeduction.hc3.Amount)
    })
    .then(function (result) {
      ids.claimDeductionId1 = result[0]
      return insertClaimDeduction(uniqueId, reference, ids.eligibilityId, data.ClaimDeduction.overpayment.DeductionType, data.ClaimDeduction.overpayment.Amount)
    })
    .then(function (result) {
      ids.claimDeductionId2 = result[0]
      return insertClaimEscort(uniqueId, reference, ids.eligibilityId, data.ClaimEscort)
    })
    .then(function (result) {
      ids.claimEscortId = result[0]
      return ids
    })
}

function deleteByReference (schemaTable, reference) {
  return knex(schemaTable).where('Reference', reference).del()
}

function deleteByClaimIds (schemaTable, claimIds) {
  return knex(schemaTable).whereIn('ClaimId', claimIds).del()
}

function getClaimIdsForReference (schemaTable, reference) {
  return knex(schemaTable).where('Reference', reference).select('ClaimId')
    .then(function (results) {
      const claimIdArray = []
      results.forEach(function (result) {
        claimIdArray.push(result.ClaimId)
      })
      return claimIdArray
    })
}

module.exports.deleteAll = function (reference) {
  return deleteByReference('IntSchema.Task', reference)
    .then(function () { return deleteByReference('IntSchema.ClaimEvent', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimBankDetail', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimDocument', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimExpense', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimChild', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimDeduction', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimEscort', reference) })
    .then(function () { return getClaimIdsForReference('IntSchema.Claim', reference) })
    .then(function (claimIds) { return deleteByClaimIds('IntSchema.TopUp', claimIds) })
    .then(function () { return deleteByReference('IntSchema.Claim', reference) })
    .then(function () { return deleteByReference('IntSchema.Visitor', reference) })
    .then(function () { return deleteByReference('IntSchema.Prisoner', reference) })
    .then(function () { return deleteByReference('IntSchema.Eligibility', reference) })
}

module.exports.getTestData = function (reference, status) {
  return {
    Prisoner: {
      FirstName: 'TestFirst',
      LastName: 'TestLast',
      PrisonNumber: 'A123456',
      NameOfPrison: 'Test'
    },
    Visitor: {
      FirstName: 'John',
      LastName: 'Smith',
      NationalInsuranceNumber: 'QQ123456C',
      HouseNumberAndStreet: '1 Test Road',
      Town: 'Town',
      County: 'Durham',
      PostCode: 'BT111BT',
      Country: 'England',
      EmailAddress: 'donotsend@apvs.com',
      PhoneNumber: '07911111111',
      Relationship: 'partner',
      Benefit: 'income-support',
      DWPBenefitCheckerResult: 'UNDETERMINED'
    },
    Claim: {
      ClaimType: 'first-time',
      IsAdvanceClaim: false,
      IsOverpaid: false,
      OverpaymentAmount: 20,
      PaymentMethod: 'bank',
      AssignedTo: 'TestUser@test.com'
    },
    ClaimExpenses: [{
      ExpenseType: 'train',
      Cost: 12,
      From: 'London',
      To: 'Hewell',
      IsReturn: true
    },
    {
      ExpenseType: 'accommodation',
      Cost: 80,
      DurationOfTravel: 1
    }],
    ClaimChild: [{
      FirstName: 'Jane',
      LastName: 'Bloggs',
      DateOfBirth: '01-09-2005',
      Relationship: 'prisoners-child'
    },
    {
      FirstName: 'Michael',
      LastName: 'Bloggs',
      DateOfBirth: '15-10-2010',
      Relationship: 'claimants-child'
    }],
    ClaimDocument: {
      'visit-confirmation': {
        DocumentType: 'VISIT-CONFIRMATION',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true',
        Caseworker: 'test@test.com'
      },
      benefit: {
        DocumentType: 'BENEFIT',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true'
      },
      expense: {
        DocumentType: 'RECEIPT',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true'
      }
    },
    ClaimEvent: [
      {
        Event: 'Event text',
        AdditionalData: 'A note',
        Caseworker: 'Joe Bloggs',
        IsInternal: true
      },
      {
        Event: 'Event text 2',
        AdditionalData: 'Another note',
        Caseworker: 'Jane Bloggs',
        IsInternal: false
      }
    ],
    ClaimDeduction: {
      overpayment: {
        Amount: 5,
        DeductionType: 'overpayment',
        IsEnabled: true
      },
      hc3: {
        Amount: 10,
        DeductionType: 'hc3',
        IsEnabled: true
      }
    },
    ClaimEscort: {
      FirstName: 'Escort',
      LastName: 'Person',
      DateOfBirth: '01-01-1990'
    }
  }
}

module.exports.insertClaim = function (claimId, eligibilityId, reference, date, status, isOverpaid, overpaymentAmount, remainingOverpaymentAmount, isAdvanceClaim, paymentStatus) {
  return knex('Claim')
    .returning('ClaimId')
    .insert({
      ClaimId: claimId,
      EligibilityId: eligibilityId,
      Reference: reference,
      DateOfJourney: date,
      DateCreated: date,
      DateSubmitted: date,
      Status: status,
      IsOverpaid: isOverpaid,
      OverpaymentAmount: overpaymentAmount,
      RemainingOverpaymentAmount: remainingOverpaymentAmount,
      IsAdvanceClaim: isAdvanceClaim,
      PaymentStatus: paymentStatus
    })
}

function insertClaimDeduction (claimId, reference, eligibilityId, deductionType, amount) {
  return knex('ClaimDeduction')
    .returning('ClaimDeductionId')
    .insert({
      EligibilityId: eligibilityId,
      Reference: reference,
      ClaimId: claimId,
      DeductionType: deductionType,
      Amount: amount,
      IsEnabled: true
    })
}

function insertClaimEscort (claimId, reference, eligibilityId, escortData) {
  return knex('ClaimEscort')
    .returning('ClaimEscortId')
    .insert({
      ClaimEscortId: claimId,
      ClaimId: claimId,
      EligibilityId: eligibilityId,
      Reference: reference,
      FirstName: escortData.FirstName,
      LastName: escortData.LastName,
      DateOfBirth: escortData.DateOfBirth,
      IsEnabled: true
    })
}

module.exports.getBenefitExpiryDate = function (reference) {
  return knex('IntSchema.Visitor')
    .first('BenefitExpiryDate')
    .where('Reference', reference)
}

module.exports.getLastTopUpAdded = function getLastTopUpAdded (claimId) {
  return knex('IntSchema.TopUp')
    .first()
    .where('ClaimId', claimId)
    .then(function (result) {
      result.TopUpAmount = Number(result.TopUpAmount).toFixed(2)
      return result
    })
}

module.exports.insertClaimDeduction = insertClaimDeduction
<commit_msg>APVS0250: Fixing integration tests<commit_after>const config = require('../../knexfile').migrations
const knex = require('knex')(config)

// TODO extract sample data into separate object so you can retrieve it and use in tests, so if it is updated it won't break tests
module.exports.insertTestData = function (reference, date, status, visitDate, increment, paymentStatus = null) {
  const idIncrement = increment || 0
  // Generate unique Integer for Ids using timestamp in tenth of seconds
  const uniqueId = Math.floor(Date.now() / 100) - 15000000000 + idIncrement

  return this.insertTestDataForIds(reference, date, status, visitDate, uniqueId, uniqueId + 1, uniqueId + 2, uniqueId + 3, paymentStatus)
}

module.exports.insertTestDataForIds = function (reference, date, status, visitDate, uniqueId, uniqueId2, uniqueId3, uniqueId4, paymentStatus) {
  const data = this.getTestData(reference, status)

  const ids = {}
  return knex('IntSchema.Eligibility')
    .insert({
      EligibilityId: uniqueId,
      Reference: reference,
      DateCreated: date,
      DateSubmitted: date,
      Status: status
    })
    .returning('EligibilityId')
    .then(function (result) {
      ids.eligibilityId = result[0]
      return knex('IntSchema.Prisoner')
        .returning('PrisonerId')
        .insert({
          PrisonerId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          FirstName: data.Prisoner.FirstName,
          LastName: data.Prisoner.LastName,
          DateOfBirth: date,
          PrisonNumber: data.Prisoner.PrisonNumber,
          NameOfPrison: data.Prisoner.NameOfPrison
        })
        .then(function (result) {
          ids.prisonerId = result[0]
          return ids.prisonerId
        })
    })
    .then(function () {
      return knex('IntSchema.Visitor')
        .returning('VisitorId')
        .insert({
          VisitorId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          FirstName: data.Visitor.FirstName,
          LastName: data.Visitor.LastName,
          NationalInsuranceNumber: data.Visitor.NationalInsuranceNumber,
          HouseNumberAndStreet: data.Visitor.HouseNumberAndStreet,
          Town: data.Visitor.Town,
          County: data.Visitor.County,
          PostCode: data.Visitor.PostCode,
          Country: data.Visitor.Country,
          EmailAddress: data.Visitor.EmailAddress,
          PhoneNumber: data.Visitor.PhoneNumber,
          DateOfBirth: date,
          Relationship: data.Visitor.Relationship,
          Benefit: data.Visitor.Benefit,
          DWPBenefitCheckerResult: data.Visitor.DWPBenefitCheckerResult
        })
        .then(function (result) {
          ids.visitorId = result[0]
          return ids.visitorId
        })
    })
    .then(function () {
      return knex('IntSchema.Claim')
        .returning(['ClaimId', 'LastUpdated'])
        .insert({
          ClaimId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DateOfJourney: visitDate || date,
          DateCreated: date,
          DateSubmitted: date,
          ClaimType: data.Claim.ClaimType,
          IsAdvanceClaim: data.Claim.IsAdvanceClaim,
          IsOverpaid: data.Claim.IsOverpaid,
          OverpaymentAmount: data.Claim.OverpaymentAmount,
          Status: status,
          PaymentMethod: data.Claim.PaymentMethod,
          AssignedTo: data.Claim.AssignedTo,
          AssignmentExpiry: new Date(date.getTime() + 300000), // current time + 5 minutes
          PaymentStatus: paymentStatus
        })
    })
    .then(function (result) {
      ids.claimId = result[0].ClaimId
      ids.lastUpdated = result[0].LastUpdated
    })
    .then(function () {
      return knex('IntSchema.ClaimExpense')
        .returning('ClaimExpenseId')
        .insert({
          ClaimExpenseId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          ExpenseType: data.ClaimExpenses[0].ExpenseType,
          Cost: data.ClaimExpenses[0].Cost,
          From: data.ClaimExpenses[0].From,
          To: data.ClaimExpenses[0].To,
          IsReturn: data.ClaimExpenses[0].IsReturn,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.expenseId1 = result[0]
      return knex('IntSchema.ClaimExpense')
        .returning('ClaimExpenseId')
        .insert({
          ClaimExpenseId: uniqueId2,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          ExpenseType: data.ClaimExpenses[1].ExpenseType,
          Cost: data.ClaimExpenses[1].Cost,
          DurationOfTravel: data.ClaimExpenses[1].DurationOfTravel,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.expenseId2 = result[0]
      return knex('IntSchema.ClaimChild')
        .returning('ClaimChildId')
        .insert({
          ClaimChildId: uniqueId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          FirstName: data.ClaimChild[0].FirstName,
          LastName: data.ClaimChild[0].LastName,
          DateOfBirth: date,
          Relationship: data.ClaimChild[0].Relationship,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.childId1 = result[0]
      return knex('IntSchema.ClaimChild')
        .returning('ClaimChildId')
        .insert({
          ClaimChildId: uniqueId2,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: ids.claimId,
          FirstName: data.ClaimChild[1].FirstName,
          LastName: data.ClaimChild[1].LastName,
          DateOfBirth: date,
          Relationship: data.ClaimChild[1].Relationship,
          IsEnabled: true
        })
    })
    .then(function (result) {
      ids.childId2 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument['visit-confirmation'].DocumentType,
          DocumentStatus: data.ClaimDocument['visit-confirmation'].DocumentStatus,
          Filepath: '/example/path/1',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument['visit-confirmation'].IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId1 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId2,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.benefit.DocumentType,
          DocumentStatus: data.ClaimDocument.benefit.DocumentStatus,
          Filepath: '/example/path/2',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.benefit.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId2 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId3,
          ClaimExpenseId: uniqueId,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.expense.DocumentType,
          DocumentStatus: data.ClaimDocument.expense.DocumentStatus,
          Filepath: '/example/path/3',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.expense.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId3 = result[0]
      return knex('IntSchema.ClaimDocument')
        .returning('ClaimDocumentId')
        .insert({
          ClaimDocumentId: uniqueId4,
          ClaimExpenseId: uniqueId2,
          ClaimId: ids.claimId,
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          DocumentType: data.ClaimDocument.expense.DocumentType,
          DocumentStatus: data.ClaimDocument.expense.DocumentStatus,
          Filepath: '/example/path/4',
          DateSubmitted: date,
          IsEnabled: data.ClaimDocument.expense.IsEnabled
        })
    })
    .then(function (result) {
      ids.claimDocumentId4 = result[0]
      return knex('IntSchema.ClaimEvent')
        .returning('ClaimEventId')
        .insert({
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: uniqueId,
          DateAdded: date,
          Event: 'An event',
          AdditionalData: 'Additional stuff',
          Note: 'A note',
          Caseworker: 'Joe Bloggs',
          IsInternal: true
        })
    })
    .then(function (result) {
      ids.claimEventId1 = result[0]
      return knex('IntSchema.ClaimEvent')
        .returning('ClaimEventId')
        .insert({
          EligibilityId: ids.eligibilityId,
          Reference: reference,
          ClaimId: uniqueId,
          DateAdded: date,
          Event: 'Another event',
          AdditionalData: 'More additional stuff',
          Note: 'Another note',
          Caseworker: 'Jane Bloggs',
          IsInternal: false
        })
    })
    .then(function (result) {
      ids.claimEventId2 = result[0]
      return insertClaimDeduction(uniqueId, reference, ids.eligibilityId, data.ClaimDeduction.hc3.DeductionType, data.ClaimDeduction.hc3.Amount)
    })
    .then(function (result) {
      ids.claimDeductionId1 = result[0]
      return insertClaimDeduction(uniqueId, reference, ids.eligibilityId, data.ClaimDeduction.overpayment.DeductionType, data.ClaimDeduction.overpayment.Amount)
    })
    .then(function (result) {
      ids.claimDeductionId2 = result[0]
      return insertClaimEscort(uniqueId, reference, ids.eligibilityId, data.ClaimEscort)
    })
    .then(function (result) {
      ids.claimEscortId = result[0]
      return ids
    })
}

function deleteByReference (schemaTable, reference) {
  return knex(schemaTable).where('Reference', reference).del()
}

function deleteByClaimIds (schemaTable, claimIds) {
  return knex(schemaTable).whereIn('ClaimId', claimIds).del()
}

function getClaimIdsForReference (schemaTable, reference) {
  return knex(schemaTable).where('Reference', reference).select('ClaimId')
    .then(function (results) {
      const claimIdArray = []
      results.forEach(function (result) {
        claimIdArray.push(result.ClaimId)
      })
      return claimIdArray
    })
}

module.exports.deleteAll = function (reference) {
  return deleteByReference('IntSchema.Task', reference)
    .then(function () { return deleteByReference('IntSchema.ClaimEvent', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimBankDetail', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimDocument', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimExpense', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimChild', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimDeduction', reference) })
    .then(function () { return deleteByReference('IntSchema.ClaimEscort', reference) })
    .then(function () { return getClaimIdsForReference('IntSchema.Claim', reference) })
    .then(function (claimIds) { return deleteByClaimIds('IntSchema.TopUp', claimIds) })
    .then(function () { return deleteByReference('IntSchema.Claim', reference) })
    .then(function () { return deleteByReference('IntSchema.Visitor', reference) })
    .then(function () { return deleteByReference('IntSchema.Prisoner', reference) })
    .then(function () { return deleteByReference('IntSchema.Eligibility', reference) })
}

module.exports.getTestData = function (reference, status) {
  return {
    Prisoner: {
      FirstName: 'TestFirst',
      LastName: 'TestLast',
      PrisonNumber: 'A123456',
      NameOfPrison: 'Test'
    },
    Visitor: {
      FirstName: 'John',
      LastName: 'Smith',
      NationalInsuranceNumber: 'QQ123456C',
      HouseNumberAndStreet: '1 Test Road',
      Town: 'Town',
      County: 'Durham',
      PostCode: 'BT111BT',
      Country: 'England',
      EmailAddress: 'donotsend@apvs.com',
      PhoneNumber: '07911111111',
      Relationship: 'partner',
      Benefit: 'income-support',
      DWPBenefitCheckerResult: 'UNDETERMINED'
    },
    Claim: {
      ClaimType: 'first-time',
      IsAdvanceClaim: false,
      IsOverpaid: false,
      OverpaymentAmount: 20,
      PaymentMethod: 'bank',
      AssignedTo: 'TestUser@test.com'
    },
    ClaimExpenses: [{
      ExpenseType: 'train',
      Cost: 12,
      From: 'London',
      To: 'Hewell',
      IsReturn: true
    },
    {
      ExpenseType: 'accommodation',
      Cost: 80,
      DurationOfTravel: 1
    }],
    ClaimChild: [{
      FirstName: 'Jane',
      LastName: 'Bloggs',
      DateOfBirth: '01-09-2005',
      Relationship: 'prisoners-child'
    },
    {
      FirstName: 'Michael',
      LastName: 'Bloggs',
      DateOfBirth: '15-10-2010',
      Relationship: 'claimants-child'
    }],
    ClaimDocument: {
      'visit-confirmation': {
        DocumentType: 'VISIT-CONFIRMATION',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true',
        Caseworker: 'test@test.com'
      },
      benefit: {
        DocumentType: 'BENEFIT',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true'
      },
      expense: {
        DocumentType: 'RECEIPT',
        DocumentStatus: 'uploaded',
        IsEnabled: 'true'
      }
    },
    ClaimEvent: [
      {
        Event: 'Event text',
        AdditionalData: 'A note',
        Caseworker: 'Joe Bloggs',
        IsInternal: true
      },
      {
        Event: 'Event text 2',
        AdditionalData: 'Another note',
        Caseworker: 'Jane Bloggs',
        IsInternal: false
      }
    ],
    ClaimDeduction: {
      overpayment: {
        Amount: 5,
        DeductionType: 'overpayment',
        IsEnabled: true
      },
      hc3: {
        Amount: 10,
        DeductionType: 'hc3',
        IsEnabled: true
      }
    },
    ClaimEscort: {
      FirstName: 'Escort',
      LastName: 'Person',
      DateOfBirth: '01-01-1990'
    }
  }
}

module.exports.insertClaim = function (claimId, eligibilityId, reference, date, status, isOverpaid, overpaymentAmount, remainingOverpaymentAmount, isAdvanceClaim, paymentStatus) {
  return knex('Claim')
    .returning('ClaimId')
    .insert({
      ClaimId: claimId,
      EligibilityId: eligibilityId,
      Reference: reference,
      DateOfJourney: date,
      DateCreated: date,
      DateSubmitted: date,
      Status: status,
      IsOverpaid: isOverpaid,
      OverpaymentAmount: overpaymentAmount,
      RemainingOverpaymentAmount: remainingOverpaymentAmount,
      IsAdvanceClaim: isAdvanceClaim,
      PaymentStatus: paymentStatus
    })
}

function insertClaimDeduction (claimId, reference, eligibilityId, deductionType, amount) {
  return knex('ClaimDeduction')
    .returning('ClaimDeductionId')
    .insert({
      EligibilityId: eligibilityId,
      Reference: reference,
      ClaimId: claimId,
      DeductionType: deductionType,
      Amount: amount,
      IsEnabled: true
    })
}

function insertClaimEscort (claimId, reference, eligibilityId, escortData) {
  return knex('ClaimEscort')
    .returning('ClaimEscortId')
    .insert({
      ClaimEscortId: claimId,
      ClaimId: claimId,
      EligibilityId: eligibilityId,
      Reference: reference,
      FirstName: escortData.FirstName,
      LastName: escortData.LastName,
      DateOfBirth: escortData.DateOfBirth,
      IsEnabled: true
    })
}

module.exports.getBenefitExpiryDate = function (reference) {
  return knex('IntSchema.Visitor')
    .first('BenefitExpiryDate')
    .where('Reference', reference)
}

module.exports.getLastTopUpAdded = function getLastTopUpAdded (claimId) {
  return knex('IntSchema.TopUp')
    .first()
    .where('ClaimId', claimId)
    .then(function (result) {
      result.TopUpAmount = Number(result.TopUpAmount).toFixed(2)
      return result
    })
}

module.exports.insertClaimDeduction = insertClaimDeduction
<|endoftext|>


<commit_before>if ( 'undefined' === typeof go_content_widgets_admin ) {
	var go_content_widgets_admin = {
		// this ultimately gets set via wp_localize_script, set it to a dummy value as a default
		sidebar_id: 'this-should-be-set-via-wp-localize-script',
		layout_preferences: {}
	};
}//end if

( function( $ ) {
	'use strict';

	/**
	 * initialize all the things
	 */
	go_content_widgets_admin.init = function() {
		this.$sidebar = $( '#' + this.sidebar_id );
		this.inject_fields();
	};

	go_content_widgets_admin.inject_fields = function() {
		this.$sidebar.find( '.widget' ).each( function() {
			var $widget = $( this );
			var widget_id = $widget.attr( 'id' );
			var $fields = $(
				'
' +
					'
' +
						'' +
							'Placement preference:' +
						'' +
						'<select class="layout-preference widefat" name="go-content-widgets[' + widget_id +']" id="go-content-widgets_' + widget_id + '">' +
							'<option value="any">No preference</option>' +
							'<option value="full">Full width</option>' +
							'<option value="left">Left</option>' +
							'<option value="right">Right</option>' +
						'</select>' +
					'
' +
				'
'
			);

			if ( 'undefined' !== typeof go_content_widgets_admin.layout_preferences[ widget_id ] ) {
				$fields.find( '.layout-preference' ).val( go_content_widgets_admin.layout_preferences[ widget_id ] );
			}//end if

			$widget.find( '.widget-content' ).append( $fields );
		});
	};

	$( function() {
		go_content_widgets_admin.init();
	});
})( jQuery );
<commit_msg>make sure form stays on widgets and loads from preferences<commit_after>if ( 'undefined' === typeof go_content_widgets_admin ) {
	var go_content_widgets_admin = {
		// this ultimately gets set via wp_localize_script, set it to a dummy value as a default
		sidebar_id: 'this-should-be-set-via-wp-localize-script',
		layout_preferences: {}
	};
}//end if

( function( $ ) {
	'use strict';

	/**
	 * initialize all the things
	 */
	go_content_widgets_admin.init = function() {
		this.$sidebar = $( '#' + this.sidebar_id );
		this.inject_fields();

		$( document ).on( 'change', '.go-content-widgets-fields .layout-preference', function() {
			var $el = $( this );
			var $widget = $el.closest( '.widget' );

			go_content_widgets_admin.layout_preferences[ $widget.attr( 'id' ) ] = $el.val();
		});

		$( document ).ajaxComplete( function( event, jqxhr, ajax_options ) {
			var data = decodeURIComponent( ajax_options.data );
			if ( ! data.match( /\&action\=save\-widget\&/ ) ) {
				return;
			}

			go_content_widgets_admin.refresh_fields();
		});
	};

	go_content_widgets_admin.refresh_fields = function() {
		this.$sidebar.find( '.go-content-widgets-fields' ).remove();
		this.inject_fields();
	};

	go_content_widgets_admin.inject_fields = function() {
		this.$sidebar.find( '.widget' ).each( function() {
			var $widget = $( this );
			var widget_id = $widget.attr( 'id' );
			var $fields = $(
				'
' +
					'
' +
						'' +
							'Placement preference:' +
						'' +
						'<select class="layout-preference widefat" name="go-content-widgets[' + widget_id +']" id="go-content-widgets_' + widget_id + '">' +
							'<option value="any">No preference</option>' +
							'<option value="full">Full width</option>' +
							'<option value="left">Left</option>' +
							'<option value="right">Right</option>' +
						'</select>' +
					'
' +
				'
'
			);

			if ( 'undefined' !== typeof go_content_widgets_admin.layout_preferences[ widget_id ] ) {
				$fields.find( '.layout-preference' ).val( go_content_widgets_admin.layout_preferences[ widget_id ] );
			}//end if

			$widget.find( '.widget-content' ).append( $fields );
		});
	};

	$( function() {
		go_content_widgets_admin.init();
	});
})( jQuery );
<|endoftext|>


<commit_before>/* eslint-env jest */

const { createTestServer, setServerResponse, url } = require('../../tools');
const Parser = require('../../../lib/Parser');
const ChromeEnvironment = require('goose-chrome-environment');

jest.setTimeout(20000);
describe('Actions', () => {
  let testServer;
  let parser;

  beforeAll(async () => {
    testServer = await createTestServer();
    parser = new Parser({
      environment: new ChromeEnvironment({}),
      mode: 'multiple',
    });
  });

  afterAll(async () => {
    await testServer.close();
    await parser.finish();
  });

  describe('ActionBlur', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('blur', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'focus',
            scope: '[type="text"]',
          },
          {
            type: 'blur',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClick', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('click', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseClick', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('click', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseClick',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseDown', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('mousedown', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseDown',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseUp', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('mouseup', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseUp',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionFocus', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('focus', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'focus',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClickWithWaitForPage', () => {
    test('perform', async () => {
      setServerResponse([
        {
          route: '/',
          html: `<a href="/test">test</a>`
        },
        {
          route: '/test',
          html: `<a href="/">1</a>`
        }
      ]);
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: 'page',
          },
        ],
        rules: {
          scope: 'a',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClickWithWaitForPattern', () => {
    test('perform', async () => {
      setServerResponse({
          html: `<a href="#">test</a>`,
          fn: () => {
            // the phone number appears after some time in the link
            document.querySelector('a').addEventListener('click', ({ target }) => {
              setTimeout(function () {
                target.setAttribute('href', 'tel:+123456890102');
              }, 500);
            });
          }
        });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'pattern',
              pattern: '^tel:',
              scope: 'a',
              attr: 'href',
            },
          },
        ],
        rules: {
          scope: 'a',
          attr: 'href',
        },
      });

      expect(result).toEqual('tel:+123456890102');
    });
  });

  describe('ActionClickWithWaitForVisible', () => {
    test('wait visible', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.body.insertAdjacentHTML('beforeend', '
12345
');
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'visible',
              scope: 'div',
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('12345');
    });

    test('wait invisible', async () => {
      setServerResponse({
        html: `<a href="#">test</a><div>12345</div>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.querySelector('div').remove();
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'visible',
              scope: 'div',
              visibility: false,
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('');
    });
  });

  describe('ActionWaitForElement', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.body.insertAdjacentHTML('beforeend', '
12345
');
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'element',
              scope: 'div',
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('12345');
    });
  });

  describe('ActionClickWithWaitForQuery', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          // the phone number appears after some time in the link
          document.querySelector('a').addEventListener('click', ({ target }) => {
            document.body.insertAdjacentHTML('beforeend', '');
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'query',
              uri: '12345',
            },
          },
        ],
        rules: {
          scope: 'img',
          attr: 'src'
        },
      });

      expect(result).toEqual('12345');
    });
  });

  describe('ActionChangeElement', () => {
    test('change style, attr', async () => {
      setServerResponse({
        html: `<img src="12345" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'changeElement',
            scope: 'img',
            style: {
              display: 'none',
            },
            attr: {
              alt: 'test',
            },
          },
        ],
        rules: {
          collection: [
            {
              name: 'alt',
              scope: 'img',
              attr: 'alt',
            },
            {
              name: 'style',
              scope: 'img',
              attr: 'style',
            },
          ],
        },
      });

      expect(result).toEqual({ alt: 'test', style: 'display: none;' });
    });

    test('change nothing', async () => {
      setServerResponse({
        html: `<img src="12345" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'changeElement',
            scope: 'img',
          },
        ],
        rules: {
          collection: [
            {
              name: 'alt',
              scope: 'img',
              attr: 'alt',
            },
            {
              name: 'style',
              scope: 'img',
              attr: 'style',
            },
          ],
        },
      });

      expect(result).toEqual({ alt: null, style: null });
    });
  });
});
<commit_msg>- ActionType - added tests<commit_after>/* eslint-env jest */

const { createTestServer, setServerResponse, url } = require('../../tools');
const Parser = require('../../../lib/Parser');
const ChromeEnvironment = require('goose-chrome-environment');

jest.setTimeout(20000);
describe('Actions', () => {
  let testServer;
  let parser;

  beforeAll(async () => {
    testServer = await createTestServer();
    parser = new Parser({
      environment: new ChromeEnvironment({}),
      mode: 'multiple',
    });
  });

  afterAll(async () => {
    await testServer.close();
    await parser.finish();
  });

  describe('ActionBlur', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('blur', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'focus',
            scope: '[type="text"]',
          },
          {
            type: 'blur',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClick', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('click', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseClick', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('click', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseClick',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseDown', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('mousedown', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseDown',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionMouseUp', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('mouseup', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'mouseUp',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionFocus', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<input type="text" value="0" />`,
        fn: () => {
          document.querySelector('[type="text"]').addEventListener('focus', ({ target }) => {
            const value = '1';
            target.value = value;
            target.setAttribute('value', value);
          });
        },
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'focus',
            scope: '[type="text"]',
          },
          {
            type: 'pause',
            timeout: 50,
          },
        ],
        rules: {
          scope: '[type="text"]',
          attr: 'value',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClickWithWaitForPage', () => {
    test('perform', async () => {
      setServerResponse([
        {
          route: '/',
          html: `<a href="/test">test</a>`
        },
        {
          route: '/test',
          html: `<a href="/">1</a>`
        }
      ]);
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: 'page',
          },
        ],
        rules: {
          scope: 'a',
        },
      });

      expect(result).toEqual('1');
    });
  });

  describe('ActionClickWithWaitForPattern', () => {
    test('perform', async () => {
      setServerResponse({
          html: `<a href="#">test</a>`,
          fn: () => {
            // the phone number appears after some time in the link
            document.querySelector('a').addEventListener('click', ({ target }) => {
              setTimeout(function () {
                target.setAttribute('href', 'tel:+123456890102');
              }, 500);
            });
          }
        });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'pattern',
              pattern: '^tel:',
              scope: 'a',
              attr: 'href',
            },
          },
        ],
        rules: {
          scope: 'a',
          attr: 'href',
        },
      });

      expect(result).toEqual('tel:+123456890102');
    });
  });

  describe('ActionClickWithWaitForVisible', () => {
    test('wait visible', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.body.insertAdjacentHTML('beforeend', '
12345
');
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'visible',
              scope: 'div',
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('12345');
    });

    test('wait invisible', async () => {
      setServerResponse({
        html: `<a href="#">test</a><div>12345</div>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.querySelector('div').remove();
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'visible',
              scope: 'div',
              visibility: false,
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('');
    });
  });

  describe('ActionWaitForElement', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          document.querySelector('a').addEventListener('click', ({ target }) => {
            setTimeout(function () {
              document.body.insertAdjacentHTML('beforeend', '
12345
');
            }, 500);
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'element',
              scope: 'div',
            },
          },
        ],
        rules: {
          scope: 'div',
        },
      });

      expect(result).toEqual('12345');
    });
  });

  describe('ActionClickWithWaitForQuery', () => {
    test('perform', async () => {
      setServerResponse({
        html: `<a href="#">test</a>`,
        fn: () => {
          // the phone number appears after some time in the link
          document.querySelector('a').addEventListener('click', ({ target }) => {
            document.body.insertAdjacentHTML('beforeend', '');
          });
        }
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'click',
            scope: 'a',
            waitFor: {
              type: 'query',
              uri: '12345',
            },
          },
        ],
        rules: {
          scope: 'img',
          attr: 'src'
        },
      });

      expect(result).toEqual('12345');
    });
  });

  describe('ActionChangeElement', () => {
    test('change style, attr', async () => {
      setServerResponse({
        html: `<img src="12345" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'changeElement',
            scope: 'img',
            style: {
              display: 'none',
            },
            attr: {
              alt: 'test',
            },
          },
        ],
        rules: {
          collection: [
            {
              name: 'alt',
              scope: 'img',
              attr: 'alt',
            },
            {
              name: 'style',
              scope: 'img',
              attr: 'style',
            },
          ],
        },
      });

      expect(result).toEqual({ alt: 'test', style: 'display: none;' });
    });

    test('change nothing', async () => {
      setServerResponse({
        html: `<img src="12345" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'changeElement',
            scope: 'img',
          },
        ],
        rules: {
          collection: [
            {
              name: 'alt',
              scope: 'img',
              attr: 'alt',
            },
            {
              name: 'style',
              scope: 'img',
              attr: 'style',
            },
          ],
        },
      });

      expect(result).toEqual({ alt: null, style: null });
    });
  });

  describe('ActionType', () => {
    test('typing provided text', async () => {
      setServerResponse({
        html: `<input type="text" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'type',
            scope: 'input',
            text: 'test',
          },
        ],
        rules: {
          scope: 'input',
          prop: 'value'
        },
      });

      expect(result).toEqual('test');
    });

    test('typing value from prev action', async () => {
      setServerResponse({
        html: `<span>test</span><input type="text" />`,
      });
      const result = await parser.parse({
        url,
        actions: [
          {
            type: 'parse',
            rules: {
              scope: 'span',
            },
          },
          {
            type: 'type',
            scope: 'input',
            useActionsResult: true,
          },
        ],
        rules: {
          scope: 'input',
          prop: 'value'
        },
      });

      expect(result).toEqual('test');
    });
  });
});
<|endoftext|>


<commit_before>/* global describe, it */

var assert = require('assert')
var bigi = require('bigi')
var bitcoin = require('../../')

describe('bitcoinjs-lib (basic)', function () {
  it('can generate a random bitcoin address', function () {
    // for testing only
    function rng () { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }

    // generate random keyPair
    var keyPair = bitcoin.ECPair.makeRandom({ rng: rng })
    var address = keyPair.getAddress()

    assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64')
  })

  it('can generate an address from a SHA256 hash', function () {
    var hash = bitcoin.crypto.sha256('correct horse battery staple')
    var d = bigi.fromBuffer(hash)

    var keyPair = new bitcoin.ECPair(d)
    var address = keyPair.getAddress()

    assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
  })

  it('can generate a random keypair for alternative networks', function () {
    // for testing only
    function rng () { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }

    var litecoin = bitcoin.networks.litecoin

    var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng })
    var wif = keyPair.toWIF()
    var address = keyPair.getAddress()

    assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn')
    assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS')
  })

  it('can import an address via WIF', function () {
    var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct')
    var address = keyPair.getAddress()

    assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31')
  })

  it('can create a Transaction', function () {
    var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
    var tx = new bitcoin.TransactionBuilder()

    tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0)
    tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000)
    tx.sign(0, keyPair)

    assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000')
  })
})
<commit_msg>tests: add more complex integration transaction<commit_after>/* global describe, it */

var assert = require('assert')
var bigi = require('bigi')
var bitcoin = require('../../')
var blockchain = require('./_blockchain')

describe('bitcoinjs-lib (basic)', function () {
  it('can generate a random bitcoin address', function () {
    // for testing only
    function rng () { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }

    // generate random keyPair
    var keyPair = bitcoin.ECPair.makeRandom({ rng: rng })
    var address = keyPair.getAddress()

    assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64')
  })

  it('can generate an address from a SHA256 hash', function () {
    var hash = bitcoin.crypto.sha256('correct horse battery staple')
    var d = bigi.fromBuffer(hash)

    var keyPair = new bitcoin.ECPair(d)
    var address = keyPair.getAddress()

    assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8')
  })

  it('can generate a random keypair for alternative networks', function () {
    // for testing only
    function rng () { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') }

    var litecoin = bitcoin.networks.litecoin

    var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng })
    var wif = keyPair.toWIF()
    var address = keyPair.getAddress()

    assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn')
    assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS')
  })

  it('can import an address via WIF', function () {
    var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct')
    var address = keyPair.getAddress()

    assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31')
  })

  it('can create a Transaction', function () {
    var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
    var tx = new bitcoin.TransactionBuilder()

    tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0)
    tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000)
    tx.sign(0, keyPair)

    assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000')
  })

  it('can create a [complex] Transaction', function (done) {
    this.timeout(30000)

    var network = bitcoin.networks.testnet
    var alice = bitcoin.ECPair.makeRandom({ network: network })
    var bob = bitcoin.ECPair.makeRandom({ network: network })
    var alicesAddress = alice.getAddress()
    var bobsAddress = bob.getAddress()

    blockchain.t.faucet(alicesAddress, 2e4, function (err, unspentA) {
      if (err) return done(err)

      blockchain.t.faucet(bobsAddress, 2e4, function (err, unspentB) {
        if (err) return done(err)

        var tx = new bitcoin.TransactionBuilder(network)
        tx.addInput(unspentA.txId, unspentA.vout)
        tx.addInput(unspentB.txId, unspentB.vout)
        tx.addOutput('mrCDrCybB6J1vRfbwM5hemdJz73FwDBC8r', 1e4)
        tx.addOutput('2NByiBUaEXrhmqAsg7BbLpcQSAQs1EDwt5w', 1e4)
        tx.sign(0, alice)
        tx.sign(1, bob)

        blockchain.t.transactions.propagate(tx.build().toHex(), done)
      })
    })
  })
})
<|endoftext|>


<commit_before>var Publish = function(manifest, adapter) {
    this.manifest = manifest;
    this.adapter = adapter;
};

Publish.prototype.handle = function() {
    this.manifest.localFiles()
        .then(this.manifest.transposeWithMD5.bind(this.manifest))
        .then(this.manifest.filterInManifest.bind(this.manifest))
        .then(this.adapter.filterExisting.bind(this.adapter))
        .then(this.adapter.transposeVersions.bind(this.adapter))
        .then(this.adapter.upload.bind(this.adapter))
        .then(this.adapter.renameUploadedFiles.bind(this.adapter))
        // @todo update manifest file
        .then(function(updated) {
            console.log('Uploaded:');
            updated.forEach(function(entry) {
                console.log('%s --> %s', entry.originalName, entry.name);
            });
            console.log(JSON.stringify(updated, null, 4));
        })
        .catch(function(e) {
            console.error(e.message);
            process.exit(1);
        })
        .done(function() {
            console.log('\nPublish complete');
        });
};

module.exports = Publish;
module.exports.$name = 'command.publish';
module.exports.$type = 'service';
module.exports.$inject = ['manifest', 'adapter'];
<commit_msg>Add manifest update to publish pipeline.<commit_after>var Publish = function(manifest, adapter) {
    this.manifest = manifest;
    this.adapter = adapter;
};

Publish.prototype.handle = function() {
    this.manifest.localFiles()
        .then(this.manifest.transposeWithMD5.bind(this.manifest))
        .then(this.manifest.filterInManifest.bind(this.manifest))
        .then(this.adapter.filterExisting.bind(this.adapter))
        .then(this.adapter.transposeVersions.bind(this.adapter))
        .then(this.adapter.upload.bind(this.adapter))
        .then(this.adapter.renameUploadedFiles.bind(this.adapter))
        .then(this.manifest.update.bind(this.manifest))
        .then(function(updated) {
            console.log('Uploaded:');
            updated.forEach(function(entry) {
                console.log('%s --> %s', entry.originalName, entry.name);
            });
            console.log(JSON.stringify(updated, null, 4));
        })
        .catch(function(e) {
            console.error(e.message);
            process.exit(1);
        })
        .done(function() {
            console.log('\nPublish complete');
        });
};

module.exports = Publish;
module.exports.$name = 'command.publish';
module.exports.$type = 'service';
module.exports.$inject = ['manifest', 'adapter'];
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var http = require('http');
http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain; charset=UTF-8'
    });

    res.end('Hello from Aethernaut-Server.\n');

}).listen(9080, "");
<commit_msg>Delete Aethernaut-Server.js<commit_after><|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const getTagVersion = require('../../src/get-tag-version');

describe('Integration - getTagVersion', function() {
  this.timeout(10000);

  it('works', function() {
    expect(getTagVersion('beta')).to.not.be.empty;
    expect(getTagVersion('latest')).to.not.be.empty;
  });
});
<commit_msg>check for valid semver strings<commit_after>'use strict';

const expect = require('chai').expect;
const getTagVersion = require('../../src/get-tag-version');
const semver = require('semver');

describe('Integration - getTagVersion', function() {
  this.timeout(10000);

  it('works', function() {
    expect(semver.valid(getTagVersion('beta'))).to.not.be.null;
    expect(semver.valid(getTagVersion('latest'))).to.not.be.null;
  });
});
<|endoftext|>


<commit_before>// @flow
import * as options from '../utils/options';
import * as logger from '../utils/logger';
import * as messages from '../utils/messages';
import {
  publish as publishUtil,
  type PublishOptions,
  type PackageMeta
} from '../utils/publish';
import { BoltError } from '../../dist/modern/utils/errors';

export function toPublishOptions(
  args: options.Args,
  flags: options.Flags
): PublishOptions {
  return {
    cwd: options.string(flags.cwd, 'cwd'),
    access: options.string(flags.access, 'access')
  };
}

function partition(collection, predicate = x => x): PackageMeta[][] {
  return collection.reduce(
    ([a, b], value) => {
      (predicate(value) ? a : b).push(value);
      return [a, b];
    },
    [[], []]
  );
}

export async function publish(opts: PublishOptions) {
  const response: PackageMeta[] = await publishUtil(opts);

  const [successful, unsuccessful] = partition(response, p => p.published);

  for (const pkg of successful) {
    logger.success(
      messages.successfullyPublishedPackage(pkg.name, pkg.newVersion)
    );
  }

  for (const pkg of unsuccessful) {
    logger.error(messages.failedToPublishPackage(pkg.name));
  }

  if (unsuccessful.length > 0) {
    throw new BoltError(
      `Failed to publish ${unsuccessful.length} ${unsuccessful.length === 1
        ? 'package'
        : 'packages'}`
    );
  }
}
<commit_msg>Fixes incorrect import in publishCommand<commit_after>// @flow
import * as options from '../utils/options';
import * as logger from '../utils/logger';
import * as messages from '../utils/messages';
import {
  publish as publishUtil,
  type PublishOptions,
  type PackageMeta
} from '../utils/publish';
import { BoltError } from '../utils/errors';

export function toPublishOptions(
  args: options.Args,
  flags: options.Flags
): PublishOptions {
  return {
    cwd: options.string(flags.cwd, 'cwd'),
    access: options.string(flags.access, 'access')
  };
}

function partition(collection, predicate = x => x): PackageMeta[][] {
  return collection.reduce(
    ([a, b], value) => {
      (predicate(value) ? a : b).push(value);
      return [a, b];
    },
    [[], []]
  );
}

export async function publish(opts: PublishOptions) {
  const response: PackageMeta[] = await publishUtil(opts);

  const [successful, unsuccessful] = partition(response, p => p.published);

  for (const pkg of successful) {
    logger.success(
      messages.successfullyPublishedPackage(pkg.name, pkg.newVersion)
    );
  }

  for (const pkg of unsuccessful) {
    logger.error(messages.failedToPublishPackage(pkg.name));
  }

  if (unsuccessful.length > 0) {
    throw new BoltError(
      `Failed to publish ${unsuccessful.length} ${unsuccessful.length === 1
        ? 'package'
        : 'packages'}`
    );
  }
}
<|endoftext|>


<commit_before>(function() {

  $.fn.timeago.defaults.lang = {
    units: {
        second: "Sekunde",
        seconds: "Sekunden",
        minute: "Minute",
        minutes: "Minuten",
        hour: "Stunde",
        hours: "Stunden",
        day: "Tag",
        days: "Tagen",
        month: "Monat",
        months: "Monaten",
        year: "Jahr",
        years: "Jahren",
    },
    prefixes: {
      lt: "weniger als eine",
      about: "ungefähr",
      over: "über",
      almost: "fast",
      ago: "vor "
    },
    suffix: ""
  };

}).call(this);
<commit_msg>Generate timeago.de.js by coffee.<commit_after>(function() {

  $.fn.timeago.defaults.lang = {
    units: {
      second: "Sekunde",
      seconds: "Sekunden",
      minute: "Minute",
      minutes: "Minuten",
      hour: "Stunde",
      hours: "Stunden",
      day: "Tag",
      days: "Tagen",
      month: "Monat",
      months: "Monaten",
      year: "Jahr",
      years: "Jahren"
    },
    prefixes: {
      lt: "weniger als eine",
      about: "ungerfähr",
      over: "über",
      almost: "fast",
      ago: "vor "
    },
    suffix: ""
  };

}).call(this);
<|endoftext|>


<commit_before>import MetaInspector from 'node-metainspector';
import PlayerActions from '../actions';

var linker = {};

linker.isSupportedLink = link => {

    if (link.indexOf('youtube.com/watch?v=') > -1) {
        return true;
    }

    if (link.indexOf('vimeo.com/') > -1) {

        var simpler = link.substr(link.indexOf('vimeo.com/')+10);

        if (simpler.indexOf('?') > -1) {
            simpler = simpler.substr(0, simpler.indexOf('?'));
        }

        if (simpler.indexOf('#') > -1) {
            simpler = simpler.substr(0, simpler.indexOf('#'));
        }

        if (!isNaN(simpler)) return true;

    }

    if (link.indexOf('soundcloud.com') > -1) {

        if (link.indexOf('?q=') > -1) return false;

        if (link.indexOf('/search/') > -1) return false;

        if (link.indexOf('/groups/') > -1) return false;

        if (link.indexOf('/popular/') > -1) return false;

        if ((link.match(/\//g) || []).length == 4) return true;

        if ((link.match(/\//g) || []).length == 5 && link.indexOf('/sets/')) return true;

    }

    return false;
};

linker.iframeToLink = el => {

    if (el.indexOf('youtube.com/embed/') > -1) {
        el = el.substr(el.indexOf('youtube.com/embed/')+18);
        if (el.indexOf('?') > -1) {
            el = el.substr(0,el.indexOf('?'));
        }
        el = 'https://www.youtube.com/watch?v='+el;
    }

    if (el.indexOf('player.vimeo.com/video/') > -1) {
        el = el.substr(el.indexOf('player.vimeo.com/video')+23);
        if (el.indexOf('?') > -1) {
            el = el.substr(0,el.indexOf('?'));
        }
        el = 'https://vimeo.com/'+el;
    }

    return el;

};

linker.handleURL = (parsed, cb) => {
//    console.log(parsed.url);
    if (!linker.isSupportedLink(parsed.url)) {

        var client = new MetaInspector(parsed.url, { timeout: 5000 });

        client.on("fetch", function(){

//            console.log(client);

            var newFiles = [];
            var noDupes = [];
            var links = [];

            if (client.links.absolute) {
                if (client.links.absolute.http && client.links.absolute.https) {
                    links = client.links.absolute.http.concat(client.links.absolute.https);
                } else if (client.links.absolute.http) {
                    links = client.links.absolute.http;
                } else if (client.links.absolute.https) {
                    links = client.links.absolute.https;
                }
            }

            var iframes = client.iframes;

            var queueParser = [];

            links.forEach( (el, ij) => {
                if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {
                    queueParser.push({
                        idx: ij,
                        url: el
                    });
                    newFiles.push({
                        uri: el
                    });
                }
                noDupes.push(el);
            });

            client.host = client.host.replace('www.','');

            if (['soundcloud.com', 'youtube.com', 'vimeo.com'].indexOf(client.host) > -1) {
                var relatives = client.links.relative;
                relatives.forEach( (el, ij) => {
                    el = 'https://'+client.host+el;
//                    console.log(el);
                    if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {
//                        console.log("ADDING: "+el);
                        queueParser.push({
                            idx: ij,
                            url: el
                        });
                        newFiles.push({
                            uri: el
                        });
                    }
                    noDupes.push(el);
                });
            }

            iframes.forEach( (el, ij) => {

                el = linker.iframeToLink(el);

                if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {
                    queueParser.push({
                        idx: ij,
                        url: el
                    });
                    newFiles.push({
                        uri: el
                    });
                }
                noDupes.push(el);
            });

            cb(newFiles, queueParser);

        });

        client.on("error", function(err){
            cb([], []);
        });

        client.fetch();

    } else {
        PlayerActions.addPlaylist([{
            uri: parsed.url,
            title: parsed.title
        }]);
    }
};

module.exports = linker;
<commit_msg>suported links to es6 class<commit_after>import MetaInspector from 'node-metainspector';
import Promice from 'bluebird';
import PlayerActions from '../actions';

class supportedLinks {
    isSupportedLink(link) {

        if (link.includes('youtube.com/watch?v=')) {
            return true;
        }

        if (link.includes('vimeo.com/')) {

            var simpler = link.substr(link.includes('vimeo.com/'));

            if (simpler.includes('?')) {
                simpler = simpler.substr(0, simpler.includes('?'));
            }

            if (simpler.includes('#')) {
                simpler = simpler.substr(0, simpler.includes('#'));
            }

            if (!isNaN(simpler)) return true;

        }

        if (link.includes('soundcloud.com')) {

            if (link.includes('?q=')) return false;

            if (link.includes('/search/')) return false;

            if (link.includes('/groups/')) return false;

            if (link.includes('/popular/')) return false;

            if ((link.match(/\//g) || []).length == 4) return true;

            if ((link.match(/\//g) || []).length == 5 && link.includes('/sets/')) return true;

        }

        return false;
    }

    iframeToLink(el) {

        if (el.includes('youtube.com/embed/')) {
            el = el.substr(el.indexOf('youtube.com/embed/') + 18);
            if (el.includes('?')) {
                el = el.substr(0, el.includes('?'));
            }
            el = 'https://www.youtube.com/watch?v=' + el;
        }

        if (el.includes('player.vimeo.com/video/')) {
            el = el.substr(el.indexOf('player.vimeo.com/video') + 23);
            if (el.includes('?')) {
                el = el.substr(0, el.includes('?'));
            }
            el = 'https://vimeo.com/' + el;
        }

        return el;
    }

    handleURL(parsed) {
        return new Promise((resolve, reject) => {
            if (!linker.isSupportedLink(parsed.url)) {

                var client = new MetaInspector(parsed.url, {
                    timeout: 5000
                });

                client.on("fetch", () => {
                    var newFiles = [];
                    var noDupes = [];
                    var links = [];

                    if (client.links.absolute) {
                        if (client.links.absolute.http && client.links.absolute.https) {
                            links = client.links.absolute.http.concat(client.links.absolute.https);
                        } else if (client.links.absolute.http) {
                            links = client.links.absolute.http;
                        } else if (client.links.absolute.https) {
                            links = client.links.absolute.https;
                        }
                    }

                    var iframes = client.iframes;

                    var queueParser = [];

                    links.forEach((el, ij) => {
                        if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {
                            queueParser.push({
                                idx: ij,
                                url: el
                            });
                            newFiles.push({
                                uri: el
                            });
                        }
                        noDupes.push(el);
                    });

                    client.host = client.host.replace('www.', '');

                    if (['soundcloud.com', 'youtube.com', 'vimeo.com'].includes(client.host)) {
                        var relatives = client.links.relative;
                        relatives.forEach((el, ij) => {
                            el = 'https://' + client.host + el;

                            if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {

                                queueParser.push({
                                    idx: ij,
                                    url: el
                                });
                                newFiles.push({
                                    uri: el
                                });
                            }
                            noDupes.push(el);
                        });
                    }

                    iframes.forEach((el, ij) => {

                        el = linker.iframeToLink(el);

                        if (noDupes.indexOf(el) == -1 && linker.isSupportedLink(el)) {
                            queueParser.push({
                                idx: ij,
                                url: el
                            });
                            newFiles.push({
                                uri: el
                            });
                        }
                        noDupes.push(el);
                    });
                    resolve([newFiles, queueParser]);

                });

                client.on("error", reject);

                client.fetch();

            } else {
                PlayerActions.addPlaylist([{
                    uri: parsed.url,
                    title: parsed.title
                }]);
            }
        });
    }
}

export
default supportedLinks;<|endoftext|>


<commit_before>Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';

Ext.namespace(
'Kwf', 'Kwc',
'Kwf.Component',
'Kwf.User.Login',
'Kwf.Auto',
'Kwf.Form',
'Kwf.Binding',
'Kwc.Advanced',
'Kwf.Debug',
'Kwf.Switch',
'Kwf.Basic.LinkTag.Extern',
'Kwf.Layout',
'Kwf.Utils'
);

Ext.applyIf(Array.prototype, {

    //deprecated! -> forEach (ist auch ein JS-Standard!)
    each : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //to use array.forEach directly
    forEach : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //add is alias for push
    add : function() {
        this.push.apply(this, arguments);
    },

    //+ Jonas Raoni Soares Silva
    //@ http://jsfromhell.com/array/shuffle [rev. #1]
    shuffle : function() {
        for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
    }
});

Ext.applyIf(Function.prototype, {

    interceptResult: function(fcn, scope) {
        if(typeof fcn != "function"){
            return this;
        }
        var method = this;
        var interception=function() {
            var retval = method.apply(this || window, arguments);
            var callArgs = Array.prototype.slice.call(arguments, 0);
            var args=[retval].concat(callArgs);
            var newRetval=fcn.apply(scope || this || window, args);
            return newRetval;
        };
        if (this.prototype){
            Ext.apply(interception.prototype, this.prototype);
            if (this.superclass){ interception.superclass=this.superclass; }
            if (this.override){ interception.override=this.override; }
        }
        return interception;
    }
});

//http://extjs.com/forum/showthread.php?t=26644
Kwf.clone = function(o) {
    if('object' !== typeof o || o === null) {
        return o;
    }
    var c = 'function' === typeof o.pop ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if('object' === typeof v && v !== null) {
                c[p] = Kwf.clone(v);
            }
            else {
                c[p] = v;
            }
        }
    }
    return c;
};

Ext.onReady(function()
{
//     Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    if (Ext.QuickTips) {
        Ext.QuickTips.init();
    }

    if (Ext.isIE6) {
        Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
            var extEl = Ext.fly(el);
            extEl.hover(
                function() { this.addClass('hover'); },
                function() { this.removeClass('hover'); },
                extEl
            );
        });
    }
});

Kwf.application = { maxAssetsMTime: '{$application.maxAssetsMTime}' };

//log das auch ohne irgendwelche abh�nigkeiten funktioniert (zB im Selenium)
Kwf.log = function(msg) {
    if (!Kwf.debugDiv) {
        Kwf.debugDiv = document.createElement('div');
        document.body.appendChild(Kwf.debugDiv);
        Kwf.debugDiv.style.position = 'absolute';
        Kwf.debugDiv.style.zIndex = '300';
        Kwf.debugDiv.style.top = 0;
        Kwf.debugDiv.style.right = 0;
        Kwf.debugDiv.style.backgroundColor = 'white';
        Kwf.debugDiv.style.fontSize = '10px';
    }
    Kwf.debugDiv.innerHTML += msg+'
';
};

//wird gesetzt in Kwf.Connection
Kwf.requestSentSinceLastKeepAlive = false;
Kwf.keepAlive = function() {
    if (!Kwf.requestSentSinceLastKeepAlive) {
        Ext.Ajax.request({
            url: '/kwf/user/login/json-keep-alive',
            ignoreErrors: true
        });
    } else {
        Kwf.requestSentSinceLastKeepAlive = false;
    }
    Kwf.keepAlive.defer(1000 * 60 * 5);
};

Kwf.keepAliveActivated = false;
Kwf.activateKeepAlive = function() {
    if (Kwf.keepAliveActivated) return;
    Kwf.keepAliveActivated = true;
    Kwf.keepAlive.defer(1000 * 60 * 5);
};

if (Kwf.isApp) {
    Kwf.activateKeepAlive();
}

Kwf.contentReadyHandlers = [];
Kwf.onContentReady = function(fn, scope) {
    Kwf.contentReadyHandlers.push({
        fn: fn,
        scope: scope
    });
};

Kwf.callOnContentReady = function(el, options) {
    if (!options) options = {};
    Ext.each(Kwf.contentReadyHandlers, function(i) {
        i.fn.call(i.scope | window, (el || document.body), options);
    }, this);
};

if (!Kwf.isApp) {
    Ext.onReady(function() {
        Kwf.callOnContentReady(document.body, { newRender: true });
    });
}

Kwf.include =  function(url, restart)
{
    if (url.substr(-4) == '.css') {
        var s = document.createElement('link');
        s.setAttribute('type', 'text/css');
        s.setAttribute('href', url+'?'+Math.random());
        s.setAttribute('rel', 'stylesheet');
    } else {
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', url+'?'+Math.random());
    }
    s.onload = function () {
        if (restart) Kwf.restart();
    };
    document.getElementsByTagName("head")[0].appendChild(s);
};

Kwf.restart = function()
{
    Ext.getBody().unmask();
    if (Kwf.currentViewport) {
        Kwf.currentViewport.onDestroy();
        delete Kwf.currentViewport;
    }
    Kwf.main();
};

var restart = Kwf.restart;
var include = Kwf.include;
<commit_msg>fix typo<commit_after>Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';

Ext.namespace(
'Kwf', 'Kwc',
'Kwf.Component',
'Kwf.User.Login',
'Kwf.Auto',
'Kwf.Form',
'Kwf.Binding',
'Kwc.Advanced',
'Kwf.Debug',
'Kwf.Switch',
'Kwf.Basic.LinkTag.Extern',
'Kwf.Layout',
'Kwf.Utils'
);

Ext.applyIf(Array.prototype, {

    //deprecated! -> forEach (ist auch ein JS-Standard!)
    each : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //to use array.forEach directly
    forEach : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //add is alias for push
    add : function() {
        this.push.apply(this, arguments);
    },

    //+ Jonas Raoni Soares Silva
    //@ http://jsfromhell.com/array/shuffle [rev. #1]
    shuffle : function() {
        for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
    }
});

Ext.applyIf(Function.prototype, {

    interceptResult: function(fcn, scope) {
        if(typeof fcn != "function"){
            return this;
        }
        var method = this;
        var interception=function() {
            var retval = method.apply(this || window, arguments);
            var callArgs = Array.prototype.slice.call(arguments, 0);
            var args=[retval].concat(callArgs);
            var newRetval=fcn.apply(scope || this || window, args);
            return newRetval;
        };
        if (this.prototype){
            Ext.apply(interception.prototype, this.prototype);
            if (this.superclass){ interception.superclass=this.superclass; }
            if (this.override){ interception.override=this.override; }
        }
        return interception;
    }
});

//http://extjs.com/forum/showthread.php?t=26644
Kwf.clone = function(o) {
    if('object' !== typeof o || o === null) {
        return o;
    }
    var c = 'function' === typeof o.pop ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if('object' === typeof v && v !== null) {
                c[p] = Kwf.clone(v);
            }
            else {
                c[p] = v;
            }
        }
    }
    return c;
};

Ext.onReady(function()
{
//     Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    if (Ext.QuickTips) {
        Ext.QuickTips.init();
    }

    if (Ext.isIE6) {
        Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
            var extEl = Ext.fly(el);
            extEl.hover(
                function() { this.addClass('hover'); },
                function() { this.removeClass('hover'); },
                extEl
            );
        });
    }
});

Kwf.application = { maxAssetsMTime: '{$application.maxAssetsMTime}' };

//log das auch ohne irgendwelche abh�nigkeiten funktioniert (zB im Selenium)
Kwf.log = function(msg) {
    if (!Kwf.debugDiv) {
        Kwf.debugDiv = document.createElement('div');
        document.body.appendChild(Kwf.debugDiv);
        Kwf.debugDiv.style.position = 'absolute';
        Kwf.debugDiv.style.zIndex = '300';
        Kwf.debugDiv.style.top = 0;
        Kwf.debugDiv.style.right = 0;
        Kwf.debugDiv.style.backgroundColor = 'white';
        Kwf.debugDiv.style.fontSize = '10px';
    }
    Kwf.debugDiv.innerHTML += msg+'
';
};

//wird gesetzt in Kwf.Connection
Kwf.requestSentSinceLastKeepAlive = false;
Kwf.keepAlive = function() {
    if (!Kwf.requestSentSinceLastKeepAlive) {
        Ext.Ajax.request({
            url: '/kwf/user/login/json-keep-alive',
            ignoreErrors: true
        });
    } else {
        Kwf.requestSentSinceLastKeepAlive = false;
    }
    Kwf.keepAlive.defer(1000 * 60 * 5);
};

Kwf.keepAliveActivated = false;
Kwf.activateKeepAlive = function() {
    if (Kwf.keepAliveActivated) return;
    Kwf.keepAliveActivated = true;
    Kwf.keepAlive.defer(1000 * 60 * 5);
};

if (Kwf.isApp) {
    Kwf.activateKeepAlive();
}

Kwf.contentReadyHandlers = [];
Kwf.onContentReady = function(fn, scope) {
    Kwf.contentReadyHandlers.push({
        fn: fn,
        scope: scope
    });
};

Kwf.callOnContentReady = function(el, options) {
    if (!options) options = {};
    Ext.each(Kwf.contentReadyHandlers, function(i) {
        i.fn.call(i.scope || window, (el || document.body), options);
    }, this);
};

if (!Kwf.isApp) {
    Ext.onReady(function() {
        Kwf.callOnContentReady(document.body, { newRender: true });
    });
}

Kwf.include =  function(url, restart)
{
    if (url.substr(-4) == '.css') {
        var s = document.createElement('link');
        s.setAttribute('type', 'text/css');
        s.setAttribute('href', url+'?'+Math.random());
        s.setAttribute('rel', 'stylesheet');
    } else {
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', url+'?'+Math.random());
    }
    s.onload = function () {
        if (restart) Kwf.restart();
    };
    document.getElementsByTagName("head")[0].appendChild(s);
};

Kwf.restart = function()
{
    Ext.getBody().unmask();
    if (Kwf.currentViewport) {
        Kwf.currentViewport.onDestroy();
        delete Kwf.currentViewport;
    }
    Kwf.main();
};

var restart = Kwf.restart;
var include = Kwf.include;
<|endoftext|>


<commit_before>'use strict';

(function() {
  var app = angular.module('pnc', [
    'ui.router',
    'pnc.Dashboard',
    'pnc.remote',
    'pnc.product',
    'pnc.project',
    'pnc.configuration'

  ]);

  app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
    function($stateProvider, $urlRouterProvider, $locationProvider) {

      $locationProvider.html5Mode(false).hashPrefix('!');

      $stateProvider.state('error', {
        url: '/error',
        views: {
          'content@': {
            templateUrl: 'error.html'
          }
        }
      });

      // Redirect any unmatched URLs to the error state.
      $urlRouterProvider.otherwise('/error');
    }
  ]);
})();
<commit_msg>Added logging for state change errors to<commit_after>'use strict';

(function() {
  var app = angular.module('pnc', [
    'ui.router',
    'pnc.Dashboard',
    'pnc.remote',
    'pnc.product',
    'pnc.project',
    'pnc.configuration'

  ]);

  app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
    function($stateProvider, $urlRouterProvider, $locationProvider) {

      $locationProvider.html5Mode(false).hashPrefix('!');

      $stateProvider.state('error', {
        url: '/error',
        views: {
          'content@': {
            templateUrl: 'error.html'
          }
        }
      });

      // Redirect any unmatched URLs to the error state.
      $urlRouterProvider.otherwise('/error');
    }
  ]);

  app.run(['$rootScope', '$log',
    function($rootScope, $log) {
      $rootScope.$on('$stateChangeError',
        function(event, toState, toParams, fromState, fromParams, error) {
          $log.debug('Caught $stateChangeError: arguments=%O', arguments);
        }
      );
    }
  ]);

})();
<|endoftext|>