[SOLVED] Product upgrading by groovy script

Any issue about Cyclos 4 scripting and Webservices

Moderators: alexandre, hugo, rmvanarkel

Post Reply
erich.manser
Posts: 24
Joined: Tue Nov 08, 2022 10:40 am

[SOLVED] Product upgrading by groovy script

Post by erich.manser »

Hello everybody,

we are in a development phase, where we often have to restore a database from production environment and the set permissions by hand, since they are not in the production environment. The changes are so many, that we decided to make a script to update the products:

Code: Select all

import org.cyclos.impl.users.ProductServiceLocal
import org.cyclos.impl.utils.jdbc.ScriptHelper
import org.cyclos.model.users.products.ProductQuery

def result = []

result << 'Adding Records to products:'

def scriptHelper = new ScriptHelper()
def productQuery = new ProductQuery()
def products = (productService as ProductServiceLocal).listEntities()
result << 'Products found: ' + products.size()


// Configuration array: one entry per product/network/record-type to change
def permissionRules = [
  [productInternalName: 'helpers', networkInternalName: 'austria', recordTypeInternalName: 'dD_chat',      enable: true,  view: true,  create: true,  edit: false,  remove: false],
  [productInternalName: 'helpers', networkInternalName: 'austria', recordTypeInternalName: 'dD_checklist', enable: true,  view: true,  create: false,  edit: false,  remove: false],
]

// Helper to format current permissions
def permissionsSummary = { rec ->
  if (!rec.isEnabled()) return ' ---'
  def tokens = ['Enabled']
  if (rec.isView()) {
    tokens << 'View'
    if (rec.isCreate()) tokens << 'Create'
    if (rec.isEdit())   tokens << 'Edit'
    if (rec.isRemove()) tokens << 'Remove'
  }
  tokens. Join(',')
}

// Fast lookup for rules by "product::network::recordType"
def rulesByKey = permissionRules.collectEntries { r ->
  [("${r.productInternalName}::${r.networkInternalName}::${r.recordTypeInternalName}".toString()): r]
}

// Explicitly typed set to avoid intersection-type issues
Set<String> productsWithRules = new LinkedHashSet<String>(
  permissionRules.collect { it.productInternalName?.toString() }.findAll { it }
)

// Helper to also set the underlying action/permission set (when present)
def applyActionSetIfSupported = { rec ->
  def actions = new LinkedHashSet()
  if (rec.isView())   actions << 'VIEW'
  if (rec.isCreate()) actions << 'CREATE'
  if (rec.isEdit())   actions << 'EDIT'
  if (rec.isRemove()) actions << 'REMOVE'

  // Try common setters / properties. If not present, no harm done.
  if (rec.respondsTo('setPermissions', Set)) {
    rec.setPermissions(actions); return true
  }
  if (rec.respondsTo('setActions', Set)) {
    rec.setActions(actions); return true
  }
  if (rec.hasProperty('permissions')) {
    rec.permissions = actions; return true
  }
  if (rec.hasProperty('actions')) {
    rec.actions = actions; return true
  }
  return false
}

products.each { product ->
  // Skip products without any matching rule
  if (!productsWithRules.contains(String.valueOf(product.internalName))) return

  String networkName = product.network.internalName
  // Skip if no rule for this product+network
  if (!permissionRules.any { it.productInternalName == product.internalName && it.networkInternalName == networkName }) return

  result << "Product: ${product.internalName} = ${product.name} für ${product.network.name} found"

  product.getMyRecordTypes().each { recordPermission ->
    def recordType = recordPermission.getRecordType()
    result << ".... Record: ${recordType.internalName}  current ${permissionsSummary(recordPermission)}"

    def ruleKey = "${product.internalName}::${networkName}::${recordType.internalName}"
    def rule = rulesByKey[ruleKey]
    if (rule) {

      if (rule.enable  != null) recordPermission.setEnabled(rule.enable as boolean)
      if (rule.view    != null) recordPermission.setView(rule.view as boolean)
      if (rule.create  != null) recordPermission.setCreate(rule.create as boolean)
      if (rule.edit    != null) recordPermission.setEdit(rule.edit as boolean)
      if (rule.remove  != null) recordPermission.setRemove(rule.remove as boolean)

      // Persist the underlying backing set when available
      def applied = applyActionSetIfSupported(recordPermission)
      if (!applied) {
        result << "...... Note: could not locate a backing permission-set property; flags may not persist."
      }

      result << "...... Changed: ${recordType.internalName}  now ${permissionsSummary(recordPermission)}"
    }
  }

}
// return result.join('\r\n')
When looking at the result everything seems to be fine. But when I check the permissions in cyclos,

