<commit_before>'use strict';

//const gt = require('./../modules/gettext');
const SpecialRightIndex = require('./../api/specialrights/index');

exports = module.exports = function(params) {
    
    let mongoose = params.mongoose;
    
	let rightSchema = new params.mongoose.Schema({
		name: { type: String, unique: true, required: true },
        description: String,
		timeCreated: { type: Date, default: Date.now },
        type: { type: mongoose.Schema.Types.ObjectId, ref: 'Type' },
        require_approval: { type: Boolean, default:true },
        sortkey: Number,
        
        special: { type: String },                               // quantity evaluation rule used instead of the default quantity
                                                                 // name will be readonly
                                                                 // special rights are stored in api/specialrights/*
                                                                 // proposed special rights will be filtered by company.country

        consuption: {                                            // consuption type
            type: String,
            enum:['proportion', 'businessDays', 'workingDays'],  // proportion: user the attendance percentage defined in user right collection
                                                                 // businessDays: next business days are consumed up to consuptionBusinessDaysLimit
            default: 'proportion'                                // workingDays: full working days are consumed
        },

        consuptionBusinessDaysLimit: { type: Number, default: 5 }, // Used if consuption=businessDays

        // automatic distribution on this right on request creation
        autoDistribution: { type: Boolean, default:true },
        
        quantity: { type: Number, min:0 },                          // initial quantity for each renewal
                                                                    // this can be overwritten by special quantity from a custom rule (ex: RTT)

        quantity_unit: { type: String, enum:['D', 'H'], required: true },   // Days our Hours
        
        /**
         * Add "quantity" every first day of month
         * on each modification of the right, an array of rightAdjustments will be created in renewal
         * from the current date to once the "max" quantity is reached or to the renewal date
         * The adjustments array should be updated if new renewal is added or removed or if the right
         * is modified but only for futur adjustments
         */
        addMonthly: {
            quantity: { type: Number, min:0 },
            max: { type: Number, min:0 }
        },
        
        timeSaving: {
            active: { type: Boolean, default: false },              // The right quantity can be saved to CET or not
            max: { type: Number, min:1 }                            // max saveable quantity from renewal
        },

        timeSavingAccount: {                                        // used only if special==='timesavingaccount'
            max: { type: Number, min:1 },                           // max saveable quantity into renewal
            savingInterval: {
                useDefault: { type: Boolean, default: true },       // default saving interval is the renewal period
                min: Number,                                        // years before renewal start date
                max: Number                                         // years before renewal end date
            }
        },

        activeFor: {
            account: { type: Boolean, default:true },
            
            // manager substituting one of his subordinate
            manager: { type: Boolean, default:true },
            
            // admin substituting one of the user with vacation account
            admin: { type: Boolean, default:true }
        },
        
        // activeSpan.min minimal number of days between entry date and request start date
        // this is the time given to the approvers
        // activeSpan.max maximal number of days between entry date and request end date
        // by default, the parameter is set globally
        activeSpan: {
            useDefault: { type: Boolean, default:true },
            min: Number,
            max: Number
        },

        rules: [params.embeddedSchemas.RightRule]
	});
    
    
    rightSchema.index({ 'name': 1 }, { unique: true });
	rightSchema.set('autoIndex', params.autoIndex);

    
    /**
     * Pre save hook
     */
    rightSchema.pre('save', function(next) {
        // set monthly adjustments from today
        this.updateAdjustments(next);

    });

    /**
     * Pre remove hook
     */
    rightSchema.pre('remove', function(next) {
        next();

        let promises = [];

        promises.push(this.removeRenewals());
        promises.push(this.removeBeneficiaries());

        Promise.all(promises).then(() => {
            next();
        }).catch(next);
    });


    /**
     * delete all renewals linked to this right
     * remove on model have no query hook so it not used here because we may have to chain multiple pre remove middlewares
     * @return {Promise}
     */
    rightSchema.methods.removeRenewals = function() {
        let RightRenewal = this.model('RightRenewal');

        return RightRenewal.find()
        .where('right').is(this._id)
        .exec()
        .then(renewals => {
            let removePromises = [];<commit_msg>fix pre remove next call<commit_after>'use strict';

//const gt = require('./../modules/gettext');
const SpecialRightIndex = require('./../api/specialrights/index');

exports = module.exports = function(params) {
    
    let mongoose = params.mongoose;
    
	let rightSchema = new params.mongoose.Schema({
		name: { type: String, unique: true, required: true },
        description: String,
		timeCreated: { type: Date, default: Date.now },
        type: { type: mongoose.Schema.Types.ObjectId, ref: 'Type' },
        require_approval: { type: Boolean, default:true },
        sortkey: Number,
        
        special: { type: String },                               // quantity evaluation rule used instead of the default quantity
                                                                 // name will be readonly
                                                                 // special rights are stored in api/specialrights/*
                                                                 // proposed special rights will be filtered by company.country

        consuption: {                                            // consuption type
            type: String,
            enum:['proportion', 'businessDays', 'workingDays'],  // proportion: user the attendance percentage defined in user right collection
                                                                 // businessDays: next business days are consumed up to consuptionBusinessDaysLimit
            default: 'proportion'                                // workingDays: full working days are consumed
        },

        consuptionBusinessDaysLimit: { type: Number, default: 5 }, // Used if consuption=businessDays

        // automatic distribution on this right on request creation
        autoDistribution: { type: Boolean, default:true },
        
        quantity: { type: Number, min:0 },                          // initial quantity for each renewal
                                                                    // this can be overwritten by special quantity from a custom rule (ex: RTT)

        quantity_unit: { type: String, enum:['D', 'H'], required: true },   // Days our Hours
        
        /**
         * Add "quantity" every first day of month
         * on each modification of the right, an array of rightAdjustments will be created in renewal
         * from the current date to once the "max" quantity is reached or to the renewal date
         * The adjustments array should be updated if new renewal is added or removed or if the right
         * is modified but only for futur adjustments
         */
        addMonthly: {
            quantity: { type: Number, min:0 },
            max: { type: Number, min:0 }
        },
        
        timeSaving: {
            active: { type: Boolean, default: false },              // The right quantity can be saved to CET or not
            max: { type: Number, min:1 }                            // max saveable quantity from renewal
        },

        timeSavingAccount: {                                        // used only if special==='timesavingaccount'
            max: { type: Number, min:1 },                           // max saveable quantity into renewal
            savingInterval: {
                useDefault: { type: Boolean, default: true },       // default saving interval is the renewal period
                min: Number,                                        // years before renewal start date
                max: Number                                         // years before renewal end date
            }
        },

        activeFor: {
            account: { type: Boolean, default:true },
            
            // manager substituting one of his subordinate
            manager: { type: Boolean, default:true },
            
            // admin substituting one of the user with vacation account
            admin: { type: Boolean, default:true }
        },
        
        // activeSpan.min minimal number of days between entry date and request start date
        // this is the time given to the approvers
        // activeSpan.max maximal number of days between entry date and request end date
        // by default, the parameter is set globally
        activeSpan: {
            useDefault: { type: Boolean, default:true },
            min: Number,
            max: Number
        },

        rules: [params.embeddedSchemas.RightRule]
	});
    
    
    rightSchema.index({ 'name': 1 }, { unique: true });
	rightSchema.set('autoIndex', params.autoIndex);

    
    /**
     * Pre save hook
     */
    rightSchema.pre('save', function(next) {
        // set monthly adjustments from today
        this.updateAdjustments(next);

    });

    /**
     * Pre remove hook
     */
    rightSchema.pre('remove', function(next) {
        let right = this;

        let promises = [];

        promises.push(right.removeRenewals());
        promises.push(right.removeBeneficiaries());

        Promise.all(promises).then(() => {
            next();
        }).catch(next);
    });


    /**
     * delete all renewals linked to this right
     * remove on model have no query hook so it not used here because we may have to chain multiple pre remove middlewares
     * @return {Promise}
     */
    rightSchema.methods.removeRenewals = function() {

        let right = this;

        let RightRenewal = right.model('RightRenewal');

        return RightRenewal.find()
        .where('right').is(right._id)
        .exec()
        .then(renewals => {
            let removePromises = [];
{'fraction_non_alphanumeric': 0.0882379450202794, 'fraction_numerical': 0.0012618296529968455, 'mean_word_length': 1.5024808299503833, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 46, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4284665', 'n_tokens_mistral': 2567, 'n_tokens_neox': 2440, 'n_words': 907}