Code: Select all

setEnable(true)
was done but

Code: Select all

setView(true)
was NOT set. Is there something that has to be done in between? I did not find a service that would help me with this.

I do get the "exception": Note: could not locate a backing permission-set property; flags may not persist.

If I run the script a second time, the current set shows, the changes were made.

My Cyclos is of 4.16.11

Any idea for this problem?
Thx Erich
Last edited by erich.manser on Tue Aug 19, 2025 6:58 am, edited 1 time in total.
erich.manser
Posts: 24
Joined: Tue Nov 08, 2022 10:40 am

Solution: Product upgrading by groovy script

Post by erich.manser »

I could get it done. When setting the view permission, there has to be at least one field set to view as well. Then the settings are recognized and set correctly. And cache has to be recreated.

The code now sets the same permission for all fields and recognizes fieldOverrides. It works fine and looks like this:

Code: Select all

import org.cyclos.impl.users.ProductServiceLocal
import org.cyclos.impl.utils.jdbc.ScriptHelper
import org.cyclos.model.users.products.ProductQuery

def result = []

result << 'Adding record permissions to products:'

def scriptHelper = new ScriptHelper()
def productQuery = new ProductQuery()
def products = (productService as ProductServiceLocal).listEntities()
result << 'Products found: ' + products.size()


// Configuration array: one entry per product/network/record-type to change
def permissionRules = [
  [
    productInternalName   : 'helpers',
    networkInternalName   : 'austria',
    recordTypeInternalName: 'dD_chat',
    enable                : true,
    view                  : true,
    create                : true,
    edit                  : false,
    remove                : false,
  ],
  [
    productInternalName   : 'helpers',
    networkInternalName   : 'austria',
    recordTypeInternalName: 'dD_checklist',
    enable                : true,
    view                  : true,
    create                : false,
    edit                  : false,
    remove                : false,
    fieldOverrides        : [
      // Hide only this field
      dD_only: [view: false],
      // Allow view + create, but disallow edit/remove for this field
//      dD_list: [view: true, create: true, edit: false, remove: false],
    ]
  ],
]

// Helper to format current permissions
def permissionsSummary = { rec ->
  if (!rec.isEnabled()) return ' ---'
  def tokens = ['Enabled']
  if (rec.isView()) {
    tokens << 'View'
    if (rec.isCreate()) tokens << 'Create'
    if (rec.isEdit()) tokens << 'Edit'
    if (rec.isRemove()) tokens << 'Remove'
  }
  tokens. Join(',')
}

// Fast lookup for rules by "product::network::recordType"
def rulesByKey = permissionRules.collectEntries { r ->
  [("${r.productInternalName}::${r.networkInternalName}::${r.recordTypeInternalName}".toString()): r]
}

// Explicitly typed set to avoid intersection-type issues
Set<String> productsWithRules = new LinkedHashSet<String>(
  permissionRules.collect { it.productInternalName?.toString() }.findAll { it }
)

products.each { product ->
  // Skip products without any matching rule
  if (!productsWithRules.contains(String.valueOf(product.internalName))) return

  String networkName = product.network.internalName
  // Skip if no rule for this product+network
  if (!permissionRules.any { it.productInternalName == product.internalName && it.networkInternalName == networkName }) return

  result << "Product: ${product.internalName} = ${product.name} for ${product.network.name} found"

  product.getMyRecordTypes().each { recordPermission ->
    def recordType = recordPermission.getRecordType()
    result << ".... Record: ${recordType.internalName}  current ${permissionsSummary(recordPermission)}"

    def ruleKey = "${product.internalName}::${networkName}::${recordType.internalName}"
    def rule = rulesByKey[ruleKey]
    if (!rule) return

    // 1) Enable/disable record
    if (rule.enable != null) recordPermission.setEnabled(rule.enable as boolean)

    // 2) Record-level permissions
    Boolean recView = (rule.view != null) ? (rule.view as boolean) : null
    Boolean recCreate = (rule.create != null) ? (rule.create as boolean) : null
    Boolean recEdit = (rule.edit != null) ? (rule.edit as boolean) : null
    Boolean recRemove = (rule.remove != null) ? (rule.remove as boolean) : null

    if (recView != null) recordPermission.setView(recView)
    // If record-level view was explicitly set to false, cascade others to false
    if (recView != null && !recView) {
      recordPermission.setCreate(false)
      recordPermission.setEdit(false)
      recordPermission.setRemove(false)
    } else {
      if (recCreate != null) recordPermission.setCreate(recCreate)
      if (recEdit != null) recordPermission.setEdit(recEdit)
      if (recRemove != null) recordPermission.setRemove(recRemove)
    }

    // 3) Field-level permissions with overrides
    def fieldOverrides = (rule.fieldOverrides instanceof Map) ? rule.fieldOverrides : [:]

    // Compute effective record-level gates for fields (fallback to current if not set in rule)
    boolean effRecView = (recView != null) ? recView : recordPermission.isView()
    boolean effRecCreate = (recCreate != null) ? recCreate : recordPermission.isCreate()
    boolean effRecEdit = (recEdit != null) ? recEdit : recordPermission.isEdit()
    boolean effRecRemove = (recRemove != null) ? recRemove : recordPermission.isRemove()

    recordPermission.getProductRecordCustomFields().each { field ->
      def name = field.customField.internalName
      def o = (fieldOverrides[name] instanceof Map) ? fieldOverrides[name] : [:]

      // Base = record-level rule if present; otherwise keep current
      Boolean baseView = (recView != null) ? recView : (field.respondsTo('isView') ? field.isView() : true)
      Boolean baseCreate = (recCreate != null) ? recCreate : (field.respondsTo('isCreate') ? field.isCreate() : true)
      Boolean baseEdit = (recEdit != null) ? recEdit : (field.respondsTo('isEdit') ? field.isEdit() : false)
      Boolean baseRemove = (recRemove != null) ? recRemove : (field.respondsTo('isRemove') ? field.isRemove() : false)

      // Apply overrides where provided
      Boolean fldView = (o.containsKey('view')) ? (o.view as boolean) : baseView
      Boolean fldCreate = (o.containsKey('create')) ? (o.create as boolean) : baseCreate
      Boolean fldEdit = (o.containsKey('edit')) ? (o.edit as boolean) : baseEdit
      Boolean fldRemove = (o.containsKey('remove')) ? (o.remove as boolean) : baseRemove

      // Field-level cascade: if field view is false, other rights become false
      if (!fldView) {
        fldCreate = false
        fldEdit = false
        fldRemove = false
      }

      // Do not exceed record-level permissions
      fldView = fldView && effRecView
      fldCreate = fldCreate && effRecView && effRecCreate
      fldEdit = fldEdit && effRecView && effRecEdit
      fldRemove = fldRemove && effRecView && effRecRemove

      // Apply to field
      if (field.respondsTo('setView')) field.setView(fldView)
      if (field.respondsTo('setCreate')) field.setCreate(fldCreate)
      if (field.respondsTo('setEdit')) field.setEdit(fldEdit)
      if (field.respondsTo('setRemove')) field.setRemove(fldRemove)

      result << ".......... Field ${name}: view=${fldView}, create=${fldCreate}, edit=${fldEdit}, remove=${fldRemove}"
    }

    result << "...... Changed: ${recordType.internalName}  now ${permissionsSummary(recordPermission)}"
  }
}
Post Reply